text
stringlengths 4
4.46M
| id
stringlengths 13
126
| metadata
dict | __index_level_0__
int64 0
415
|
---|---|---|---|
---
upgrade:
- |
When creating a :class:`~qiskit.quantum_info.Pauli` object with an invalid
string label, a :class:`~qiskit.exceptions.QiskitError` is now raised.
This is a change from previous releases which would raise an
``AttributeError`` on an invalid string label. This change was made to
ensure the error message is more informative and distinct from a generic
``AttributeError``.
| qiskit/releasenotes/notes/0.18/improve-error-in-pauli-944a71008789fbaa.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/0.18/improve-error-in-pauli-944a71008789fbaa.yaml",
"repo_id": "qiskit",
"token_count": 126
} | 241 |
---
features:
- |
Added a new :attr:`~qiskit.algorithms.optimizers.Optimizer.settings`
property to the :class:`~qiskit.algorithms.optimizers.Optimizer` abstract
base class that all the optimizer classes in the
:mod:`qiskit.algorithms.optimizers` module are based on. This property
will return a Python dictionary of the settings for the optimizer
that can be used to instantiate another instance of the same optimizer
class. For example::
from qiskit.algorithms.optimizers import GradientDescent
optimizer = GradientDescent(maxiter=10, learning_rate=0.01)
settings = optimizer.settings
new_optimizer = GradientDescent(**settings)
The ``settings`` dictionary is also potentially useful for serializing
optimizer objects using JSON or another serialization format.
| qiskit/releasenotes/notes/0.18/serializable-optimizers-642402828b0c733b.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/0.18/serializable-optimizers-642402828b0c733b.yaml",
"repo_id": "qiskit",
"token_count": 260
} | 242 |
---
features:
- |
The values ``"gate_error"`` and ``"balanced"`` are now available for the
``objective`` option in the construction of the
:class:`~qiskit.transpiler.passes.BIPMapping` object, and ``"balanced"`` is
now the default.
The ``"gate_error"`` objective requires passing a
:obj:`.BackendProperties` instance in the ``backend_prop``
kwarg, which contains the 2q-gate gate errors used in the computation of the
objectives. The ``"balanced"`` objective will use the
:obj:`.BackendProperties` instance if it is given, but otherwise will assume
a CX error rate as given in the new parameter ``default_cx_error_rate``.
The relative weights of the gate-error and depth components of the balanced
objective can be controlled with the new ``depth_obj_weight`` parameter.
upgrade:
- |
The default method for :obj:`.BIPMapping` is now ``balanced`` rather than
``depth``. This new objective generally achieves a better result, as it
factors in both the circuit depth and the gate error.
| qiskit/releasenotes/notes/0.19/add-gate-error-objective-00a96f75055d1526.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/0.19/add-gate-error-objective-00a96f75055d1526.yaml",
"repo_id": "qiskit",
"token_count": 319
} | 243 |
---
upgrade:
- |
The core dependency ``retworkx`` had its version requirement bumped to 0.10.1, up from 0.9.
This enables several performance improvements across different transpilation passes.
| qiskit/releasenotes/notes/0.19/bump-retworkx-0.10.1-1fcf4fc746bd754a.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/0.19/bump-retworkx-0.10.1-1fcf4fc746bd754a.yaml",
"repo_id": "qiskit",
"token_count": 56
} | 244 |
---
features:
- |
This release introduces a decomposition method for two-qubit gates which
targets user-defined sets of RZX gates. Transpiler users can enable
decomposition for {``RZX(pi/2)``, ``RZX(pi/4)``, and ``RZX(pi/6)``} specifically by including
``'rzx'`` in their ``basis_gates`` list when calling
:func:`~qiskit.compiler.transpile`. Quantum information package users can
find the method itself under the :obj:`.XXDecomposer` class.
| qiskit/releasenotes/notes/0.19/feature-rzx-decomposition-c3b5a36b88303c1f.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/0.19/feature-rzx-decomposition-c3b5a36b88303c1f.yaml",
"repo_id": "qiskit",
"token_count": 160
} | 245 |
---
fixes:
- |
Fixed an issue with the :meth:`.NLocal.add_layer` method incorrectly
appending layers if the :obj:`.NLocal` object had already been built.
| qiskit/releasenotes/notes/0.19/fix-nlocal-add_layer-c3cb0b5a49c2b04e.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/0.19/fix-nlocal-add_layer-c3cb0b5a49c2b04e.yaml",
"repo_id": "qiskit",
"token_count": 54
} | 246 |
---
features:
- |
Added two new classes, :class:`~qiskit.utils.mitigation.CompleteMeasFitter`
and :class:`~qiskit.utils.mitigation.TensoredMeasFitter` to the
:mod:`qiskit.utils.mitigation` module. These classes are for use only as
values for the ``measurement_error_mitigation_cls`` kwarg of the
:class:`~qiskit.utils.QuantumInstance` class. The instantiation and usage
of these classes (or anything else in :mod:`qiskit.utils.mitigation`)
outside of the ``measurement_error_mitigation_cls`` kwarg should be treated as an
internal private API and not relied upon.
deprecations:
- |
The use of the measurement mitigation classes
:class:`qiskit.ignis.mitigation.CompleteMeasFitter` and
:class:`qiskit.ignis.mitigation.TensoredMeasFitter` from ``qiskit-ignis``
as values for the ``measurement_error_mitigation_cls`` kwarg of the
constructor for the :class:`~qiskit.utils.QuantumInstance` class is
deprecated and will be removed in a future release. Instead the equivalent
classes from :mod:`qiskit.utils.mitigation`,
:class:`~qiskit.utils.mitigation.CompleteMeasFitter` and
:class:`~qiskit.utils.mitigation.TensoredMeasFitter` should be used. This
was necessary as the ``qiskit-ignis`` project is now deprecated and will
no longer be supported in the near future.
It's worth noting that unlike the equivalent classes from ``qiskit-ignis``
the versions from :mod:`qiskit.utils.mitigation` are supported only in
their use with :class:`~qiskit.utils.QuantumInstance` (i.e. as a class not
an instance with the ``measurement_error_mitigation_cls`` kwarg) and not
intended for standalone use.
| qiskit/releasenotes/notes/0.19/ignis-mitigators-70492690cbcf99ca.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/0.19/ignis-mitigators-70492690cbcf99ca.yaml",
"repo_id": "qiskit",
"token_count": 580
} | 247 |
---
features:
- |
QPY serialization is now capable of representing
:attr:`~qiskit.circuit.QuantumCircuit.global_phase` attributes of a
:class:`~qiskit.circuit.QuantumCircuit` object that are an ``int``,
:class:`~qiskit.circuit.Parameter` object, or
:class:`~qiskit.circuit.ParameterExpression` object. Previous versions of
QPY would only accept a :attr:`~qiskit.circuit.QuantumCircuit.global_phase`
that was a ``float``.
This requires the QPY format :ref:`qpy_version_2` which was introduced in
this release to represent the additional types.
| qiskit/releasenotes/notes/0.19/qpy-v2-f1c380b40936cccf.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/0.19/qpy-v2-f1c380b40936cccf.yaml",
"repo_id": "qiskit",
"token_count": 207
} | 248 |
---
features:
- |
The :class:`~qiskit.transpiler.passes.UnitarySynthesis` transpiler pass in
:mod:`qiskit.transpiler.passes` has a new kwarg in the constructor,
``min_qubits``. When specified this can be set to an ``int`` value which
is the minimum size :class:`~qiskit.extensions.UnitaryGate` object to
run the unitary synthesis on. If a :class:`~qiskit.extensions.UnitaryGate`
in a :class:`~qiskit.circuit.QuantumCircuit` uses fewer qubits it will
be skipped by that instance of the pass.
upgrade:
- |
The :attr:`~qiskit.extensions.SingleQubitUnitary.name` attribute of the
:class:`~qiskit.extensions.SingleQubitUnitary` gate class has been changed
from ``unitary`` to ``squ``. This was necessary to avoid a conflict with
the :class:`~qiskit.extensions.UnitaryGate` class's name which was also
``unitary`` since the 2 gates are not the same and don't have the same
implementation (and can't be used interchangeably).
| qiskit/releasenotes/notes/0.19/squ-gate-name-785b7896300a92ef.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/0.19/squ-gate-name-785b7896300a92ef.yaml",
"repo_id": "qiskit",
"token_count": 341
} | 249 |
---
features:
- |
The :class:`.TemplateOptimization` transpiler pass can now work
with :class:`~.Gate` objects that have :class:`.ParameterExpression`
parameters. An illustrative example of using :class:`.Parameter`\s
with :class:`.TemplateOptimization` is the following::
from qiskit import QuantumCircuit, transpile, schedule
from qiskit.circuit import Parameter
from qiskit.transpiler import PassManager
from qiskit.transpiler.passes import TemplateOptimization
# New contributions to the template optimization
from qiskit.transpiler.passes.calibration import RZXCalibrationBuilder, rzx_templates
from qiskit.test.mock import FakeCasablanca
backend = FakeCasablanca()
phi = Parameter('Ο')
qc = QuantumCircuit(2)
qc.cx(0,1)
qc.p(2*phi, 1)
qc.cx(0,1)
print('Original circuit:')
print(qc)
pass_ = TemplateOptimization(**rzx_templates.rzx_templates(['zz2']))
qc_cz = PassManager(pass_).run(qc)
print('ZX based circuit:')
print(qc_cz)
# Add the calibrations
pass_ = RZXCalibrationBuilder(backend)
cal_qc = PassManager(pass_).run(qc_cz.bind_parameters({phi: 0.12}))
# Transpile to the backend basis gates
cal_qct = transpile(cal_qc, backend)
qct = transpile(qc.bind_parameters({phi: 0.12}), backend)
# Compare the schedule durations
print('Duration of schedule with the calibration:')
print(schedule(cal_qct, backend).duration)
print('Duration of standard with two CNOT gates:')
print(schedule(qct, backend).duration)
outputs
.. parsed-literal::
Original circuit:
q_0: βββ βββββββββββββββ ββ
βββ΄βββββββββββββββ΄ββ
q_1: β€ X ββ€ P(2*Ο) ββ€ X β
ββββββββββββββββββββ
ZX based circuit:
βββββββββββββββ Β»
q_0: βββββββββββββββββββββββββββββββββββββ€0 βββββββββββββΒ»
βββββββββββββββββββββββββββββββββββββ Rzx(2.0*Ο) βββββββββββββΒ»
q_1: β€ Rz(-Ο/2) ββ€ Rx(-Ο/2) ββ€ Rz(-Ο/2) ββ€1 ββ€ Rx(-2*Ο) βΒ»
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββΒ»
Β«
Β«q_0: ββββββββββββββββββββββββββββββββββββββββββββββββ
Β« ββββββββββββββββββββββββββββββββββββββββββββββββ
Β«q_1: β€ Rz(-Ο/2) ββ€ Rx(-Ο/2) ββ€ Rz(-Ο/2) ββ€ P(2.0*Ο) β
Β« ββββββββββββββββββββββββββββββββββββββββββββββββ
Duration of schedule with the calibration:
1600
Duration of standard with two CNOT gates:
6848
| qiskit/releasenotes/notes/0.20/add-parameters-to-template-substitution-a1379cdbfcc10b5c.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/0.20/add-parameters-to-template-substitution-a1379cdbfcc10b5c.yaml",
"repo_id": "qiskit",
"token_count": 1344
} | 250 |
deprecations:
- |
The ``max_credits`` argument to :func:`~.execute_function.execute`, and all
of the ``Qobj`` configurations (e.g. :class:`.QasmQobjConfig` and
:class:`.PulseQobjConfig`), is deprecated and will be removed in a future
release. The credit system has not been in use on IBM Quantum backends for
two years, and the option has no effect. No alternative is necessary.
For example, if you were calling :func:`~.execute_function.execute` as::
job = execute(qc, backend, shots=4321, max_credits=10)
you can simply omit the ``max_credits`` argument::
job = execute(qc, backend, shots=4321)
| qiskit/releasenotes/notes/0.20/deprecate-max-credits-56a404050a655a04.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/0.20/deprecate-max-credits-56a404050a655a04.yaml",
"repo_id": "qiskit",
"token_count": 221
} | 251 |
---
features:
- |
The :class:`~qiskit.opflow.gradients.Gradient` and
:class:`~qiskit.opflow.gradients.QFI` classes can now calculate the imaginary
part of expectation value gradients. When using a different measurement basis,
i.e. ``-Y`` instead of ``Z``, we can measure the imaginary part of gradients
The measurement basis can be set with the ``aux_meas_op`` argument.
For the gradients, ``aux_meas_op = Z`` computes ``0.5Re[(β¨Ο(Ο)|)O(ΞΈ)|dΟΟ(Ο)γ]``
and ``aux_meas_op = -Y`` computes ``0.5Im[(β¨Ο(Ο)|)O(ΞΈ)|dΟΟ(Ο)γ]``.
For the QFIs, ``aux_meas_op = Z`` computes ``4Re[(dΟβ¨<Ο(Ο)|)(dΟ|Ο(Ο)γ)]``
and ``aux_meas_op = -Y`` computes ``4Im[(dΟβ¨<Ο(Ο)|)(dΟ|Ο(Ο)γ)]``.
For example::
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.opflow import CircuitStateFn, Y
from qiskit.opflow.gradients.circuit_gradients import LinComb
from qiskit.circuit import Parameter
a = Parameter("a")
b = Parameter("b")
params = [a, b]
q = QuantumRegister(1)
qc = QuantumCircuit(q)
qc.h(q)
qc.rz(params[0], q[0])
qc.rx(params[1], q[0])
op = CircuitStateFn(primitive=qc, coeff=1.0)
aux_meas_op = -Y
prob_grad = LinComb(aux_meas_op=aux_meas_op).convert(operator=op, params=params)
| qiskit/releasenotes/notes/0.20/imag_gradients-3dabcd11343062a8.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/0.20/imag_gradients-3dabcd11343062a8.yaml",
"repo_id": "qiskit",
"token_count": 614
} | 252 |
fixes:
- |
Stopped the parser in :meth:`.QuantumCircuit.from_qasm_str` and
:meth:`~.QuantumCircuit.from_qasm_file` from accepting OpenQASM programs
that identified themselves as being from a language version other than 2.0.
This parser is only for OpenQASM 2.0; support for imported circuits from
OpenQASM 3.0 will be added in an upcoming release.
| qiskit/releasenotes/notes/0.20/qasm-lexer-bugfix-1779525b3738902c.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/0.20/qasm-lexer-bugfix-1779525b3738902c.yaml",
"repo_id": "qiskit",
"token_count": 124
} | 253 |
---
features:
- |
Introduced a new transpiler pass workflow for building :class:`~.PassManager` objects
for scheduling :class:`~.QuantumCircuit` objects in the transpiler. In the new
workflow, scheduling and alignment passes are all :class:`~.AnalysisPass` objects that
only update the pass manager's property set, specifically a new property set item
``node_start_time``, which holds the absolute start time of each opnode. A separate
:class:`~.TransformationPass` such as :class:`~.PadDelay` is subsequently used
to apply scheduling to the DAG. This new workflow is both more efficient and can
correct for additional timing constraints exposed by a backend.
Previously, the pass chain would have been implemented as ``scheduling -> alignment``
which were both transform passes thus there were multiple :class:`~.DAGCircuit`
instances recreated during each pass. In addition, scheduling occurred in each pass
to obtain instruction start time. Now the required pass chain becomes
``scheduling -> alignment -> padding`` where the :class:`~.DAGCircuit` update only
occurs at the end with the ``padding`` pass.
For those who are creating custom :class:`~.PassManager` objects that involve
circuit scheduling you will need to adjust your :class:`~.PassManager`
to insert one of the :class:`~.BasePadding` passes (currently
either :class:`~.PadDelay` or :class:`~.PadDynamicalDecoupling` can be used)
at the end of the scheduling pass chain. Without the padding pass the scheduling
passes will not be reflected in the output circuit of the :meth:`~.PassManager.run`
method of your custom :class:`~.PassManager`.
For example, if you were previously building your :class:`~.PassManager`
with something like::
from qiskit.transpiler import PassManager
from qiskit.transpiler.passes import TimeUnitConversion, ALAPSchedule, ValidatePulseGates, AlignMeasures
pm = PassManager()
scheduling = [
ALAPSchedule(instruction_durations), PadDelay()),
ValidatePulseGates(granularity=timing_constraints.granularity, min_length=timing_constraints.min_length),
AlignMeasures(alignment=timing_constraints.acquire_alignment),
]
pm.append(scheduling)
you can instead use::
from qiskit.transpiler import PassManager
from qiskit.transpiler.passes import TimeUnitConversion, ALAPScheduleAnalysis, ValidatePulseGates, AlignMeasures, PadDelay
pm = PassManager()
scheduling = [
ALAPScheduleAnalysis(instruction_durations), PadDelay()),
ConstrainedReschedule(acquire_alignment=timing_constraints.acquire_alignment, pulse_alignment=timing_constraints.pulse_alignment),
ValidatePulseGates(granularity=timing_constraints.granularity, min_length=timing_constraints.min_length),
PadDelay()
]
pm.append(scheduling)
which will both be more efficient and also align instructions based on any hardware constraints.
- |
Added a new transpiler pass :class:`~.ConstrainedReschedule` pass.
The :class:`~.ConstrainedReschedule` pass considers both hardware
alignment constraints that can be definied in a :class:`.BackendConfiguration`
object, ``pulse_alignment`` and ``acquire_alignment``. This new class superscedes
the previously existing :class:`~.AlignMeasures` as it performs the same alignment
(via the property set) for measurement instructions in addition to general instruction
alignment. By setting the ``acquire_alignment`` constraint argument for the
:class:`~.ConstrainedReschedule` pass it is a drop-in replacement of
:class:`~.AlignMeasures` when paired with a new :class:`~.BasePadding` pass.
- |
Added two new transpiler passes :class:`~.ALAPScheduleAnalysis` and :class:`~.ASAPScheduleAnalysis`
which superscede the :class:`~.ALAPSchedule` and :class:`~.ASAPSchedule` as part of the
reworked transpiler workflow for scheduling. The new passes perform the same scheduling but
in the property set and relying on a :class:`~.BasePadding` pass to adjust the circuit
based on all the scheduling alignment analysis.
The standard behavior of these passes also aligns timing ordering with the topological
ordering of the DAG nodes. This change may affect the scheduling outcome if it includes
conditional operations, or simultaneously measuring two qubits with the same classical
register (edge-case). To reproduce conventional behavior, set ``clbit_write_latency``
identical to the measurement instruction length.
For example, consider scheduling an input circuit like:
.. parsed-literal::
ββββββββ
q_0: β€ X ββ€Mβββββββββββββββ
βββββββ₯β βββββ
q_1: βββββββ«βββββ€ X βββββββ
β βββ₯ββ βββ
q_2: βββββββ«βββββββ«ββββββ€Mβ
β ββββββ¨βββββββ₯β
c: 1/βββββββ©ββ‘ c_0=0x1 βββ©β
0 βββββββββββ 0
.. code-block::
from qiskit import QuantumCircuit
from qiskit.transpiler import InstructionDurations, PassManager
from qiskit.transpiler.passes import ALAPScheduleAnalysis, PadDelay, SetIOLatency
from qiskit.visualization.timeline import draw
circuit = QuantumCircuit(3, 1)
circuit.x(0)
circuit.measure(0, 0)
circuit.x(1).c_if(0, 1)
circuit.measure(2, 0)
durations = InstructionDurations([("x", None, 160), ("measure", None, 800)])
pm = PassManager(
[
SetIOLatency(clbit_write_latency=800, conditional_latency=0),
ALAPScheduleAnalysis(durations),
PadDelay(),
]
)
draw(pm.run(circuit))
As you can see in the timeline view, the measurement on ``q_2`` starts before
the conditional X gate on the ``q_1``, which seems to be opposite to the
topological ordering of the node. This is also expected behavior
because clbit write-access happens at the end edge of the measure instruction,
and the read-access of the conditional gate happens the begin edge of the instruction.
Thus topological ordering is preserved on the timeslot of the classical register,
which is not captured by the timeline view.
However, this assumes a paticular microarchitecture design, and the circuit is
not necessary scheduled like this.
By using the default configuration of passes, the circuit is schedule like below.
.. code-block::
from qiskit import QuantumCircuit
from qiskit.transpiler import InstructionDurations, PassManager
from qiskit.transpiler.passes import ALAPScheduleAnalysis, PadDelay
from qiskit.visualization.timeline import draw
circuit = QuantumCircuit(3, 1)
circuit.x(0)
circuit.measure(0, 0)
circuit.x(1).c_if(0, 1)
circuit.measure(2, 0)
durations = InstructionDurations([("x", None, 160), ("measure", None, 800)])
pm = PassManager([ALAPScheduleAnalysis(durations), PadDelay()])
draw(pm.run(circuit))
Note that clbit is locked throughout the measurement instruction interval.
This behavior is designed based on the Qiskit Pulse, in which the acquire instruction takes
``AcquireChannel`` and ``MemorySlot`` which are not allowed to overlap with other instructions,
i.e. simultaneous memory access from the different instructions is prohibited.
This also always aligns the timing ordering with the topological node ordering.
- |
Added a new transpiler pass :class:`~.PadDynamicalDecoupling`
which superscedes the :class:`~.DynamicalDecoupling` pass as part of the
reworked transpiler workflow for scheduling. This new pass will insert dynamical decoupling
sequences into the circuit per any scheduling and alignment analysis that occurred in earlier
passes.
| qiskit/releasenotes/notes/0.20/update-instruction-alignment-passes-ef0f20d4f89f95f3.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/0.20/update-instruction-alignment-passes-ef0f20d4f89f95f3.yaml",
"repo_id": "qiskit",
"token_count": 2697
} | 254 |
---
features:
- |
Added a new circuit drawing style, ``textbook``, which uses the color
scheme of the Qiskit Textbook.
| qiskit/releasenotes/notes/0.21/add-textbook-circuit-style-98600038608c8f75.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/0.21/add-textbook-circuit-style-98600038608c8f75.yaml",
"repo_id": "qiskit",
"token_count": 42
} | 255 |
---
upgrade:
- |
The QPY version format version emitted by :func:`.qpy.dump` has been
increased to version 5. This new format version is incompatible with the
previous versions and will result in an error when trying to load it with
a deserializer that isn't able to handle QPY version 5. This change was
necessary to fix support for representing controlled gates properly and
representing non-default control states.
fixes:
- |
Fixed support for QPY serialization (:func:`.qpy.dump`) and deserialization
(:func:`.qpy.load`) of a :class:`~.QuantumCircuit` object containing custom
:class:`~.ControlledGate` objects. Previously, an exception would be raised
by :func:`.qpy.load` when trying to reconstruct the custom
:class:`~.ControlledGate`.
Fixed `#7999 <https://github.com/Qiskit/qiskit-terra/issues/7999>`__.
- |
Fixed support for QPY serialization (:func:`.qpy.dump`) and deserialization
(:func:`.qpy.load`) of a :class:`~.QuantumCircuit` object containing custom
:class:`~.MCPhaseGate` objects. Previously, an exception would be raised
by :func:`.qpy.load` when trying to reconstruct the :class:`~.MCPhaseGate`.
- |
Fixed support for QPY serialization (:func:`.qpy.dump`) and deserialization
(:func:`.qpy.load`) of a :class:`~.QuantumCircuit` object containing
controlled gates with an open control state. Previously, the open control
state would be lost by the serialization process and the reconstructed
circuit.
| qiskit/releasenotes/notes/0.21/fix-qpy-controlled-gates-e653cbeee067f90b.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/0.21/fix-qpy-controlled-gates-e653cbeee067f90b.yaml",
"repo_id": "qiskit",
"token_count": 488
} | 256 |
---
upgrade:
- |
The previously deprecated ``BaseBackend``, ``BaseJob``, and ``BaseProvider``
classes have all been removed. They were originally deprecated in the
0.18.0 release. Instead of these classes you should be using the versioned
providers interface classes, the latest being :class:`~.BackendV2`,
:class:`~.JobV1`, and :class:`~.ProviderV1`.
- |
The previously deprecated ``backend`` argument for the constructor of the
:class:`~.RZXCalibrationBuilder` transpiler pass has been removed. It was
originally deprecated in the 0.19.0 release. Instead you should query
the :class:`~.Backend` object for the ``instruction_schedule_map`` and
``qubit_channel_mapping`` and pass that directly to the constructor. For
example, with a :class:`~.BackendV1` backend::
from qiskit.transpiler.passes import RZXCalibrationBuilder
from qiskit.providers.fake_provider import FakeMumbai
backend = FakeMumbai()
inst_map = backend.defaults().instruction_schedule_map
channel_map = backend.configuration().qubit_channel_mapping
cal_pass = RZXCalibrationBuilder(
instruction_schedule_map=inst_map,
qubit_channel_mapping=channel_map,
)
or with a :class:`~.BackendV2` backend::
from qiskit.transpiler.passes import RZXCalibrationBuilder
from qiskit.providers.fake_provider import FakeMumbaiV2
backend = FakeMumbaiV2()
inst_map = backend.instruction_schedule_map
channel_map = {bit: backend.drive_channel(bit) for bit in range(backend.num_qubits)}
cal_pass = RZXCalibrationBuilder(
instruction_schedule_map=inst_map,
qubit_channel_mapping=channel_map,
)
deprecations:
- |
The ``qobj_id`` and ``qobj_header`` keyword arguments for the
:func:`~.execute` function have been deprecated and will be removed in a
future release. Since the removal of the ``BaseBackend`` class these
arguments don't have any effect as no backend supports execution with a
:class:`~.Qobj` object directly and instead only work with
:class:`~.QuantumCircuit` objects directly.
| qiskit/releasenotes/notes/0.21/remove-basebackend-7beac0abd17144fe.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/0.21/remove-basebackend-7beac0abd17144fe.yaml",
"repo_id": "qiskit",
"token_count": 790
} | 257 |
---
features:
- |
Added a new transpiler pass, :class:`~.VF2PostLayout`. This pass is of a
new type to perform a new phase/function in the compilation pipeline,
post-layout or post optimization qubit selection. The idea behind this
pass is after we finish the optimization loop in transpiler we
know what the final gate counts will be on each qubit in the circuit so
we can potentially find a better-performing subset of qubits on a backend
to execute the circuit. The pass will search for an isomorphic subgraph in
the connectivity graph of the target backend and look at the full error
rate of the complete circuit on any subgraph found and return the
layout found with the lowest error rate for the circuit.
This pass is similar to the :class:`~.VF2Layout` pass and both internally
use the same VF2 implementation from
`retworkx <https://github.com/Qiskit/retworkx>`__. However,
:class:`~.VF2PostLayout` is designed to run after initial layout, routing,
basis translation, and any optimization passes run and will only work if
a layout has already been applied, the circuit has been routed, and all
gates are in the target basis. This is required so that when a new layout
is applied the circuit can still be run on the target device. :class:`~.VF2Layout`
on the other hand is designed to find a perfect initial layout and can
work with any circuit.
- |
The :class:`~.ApplyLayout` transpiler pass now has support for updating
a layout on a circuit after a layout has been applied once before. If
the ``post_layout`` field is present (in addition to the required
``layout`` field) the ``property_set`` when the :class:`~.ApplyLayout` pass
is run the pass will update the layout to apply the new layout. This will
return a :class:`~.DAGCircuit` with the qubits in the new physical order
and the ``layout`` property set will be updated so that it maps the
virtual qubits from the original layout to the physical qubits in the new
``post_layout`` field.
- |
The preset pass managers generated by :func:`~.level_1_pass_manager`,
:func:`~.level_2_pass_manager`, and :func:`~.level_3_pass_manager` which
correspond to ``optimization_level`` 1, 2, and 3 respectively on the
:func:`~.transpile` function now run the :class:`~.VF2PostLayout` pass
after running the routing pass. This enables the transpiler to
potentially find a different set of physical qubits on the target backend
to run the circuit on which have lower error rates. The
:class:`~.VF2PostLayout` pass will not be run if you manually specify a
``layout_method``, ``routing_method``, or ``initial_layout`` arguments
to :func:`~.transpile`. If the pass can find a better performing subset of
qubits on backend to run the physical circuit it will adjust the layout of
the circuit to use the alternative qubits instead.
| qiskit/releasenotes/notes/0.21/vf2-post-layout-f0213e2c7ebb645c.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/0.21/vf2-post-layout-f0213e2c7ebb645c.yaml",
"repo_id": "qiskit",
"token_count": 861
} | 258 |
features:
- |
Added a new method :meth:`.SparsePauliOp.argsort`, which
returns the composition of permutations in the order of sorting
by coefficient and sorting by Pauli. By using the ``weight``
keyword argument for the method the output can additionally be sorted
by the number of non-identity terms in the Pauli, where the set of
all Paulis of a given weight are still ordered lexicographically.
- |
Added a new method :meth:`.SparsePauliOp.sort`, which will first
sort the coefficients using numpy's ``argsort()`` and then sort
by Pauli, where the Pauli sort takes precedence. If the Pauli sort
is the same, it will then be sorted by coefficient. By using the
``weight`` keyword argument the output can additionally be sorted
by the number of non-identity terms in the Pauli, where the set of
all Paulis of a given weight are still ordered lexicographically.
| qiskit/releasenotes/notes/0.22/add-sparsepauliop-methods-00a7e6cc7055e1d0.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/0.22/add-sparsepauliop-methods-00a7e6cc7055e1d0.yaml",
"repo_id": "qiskit",
"token_count": 261
} | 259 |
---
features:
- |
Added new attributes :attr:`.Clifford.symplectic_matrix`, :attr:`.Clifford.tableau`,
:attr:`.Clifford.z`, :attr:`.Clifford.x`, :attr:`.Clifford.phase`,
:attr:`.Clifford.stab`, :attr:`.Clifford.stab_z`, :attr:`.Clifford.stab_x`, :attr:`.Clifford.stab_phase`,
:attr:`.Clifford.destab`, :attr:`.Clifford.destab_z`, :attr:`.Clifford.destab_x`, :attr:`.Clifford.destab_phase`
to the :class:`~.Clifford` class. These can be used instead of :attr:`.Clifford.table`, that will be deprecated in the future.
:class:`.StabilizerTable` and :class:`.PauliTable` are pending deprecation and
will be deprecated in the future release and subsequently removed after that.
deprecations:
- |
The :func:`.random_stabilizer_table` has been deprecated and will be removed in a future
release. Instead the :func:`~.random_pauli_list` function should be used.
| qiskit/releasenotes/notes/0.22/deprecate-stabilizer-table-9efd08c7de1a5b4d.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/0.22/deprecate-stabilizer-table-9efd08c7de1a5b4d.yaml",
"repo_id": "qiskit",
"token_count": 331
} | 260 |
---
fixes:
- |
There were two bugs in the ``text`` circuit drawer that were fixed.
These appeared when ``vertical_compression`` was set to ``medium``,
which is the default. The first would sometimes cause text to overwrite
other text or gates, and the second would sometimes cause the connections
between a gate and its controls to break.
See `#8588 <https://github.com/Qiskit/qiskit-terra/issues/8588>`__.
| qiskit/releasenotes/notes/0.22/fix-text-drawer-compression-a80a5636957e8eec.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/0.22/fix-text-drawer-compression-a80a5636957e8eec.yaml",
"repo_id": "qiskit",
"token_count": 131
} | 261 |
---
prelude: |
The Qiskit Terra 0.22.0 release is a major feature release that includes
a myriad of new feature and bugfixes. The highlights for this release are:
* Adding initial support to the transpiler for transpiling
:class:`~.QuantumCircuit` objects that contain control flow instructions
such as :class:`~.ForLoopOp` and :class:`~.WhileLoopOp`.
* Greatly improved scaling and performance for the :func:`~.transpile` function
with large numbers of qubits, especially when ``optimization_level=3`` is used.
* External plugin interface for :func:`~.transpile` that enables external
packages to implement stages for the default pass managers. More details on this
can be found at :mod:`qiskit.transpiler.preset_passmanagers.plugin`.
Additionally, :class:`~.BackendV2` backends can now optionally set
custom default plugins to use for the scheduling and translation stages.
* Updated algorithm implementations in :mod:`qiskit.algorithms` that leverage
the :mod:`~.primitives` classes that implement the :class:`~.BaseSampler` and
:class:`~.BaseEstimator`.
features:
- |
Added new primitive implementations, :class:`~.BackendSampler` and :class:`~.BackendEstimator`,
to :mod:`qiskit.primitives`. Thes new primitive class implementation wrap a :class:`~.BackendV1`
or :class:`~.BackendV2` instance as a :class:`~.BaseSampler` or :class:`~.BaseEstimator`
respectively. The intended use case for these primitive implementations is to bridge the gap
between providers that do not have native primitive implementations and use that provider's
backend with APIs that work with primitives. For example, the :class:`~.SamplingVQE` class
takes a :class:`~.BaseSampler` instance to function. If you'd like to run that class with
a backend from a provider without a native primitive implementation you can construct a
:class:`~.BackendSampler` to do this::
from qiskit.algorithms.minimum_eigensolvers import SamplingVQE
from qiskit.algorithms.optimizers import SLSQP
from qiskit.circuit.library import TwoLocal
from qiskit.primitives import BackendSampler
from qiskit.providers.fake_provider import FakeHanoi
from qiskit.opflow import PauliSumOp
from qiskit.quantum_info import SparsePauliOp
backend = FakeHanoi()
sampler = BackendSampler(backend=backend)
operator = PauliSumOp(SparsePauliOp(["ZZ", "IZ", "II"], coeffs=[1, -0.5, 0.12]))
ansatz = TwoLocal(rotation_blocks=["ry", "rz"], entanglement_blocks="cz")
optimizer = SLSQP()
sampling_vqe = SamplingVQE(sampler, ansatz, optimizer)
result = sampling_vqe.compute_minimum_eigenvalue(operator)
eigenvalue = result.eigenvalue
If you're using a provider that has native primitive implementations (such as
``qiskit-ibm-runtime`` or ``qiskit-aer``) it is always a better choice to use that native
primitive implementation instead of :class:`~.BackendEstimator` or :class:`~.BackendSampler`
as the native implementations will be much more efficient and/or do additional pre and post
processing. :class:`~.BackendEstimator` and :class:`~.BackendSampler` are designed to be
generic that can work with any backend that returns :class:`~.Counts` in their
:class:`~.Results` which precludes additional optimization.
| qiskit/releasenotes/notes/0.22/prepare-0.22-118e15de86d36072.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/0.22/prepare-0.22-118e15de86d36072.yaml",
"repo_id": "qiskit",
"token_count": 1150
} | 262 |
---
upgrade:
- |
The deprecated arguments ``epsilon`` and ``factr`` for the constructor of
the :class:`~.L_BFGS_B` optimizer class have been removed. These arguments
were originally deprecated as part of the 0.18.0 release (released on
July 12, 2021). Instead the ``ftol`` argument should be used, you
can refer to the `scipy docs <https://docs.scipy.org/doc/scipy/reference/optimize.minimize-lbfgsb.html.>`__
on the optimizer for more detail on the relationship between these arguments.
| qiskit/releasenotes/notes/0.22/remove_optimizers_L_BFGS_B_epsilon-03f997aff50c394c.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/0.22/remove_optimizers_L_BFGS_B_epsilon-03f997aff50c394c.yaml",
"repo_id": "qiskit",
"token_count": 166
} | 263 |
---
upgrade:
- |
Updated :class:`~qiskit.result.ProbDistribution` and :class:`~qiskit.result.QuasiDistribution`
to store the information of the number of bits if bitstrings without prefix "0b" are given.
:meth:`.ProbDistribution.binary_probabilities` and
:meth:`.QuasiDistribution.binary_probabilities` use the stored number of bits
as the default value of the number of bits.
.. code-block: python
import qiskit.result import ProbDistribution, QuasiDistribution
prob = ProbDistribution({"00": 0.5, "01": 0.5})
quasi = QuasiDistribution({"00": 0.5, "01": 0.5})
print(prob.binary_probabilities())
# {'00': 0.5, '01': 0.5}
print(quasi.binary_probabilities())
# {'00': 0.5, '01': 0.5}
| qiskit/releasenotes/notes/0.22/update-prob-quasi-2044285a46219d14.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/0.22/update-prob-quasi-2044285a46219d14.yaml",
"repo_id": "qiskit",
"token_count": 296
} | 264 |
---
features:
- |
New pulse directive :class:`~qiskit.pulse.instructions.TimeBlockade` has been added.
This instruction is QPY compatible. This directive behaves almost identically to
the delay instruction, but will be removed before execution.
This directive is intended to be used internally within the pulse builder
and helps :class:`.ScheduleBlock` represent instructions with
absolute time intervals. This allows the pulse builder to convert
:class:`Schedule` into :class:`ScheduleBlock`, rather than wrapping with call instruction.
| qiskit/releasenotes/notes/0.23/add-timeblockade-instruction-9469a5e9e0218adc.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/0.23/add-timeblockade-instruction-9469a5e9e0218adc.yaml",
"repo_id": "qiskit",
"token_count": 149
} | 265 |
---
deprecations:
- |
The import ``qiskit.circuit.qpy_serialization`` is deprecated, as QPY has been promoted to the
top level. You should import the same objects from :mod:`qiskit.qpy` instead. The old path
will be removed in a future of Qiskit Terra.
| qiskit/releasenotes/notes/0.23/deprecate-old-qpy-d39c754d82655400.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/0.23/deprecate-old-qpy-d39c754d82655400.yaml",
"repo_id": "qiskit",
"token_count": 91
} | 266 |
---
fixes:
- |
The circuit drawers (:meth:`.QuantumCircuit.draw` and :func:`.circuit_drawer`) will no
longer emit a warning about the ``cregbundle`` parameter when using the default arguments,
if the content of the circuit requires all bits to be drawn individually. This was most
likely to appear when trying to draw circuits with new-style control-flow operations.
| qiskit/releasenotes/notes/0.23/fix-cregbundle-warning-d3c991bb6276761d.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/0.23/fix-cregbundle-warning-d3c991bb6276761d.yaml",
"repo_id": "qiskit",
"token_count": 110
} | 267 |
---
fixes:
- |
Fixed a bug in QPY (:mod:`qiskit.qpy`) where circuits containing registers
whose bits occurred in the circuit after loose bits would fail to deserialize.
See `#9094 <https://github.com/Qiskit/qiskit-terra/issues/9094>`__.
| qiskit/releasenotes/notes/0.23/fix-qpy-register-57ed7cf2f3f67e78.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/0.23/fix-qpy-register-57ed7cf2f3f67e78.yaml",
"repo_id": "qiskit",
"token_count": 92
} | 268 |
---
fixes:
- |
Zero-operand gates and instructions will now work with
:func:`.circuit_to_gate`, :meth:`.QuantumCircuit.to_gate`,
:meth:`.Gate.control`, and the construction of an
:class:`~.quantum_info.Operator` from a :class:`.QuantumCircuit` containing
zero-operand instructions. This edge case is occasionally useful in creating
global-phase gates as part of larger compound instructions, though for many
uses, :attr:`.QuantumCircuit.global_phase` may be more appropriate.
| qiskit/releasenotes/notes/0.23/fix-zero-operand-gates-323510ec8f392f27.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/0.23/fix-zero-operand-gates-323510ec8f392f27.yaml",
"repo_id": "qiskit",
"token_count": 162
} | 269 |
---
fixes:
- |
Fixed an issue with the :meth:`.Statevector.probabilities_dict` and :meth:`.DensityMatrix.probabilities_dict`
method where it would return incorrect results for non-qubit systems when the ``qargs`` argument was
specified.
Fixed `#9210 <https://github.com/Qiskit/qiskit-terra/issues/9210>`__ | qiskit/releasenotes/notes/0.23/probabilities_dict_bug_fix-aac3b3d3853828dc.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/0.23/probabilities_dict_bug_fix-aac3b3d3853828dc.yaml",
"repo_id": "qiskit",
"token_count": 112
} | 270 |
---
features:
- |
Added two new classes :class:`~qiskit.algorithms.time_evolvers.classical_methods.SciPyRealEvolver` and
:class:`~qiskit.algorithms.time_evolvers.classical_methods.SciPyImaginaryEvolver` that implement integration methods
for time evolution of a quantum state.
The value and standard deviation of observables as well as the times they are
evaluated at can be queried as :attr:`.TimeEvolutionResult.observables` and
:attr:`.TimeEvolutionResult.times`.
Here is simple example:
.. code-block:: python
from qiskit.algorithms.time_evolvers.time_evolution_problem import TimeEvolutionProblem
from qiskit.quantum_info import SparsePauliOp
from qiskit.quantum_info.states.statevector import Statevector
from qiskit.algorithms import SciPyImaginaryEvolver
initial_state = Statevector.from_label("+++++")
hamiltonian = SparsePauliOp("ZZZZZ")
evolution_problem = TimeEvolutionProblem(hamiltonian, 100, initial_state, {"Energy":hamiltonian})
classic_evolver = SciPyImaginaryEvolver(num_timesteps=300)
result = classic_evolver.evolve(evolution_problem)
print(result.observables)
| qiskit/releasenotes/notes/0.23/scipy-evolvers-ca92bcb90e90b035.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/0.23/scipy-evolvers-ca92bcb90e90b035.yaml",
"repo_id": "qiskit",
"token_count": 440
} | 271 |
---
features:
- |
Added an alternative way to specify in :class:`~.HLSConfig` the list of
synthesis methods used for a given high-level-object.
As before, a synthesis method can be specified as a tuple consisting of
the name of the method and additional arguments. Additionally, a synthesis method
can be specified as a tuple consisting of an instance of :class:`.HighLevelSynthesisPlugin`
and additional arguments. Moreover, when there are no additional arguments, a synthesis
method can be specified simply by name or by an instance of :class:`.HighLevelSynthesisPlugin`.
The following example illustrates the new functionality::
from qiskit import QuantumCircuit
from qiskit.circuit.library.generalized_gates import PermutationGate
from qiskit.transpiler import PassManager
from qiskit.transpiler.passes.synthesis.high_level_synthesis import HLSConfig, HighLevelSynthesis
from qiskit.transpiler.passes.synthesis.high_level_synthesis import ACGSynthesisPermutation
qc = QuantumCircuit(6)
qc.append(PermutationGate([1, 2, 3, 0]), [1, 2, 3, 4])
# All of the ways to specify hls_config are equivalent
hls_config = HLSConfig(permutation=[("acg", {})])
hls_config = HLSConfig(permutation=["acg"])
hls_config = HLSConfig(permutation=[(ACGSynthesisPermutation(), {})])
hls_config = HLSConfig(permutation=[ACGSynthesisPermutation()])
# The hls_config can then be passed as an argument to HighLevelSynthesis
pm = PassManager(HighLevelSynthesis(hls_config=hls_config))
qc_synthesized = pm.run(qc)
| qiskit/releasenotes/notes/0.24/add-alternative-hls-construction-afec157f7cf15b0b.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/0.24/add-alternative-hls-construction-afec157f7cf15b0b.yaml",
"repo_id": "qiskit",
"token_count": 580
} | 272 |
---
fixes:
- |
The :class:`.AmplitudeEstimation` class now correctly warns if an :class:`.EstimationProblem`
with a set ``is_good_state`` property is passed as input, as it is not supported and ignored.
Previously, the algorithm would silently ignore this option leading to unexpected results.
features:
- |
Added the :attr:`.EstimationProblem.has_good_state` attribute, which allows to check
whether an :class:`.EstimationProblem` has a custom :attr:`.EstimationProblem.is_good_state`
or if it is the default. This is useful for checks in amplitude estimators, such as
:class:`.AmplitudeEstimation`, which only support the default implementation.
| qiskit/releasenotes/notes/0.24/ae-warns-on-goodstate-7dbb689ba6a5e5e4.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/0.24/ae-warns-on-goodstate-7dbb689ba6a5e5e4.yaml",
"repo_id": "qiskit",
"token_count": 192
} | 273 |
---
deprecations:
- |
The :class:`~qiskit.quantum_info.PauliTable` and :class:`~qiskit.quantum_info.StabilizerTable`
are deprecated and will be removed in a future release.
Instead, the :class:`~qiskit.quantum_info.PauliList` should be used.
With this change, :meth:`~qiskit.quantum_info.Clifford.table` has been deprecated
so that you should operate directly from :meth:`~qiskit.quantum_info.Clifford.tableau`
without it.
| qiskit/releasenotes/notes/0.24/deprecate-pauli-table-fc6dcdb5eeb6e0c4.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/0.24/deprecate-pauli-table-fc6dcdb5eeb6e0c4.yaml",
"repo_id": "qiskit",
"token_count": 170
} | 274 |
---
fixes:
- |
Fixed the top-right corner of gates when using ``vertical_compression="low"`` in text visualizations of circuits.
| qiskit/releasenotes/notes/0.24/fix-circuit-drawing-low-compression-965c21de51b26ad2.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/0.24/fix-circuit-drawing-low-compression-965c21de51b26ad2.yaml",
"repo_id": "qiskit",
"token_count": 40
} | 275 |
---
fixes:
- |
Circuits containing :class:`.C3SXGate` can now be output and read in again safely from the
OpenQASM 2.0 exporter (:meth:`.QuantumCircuit.qasm`) and parser (:meth:`.QuantumCircuit.from_qasm_str`).
| qiskit/releasenotes/notes/0.24/fix-qasm2-c3sxgate-47171c9d17876219.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/0.24/fix-qasm2-c3sxgate-47171c9d17876219.yaml",
"repo_id": "qiskit",
"token_count": 86
} | 276 |
---
features:
- |
The :class:`.GateDirection` transpiler pass can now flip the direction
of ``swap`` (:class`.SwapGate`) instructions.
| qiskit/releasenotes/notes/0.24/gate-direction-swap-885b6f8ba9779853.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/0.24/gate-direction-swap-885b6f8ba9779853.yaml",
"repo_id": "qiskit",
"token_count": 51
} | 277 |
---
upgrade:
- |
When running the :func:`~.transpile` function with a :class:`~.BackendV1`
based backend or a :class:`~.BackendProperties` via the ``backend_properties``
keyword argument that has any qubits or gates flagged as faulty the function
will no longer try to automatically remap the qubits based on this information.
The method by which :func:`~.transpile` attempted to do this remapping was
fundamentally flawed and in most cases of such a backend it would result
an internal error being raised. In practice very few backends ever set the
fields in :class:`~.BackendProperties` to flag a qubit or gate as faulty.
If you were somehow successfully relying on :func:`~.transpile to do this
re-mapping for you will now need to manually do that and pass a
mapped input to the ``coupling_map`` and ``backend_properties`` arguments
which has filtered out the faulty qubits and gates and then manually re-map
the output.
| qiskit/releasenotes/notes/0.24/remove-faulty-qubits-support-00850f69185c365e.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/0.24/remove-faulty-qubits-support-00850f69185c365e.yaml",
"repo_id": "qiskit",
"token_count": 287
} | 278 |
---
features:
- |
The :class:`~.DefaultUnitarySynthesis` transpiler pass now chooses
one and two-qubit unitary synthesis based on the basis errors, if they
are reported in the target. In particular, it runs all possible synthesis
and chooses the cheapest option.
For a one-qubit decomposition, it can target Pauli basis
(e.g. RZ-RX-RZ or RZ-RY-RZ), generic unitary basis (e.g. U), and a
few others.
For a two-qubit decomposition, it can target any supercontrolled basis
(e.g. CNOT, iSWAP, B) or multiple controlled basis
(e.g. CZ, CH, ZZ^.5, ZX^.2, etc.).
- |
The interface for :class:`~.UnitarySynthesisPlugin` has two new
optional properties ``supports_gate_lengths_by_qubit`` and
``supports_gate_errors_by_qubit`` which when set will add the
fields ``gate_lengths_by_qubit`` and ``gate_errors_by_qubit``
respectively to the input options to the plugin's ``run()`` method.
These new fields are an alternative view of the data provided by
``gate_lengths`` and ``gate_errors`` but instead have the form:
``{(qubits,): [Gate, length]}`` (where ``Gate`` is the instance
of :class:`~.Gate` for that definition). This allows plugins to
reason about working with gates of the same type but but that
have different parameters set.
| qiskit/releasenotes/notes/0.24/unitary-synthesis-based-on-errors-8041fcc9584f5db2.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/0.24/unitary-synthesis-based-on-errors-8041fcc9584f5db2.yaml",
"repo_id": "qiskit",
"token_count": 443
} | 279 |
---
features:
- |
A new method, :meth:`~qiskit.dagcircuit.dag.find_bit`, has
been added to the :class:`~qiskit.dagcircuit.DagCircuit` class.
This is a method to get mapping of Qubit and Clbit to positional index.
The method takes a Bit as input, checks whether it's a Qubit or a Clbit,
and then returns the corresponding BitLocations from the respective index
dictionary (_qubit_indices or _clbit_indices).
The BitLocations is a namedtuple which includes the positional index of the
bit in the circuit and a list of registers containing the bit. If the bit
cannot be found or is of an unknown type, it raises a DAGCircuitError. | qiskit/releasenotes/notes/0.25/add-method-for-mapping-qubit-clbit-to-positional-index-6cd43a42f56eb549.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/0.25/add-method-for-mapping-qubit-clbit-to-positional-index-6cd43a42f56eb549.yaml",
"repo_id": "qiskit",
"token_count": 218
} | 280 |
---
deprecations:
- |
The :class:`~qiskit.pulse.instructions.Call` has been deprecated and will
be removed in a future release.
Instead, use the `pulse builder
<https://qiskit.org/documentation/tutorials/circuits_advanced/06_building_pulse_schedules.html>`_
function :func:`~qiskit.pulse.builder.call`
within an active building context.
| qiskit/releasenotes/notes/0.25/deprecate-pulse-Call-instruction-538802d8fad7e257.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/0.25/deprecate-pulse-Call-instruction-538802d8fad7e257.yaml",
"repo_id": "qiskit",
"token_count": 134
} | 281 |
---
fixes:
- |
Fixed an issue in tranpiler passes for padding delays, which did not respect target's constraints
and inserted delays even for qubits not supporting :class:`~.circuit.Delay` instruction.
:class:`~.PadDelay` and :class:`~.PadDynamicalDecoupling` are fixed
so that they do not pad any idle time of qubits such that the target does not support
``Delay`` instructions for the qubits.
Also legacy scheduling passes ``ASAPSchedule`` and ``ALAPSchedule``,
which pad delays internally, are fixed in the same way.
In addition, :func:`transpile` is fixed to call ``PadDelay`` with a ``target`` object
so that it works correctly when called with ``scheduling_method`` option.
Fixed `#9993 <https://github.com/Qiskit/qiskit-terra/issues/9993>`__
| qiskit/releasenotes/notes/0.25/fix-delay-padding-75937bda37ebc3fd.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/0.25/fix-delay-padding-75937bda37ebc3fd.yaml",
"repo_id": "qiskit",
"token_count": 251
} | 282 |
---
fixes:
- |
Fixed an failure of :meth:`.Target.update_from_instruction_schedule_map` when
the argument ``inst_map`` has schedule with unassigned duration.
| qiskit/releasenotes/notes/0.25/fix-update-from-instruction-schedule-map-d1cba4e4db4b679e.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/0.25/fix-update-from-instruction-schedule-map-d1cba4e4db4b679e.yaml",
"repo_id": "qiskit",
"token_count": 56
} | 283 |
---
features:
- |
The OpenQASM 3 exporters (:func:`.qasm3.dump`, :func:`~.qasm3.dumps` and :class:`~.qasm3.Exporter`)
have a new ``allow_aliasing`` argument, which will eventually replace the ``alias_classical_registers``
argument. This controls whether aliasing is permitted for either classical bits or qubits, rather
than the option only being available for classical bits.
upgrade:
- |
The OpenQASM 3 exporters (:func:`.qasm3.dump`, :func:`~.qasm3.dumps` and :class:`~.qasm3.Exporter`)
will now use fewer "register alias" definitions in its output. The circuit described will not
change, but it will now preferentially export in terms of direct ``bit``, ``qubit`` and
``qubit[n]`` types rather than producing a ``_loose_bits`` register and aliasing more registers
off this. This is done to minimise the number of advanced OpenQASM 3 features in use, and to
avoid introducing unnecessary array structure into programmes that do not require it.
| qiskit/releasenotes/notes/0.25/qasm3-alias-refactor-3389bfce3e29e4cf.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/0.25/qasm3-alias-refactor-3389bfce3e29e4cf.yaml",
"repo_id": "qiskit",
"token_count": 310
} | 284 |
---
upgrade:
- |
By default Qiskit builds its compiled extensions using the
`Python Stable ABI <https://docs.python.org/3/c-api/stable.html>`__
with support back to the oldest version of Python supported by Qiskit
(currently 3.8). This means that moving forward there
will be a single precompiled wheels that are shipped on release that
works with all of Qiskit's supported Python versions. There isn't any
expected runtime performance difference using the limited API so it is
enabled by default for all builds now.
Previously, the compiled extensions were built using the version specific API and
would only work with a single Python version. This change was made
to reduce the number of package files we need to build and publish in each
release. When building Qiskit from source there should be no changes
necessary to the build process except that the default tags in the output
filenames will be different to reflect the use of the limited API.
| qiskit/releasenotes/notes/0.25/use-abi3-4a935e0557d3833b.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/0.25/use-abi3-4a935e0557d3833b.yaml",
"repo_id": "qiskit",
"token_count": 262
} | 285 |
---
fixes:
- |
Fixed a bug in :class:`.pulse.Channel` where index validation was done incorrectly and only
raised an error when the index was both non-integer and negative, instead of either.
| qiskit/releasenotes/notes/0.45/channel-validation-bug-fix-c06f8445cecc8478.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/0.45/channel-validation-bug-fix-c06f8445cecc8478.yaml",
"repo_id": "qiskit",
"token_count": 56
} | 286 |
---
fixes:
- |
Fixed :class:`~.CommutationAnalysis` to group gates on a wire into sets, with each
set only containing gates that pairwise commute. This prevents
:class:`~.CommutationCancellation` from performing unsound optimizations.
See `#8020 <https://github.com/Qiskit/qiskit-terra/issues/8020>`__
| qiskit/releasenotes/notes/0.45/fix-commutative-analysis-e74083969db46d0f.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/0.45/fix-commutative-analysis-e74083969db46d0f.yaml",
"repo_id": "qiskit",
"token_count": 107
} | 287 |
---
deprecations:
- |
Passing a circuit to :func:`qiskit.visualization.timeline_drawer` that does not have scheduled
node start-time information is deprecated. Only circuits that have gone through one of the
scheduling analysis passes (for example :class:`.ALAPScheduleAnalysis` or
:class:`.ASAPScheduleAnalysis`) can be visualized. If you have used one of the old-style
scheduling passes (for example :class:`.ALAPSchedule` or :class:`.ASAPSchedule`), you can
propagate the scheduling information by running::
from qiskit import transpile
from qiskit.transpiler import InstructionDurations
scheduled = transpile(
my_old_style_circuit,
optimization_level=0,
scheduling_method="alap",
instruction_durations=InstructionDurations(),
)
This behavior was previously intended to be deprecated in Qiskit 0.37, but due to a bug in the
warning, it was not displayed to users until now. The behavior will be removed in Qiskit 1.0.
| qiskit/releasenotes/notes/0.45/fix-timeline-draw-unscheduled-warning-873f7a24c6b51e2c.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/0.45/fix-timeline-draw-unscheduled-warning-873f7a24c6b51e2c.yaml",
"repo_id": "qiskit",
"token_count": 328
} | 288 |
---
fixes:
- |
The OpenQASM 2 parser (:func:`.qasm2.load` and :func:`~.qasm2.loads`) running in ``strict`` mode
will now correctly emit an error if a ``barrier`` statement has no arguments. When running in
the (default) more permissive mode, an argument-less ``barrier`` statement will continue to
cause a barrier on all qubits currently in scope (the qubits a gate definition affects, or all
the qubits defined by a program, if the statement is in a gate body or in the global scope,
respectively).
- |
The OpenQASM 2 exporter (:meth:`.QuantumCircuit.qasm`) will now no longer attempt
to output ``barrier`` statements that act on no qubits. Such a barrier statement has no effect
in Qiskit either, but is invalid OpenQASM 2.
| qiskit/releasenotes/notes/0.45/qasm2-fix-zero-op-barrier-4af211b119d5b24d.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/0.45/qasm2-fix-zero-op-barrier-4af211b119d5b24d.yaml",
"repo_id": "qiskit",
"token_count": 240
} | 289 |
---
upgrade:
- |
The class constructor arguments `qregs`, `cregs`,
`layout` and `global_phase` for :class:`.visualization.QCircuitImage`
are removed, as they were deprecated in 0.20.
- |
In :class:`.transpiler.CouplingMap` method `subgraph` is removed
as deprecated in 0.20. :meth:`~reduce` can be used in place of method `subgraph`.
- |
The parameter `order` in :class:`.synthesis.SuzukiTrotter`
constructor raises an exception instead of deprecation warning when
set in an odd number. Suzuki product formulae are symmetric and
therefore only defined for even orders.
| qiskit/releasenotes/notes/0.45/removed_deprecation_0.20-17b0ea6a3980eb4f.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/0.45/removed_deprecation_0.20-17b0ea6a3980eb4f.yaml",
"repo_id": "qiskit",
"token_count": 224
} | 290 |
---
upgrade:
- |
The previously deprecated ``qiskit._util`` module has been removed.
``qiskit.util`` should be used instead.
| qiskit/releasenotes/notes/0.9/_util-removal-289fe623948983b8.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/0.9/_util-removal-289fe623948983b8.yaml",
"repo_id": "qiskit",
"token_count": 45
} | 291 |
---
features:
- |
The user config file has several new options:
* The ``circuit_drawer`` field now accepts an `auto` value. When set as
the value for the ``circuit_drawer`` field the default drawer backend
will be `mpl` if it is available, otherwise the `text` backend will be
used.
* A new field ``circuit_mpl_style`` can be used to set the default style
used by the matplotlib circuit drawer. Valid values for this field are
``bw`` and ``default`` to set the default to a black and white or the
default color style respectively.
* A new field ``transpile_optimization_level`` can be used to set the
default transpiler optimization level to use for calls to
``qiskit.compiler.transpile()``. The value can be set to either 0, 1, 2,
or 3.
| qiskit/releasenotes/notes/0.9/user-config-updates-969bd1a0a5e3a0d8.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/0.9/user-config-updates-969bd1a0a5e3a0d8.yaml",
"repo_id": "qiskit",
"token_count": 279
} | 292 |
---
features_circuits:
- |
:class:`~qiskit.circuit.ParameterExpression` (and thus also
:class:`~qiskit.circuit.Parameter`) now support powering: :code:`x**y`
where :code:`x` and :code:`y` can be any combination of
:class:`~qiskit.circuit.ParameterExpression` and number types.
| qiskit/releasenotes/notes/1.0/add-parameter-pow-ff5f8d10813f5733.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/1.0/add-parameter-pow-ff5f8d10813f5733.yaml",
"repo_id": "qiskit",
"token_count": 114
} | 293 |
---
upgrade_transpiler:
- |
The deprecated method ``Target.aquire_alignment`` has been removed. It was marked as deprecated in
Qiskit 0.43 (released 2023-05). The method
:meth:`.Target.acquire_alignment` should be used instead.
| qiskit/releasenotes/notes/1.0/deprecate_aquire_alignment-28f64480ed838328.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/1.0/deprecate_aquire_alignment-28f64480ed838328.yaml",
"repo_id": "qiskit",
"token_count": 81
} | 294 |
---
fixes:
- |
The qubit-argument broadcasting of :meth:`.QuantumCircuit.delay` now correctly produces
individual :class:`~.circuit.Delay` instructions for each qubit, as intended. Previously, when
given certain iterables (such as :class:`set`\ s), it would instead silently produce an invalid
circuit that might fail in unusual locations.
| qiskit/releasenotes/notes/1.0/fix-delay-broadcast-e8762b01dfd7e94f.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/1.0/fix-delay-broadcast-e8762b01dfd7e94f.yaml",
"repo_id": "qiskit",
"token_count": 104
} | 295 |
---
fixes:
- |
Fixed a bug in :class:`~.SabreLayout` where it would fail to add the layout
register information to the property set. This affected circuit visualization, as
``circuit.draw()`` after transpilation with certain optimization levels would show
the full ``Qubit[register]`` label rather than the expected register name
(e.g. ``q0``).
| qiskit/releasenotes/notes/1.0/fix-qreg-visualization-after-layout-42d3e643b923d8bc.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/1.0/fix-qreg-visualization-after-layout-42d3e643b923d8bc.yaml",
"repo_id": "qiskit",
"token_count": 108
} | 296 |
---
features_circuits:
- |
Added a new method, :meth:`.ParameterExpression.numeric`, which converts a fully bound
parameter expression into the most restrictive built-in Python numeric type that accurately
describes the result of the symbolic evaluation. For example, a symbolic integer will become an
:class:`int`, while a symbolic real number will become a :class:`float` and a complex number
will become a :class:`complex`. This method includes several workarounds for peculiarities of
the evaluation contexts of ``symengine``, which can sometimes lead to spurious results when
calling :class:`complex` or :class:`float` on an expression directly.
| qiskit/releasenotes/notes/1.0/parameterexpression.numeric-958d365dadabfb81.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/1.0/parameterexpression.numeric-958d365dadabfb81.yaml",
"repo_id": "qiskit",
"token_count": 175
} | 297 |
---
upgrade_transpiler:
- |
It is no longer allowable to pass ``None`` as the ``qargs`` or ``cargs`` parameters in
:meth:`.DAGCircuit.apply_operation_back` and :meth:`~.DAGCircuit.apply_operation_front`. If you
want to explicitly pass an empty argument, use the empty tuple ``()`` instead.
| qiskit/releasenotes/notes/1.0/remove-dag-none-be220777dc246803.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/1.0/remove-dag-none-be220777dc246803.yaml",
"repo_id": "qiskit",
"token_count": 104
} | 298 |
---
upgrade:
- |
The ``qiskit.algorithms`` module has been removed, following its deprecation in
Qiskit 0.44. The primitive-based algorithms from this module have been migrated to a standalone library (``qiskit_algorithms``)
and can be found on PyPI or `GitHub <https://github.com/qiskit-community/qiskit-algorithms>`_.
The decision to migrate the algorithms module to a separate package
was made to clarify the purpose Qiskit and make a distinction between the tools
and libraries built on top of it.
| qiskit/releasenotes/notes/1.0/remove-qiskit-algorithms-a43541fe24b72208.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/1.0/remove-qiskit-algorithms-a43541fe24b72208.yaml",
"repo_id": "qiskit",
"token_count": 158
} | 299 |
---
features_visualization:
- |
The :func:`.dag_drawer` has been updated for the :class:`.DAGDependency`. These
drawings have a new color scheme, and the nodes now indicate the qubits and
clbits that are used by the node. If the node has a condition, the drawings
will indicate that as well.
.. code-block:: python
from qiskit.circuit import QuantumCircuit
from qiskit.converters import circuit_to_dagdependency
qc = QuantumCircuit(3, 2)
qc.h(0)
qc.cx(0, 1)
qc.cx(0, 2)
qc.x(1)
qc.barrier()
qc.measure(0, 0)
dagdep = circuit_to_dagdependency(qc)
dagdep.draw()
| qiskit/releasenotes/notes/1.0/update-dag-dependency-drawer-d06d4ae660c1cbc2.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/1.0/update-dag-dependency-drawer-d06d4ae660c1cbc2.yaml",
"repo_id": "qiskit",
"token_count": 326
} | 300 |
---
features_synthesis:
- |
Added a new argument, ``use_dag``, to the :meth:`.TwoQubitBasisDecomposer.__call__`
and :meth:`.XXDecomposer.__call__` methods. This argument is used to control whether
a :class:`.DAGCircuit` is returned when calling a :class:`.TwoQubitBasisDecomposer`
or :class:`.XXDecomposer` instance instead of the default :class:`.QuantumCircuit`.
For example::
from qiskit.circuit.library import CXGate
from qiskit.quantum_info import random_unitary
from qiskit.synthesis import TwoQubitBasisDecomposer
decomposer = TwoQubitBasisDecomposer(CXGate(), euler_basis="PSX")
decomposer(random_unitary(4), use_dag=True)
will return a :class:`.DAGCircuit` when calling the :class:`.TwoQubitBasisDecomposer`
instance ``decomposer``.
| qiskit/releasenotes/notes/1.1/add-use-dag-flag-two-qubit-basis-decomposer-024a9ced9833289c.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/1.1/add-use-dag-flag-two-qubit-basis-decomposer-024a9ced9833289c.yaml",
"repo_id": "qiskit",
"token_count": 328
} | 301 |
---
fixes:
- |
Calling :meth:`.EquivalenceLibrary.set_entry` will now correctly update the internal graph
object of the library. Previously, the metadata would be updated, but the graph structure would
be unaltered, meaning that users like :class:`.BasisTranslator` would still use the old rules.
Fixed `#11958 <https://github.com/Qiskit/qiskit/issues/11958>`__.
| qiskit/releasenotes/notes/1.1/fix-equivalence-setentry-5a30b0790666fcf2.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/1.1/fix-equivalence-setentry-5a30b0790666fcf2.yaml",
"repo_id": "qiskit",
"token_count": 119
} | 302 |
---
features_providers:
- |
The :class:`.BasicSimulator` python-based simulator included in :mod:`qiskit.providers.basic_provider`
now includes all the standard gates (:mod:`qiskit.circuit.library .standard_gates`) up to 3 qubits.
| qiskit/releasenotes/notes/1.1/fixes_10852-e197344c5f44b4f1.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/1.1/fixes_10852-e197344c5f44b4f1.yaml",
"repo_id": "qiskit",
"token_count": 83
} | 303 |
---
features_pulse:
- |
The ``assign_parameters`` methods of :class:`.Schedule` and :class:`.ScheduleBlock`
now support assigning a :class:`.ParameterVector` to a list of parameter values
simultaneously in addition to assigning individual :class:`.Parameter` instances to
individual values.
| qiskit/releasenotes/notes/1.1/pulse_parameter_manager_compat_with_ParameterVector-7d31395fd4019827.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/1.1/pulse_parameter_manager_compat_with_ParameterVector-7d31395fd4019827.yaml",
"repo_id": "qiskit",
"token_count": 88
} | 304 |
---
upgrade:
- |
The :func:`.transpile` function has been upgraded to internally convert
`backend` inputs of type :class:`.BackendV1` to :class:`.BackendV2`,
which allows the transpilation pipeline to now access the backend
constraints through a :class:`.Target`. This change does not require any
user action. | qiskit/releasenotes/notes/1.1/use-target-in-transpile-7c04b14549a11f40.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/1.1/use-target-in-transpile-7c04b14549a11f40.yaml",
"repo_id": "qiskit",
"token_count": 105
} | 305 |
---
features_transpiler:
- |
The implementation of the :class:`.DAGCircuit` has been rewritten in Rust. This rewrite of
the Python class should be fully API compatible with the previous Python implementation of
the class. While the class was previously implemented using
`rustworkx <https://www.rustworkx.org/>`__ and its underlying data graph structure existed
in Rust, the implementation of the class and all the data was stored in Python. This new
version of :class:`.DAGCircuit` stores a Rust native representation for all its data and
is fully implemented in Rust. This new implementation should be more efficient in memory
usage as it compresses the qubit and clbit representation for instructions at rest.
It also enables speed up for transpiler passes as they can fully manipulate a
:class:`.DAGCircuit` from Rust.
upgrade_transpiler:
- |
:class:`.DAGNode` objects (and its subclasses :class:`.DAGInNode`, :class:`.DAGOutNode`, and
:class:`.DAGOpNode`) no longer return references to the same underlying object from
:class:`.DAGCircuit` methods. This was never a guarantee before that all returned nodes would
be shared reference to the same object, but with the migration of the :class:`.DAGCircuit` to
Rust when a :class:`.DAGNode` a new :class:`.DAGNode` instance is generated on the fly when
a node is returned to Python. These objects will evaluate as equal using ``==`` or similar
checks that rely on ``__eq__`` but will no longer identify as the same object.
- |
The :class:`.DAGOpNode` instances returned from the :class:`.DAGCircuit` are no longer shared
references to the underlying data stored on the DAG. In previous release it was possible to
do something like::
for node in dag.op_nodes():
node.op = new_op
however this type of mutation was always unsound as it could break the DAG's internal caching
and cause corruption of the data structure. Instead you should use the API provided by
:class:`.DAGCircuit` for mutation such as :meth:`.DAGCircuit.substitute_node`,
:meth:`.DAGCircuit.substitute_node_with_dag`, or :meth:`.DAGCircuit.contract_node`. For example
the above code block would become::
for node in dag.op_nodes():
dag.substitute_node(node, new_op)
This is similar to an upgrade note from 1.2.0 where this was noted on for mutation of the
:attr:`.DAGOpNode.op` attribute, not the :class:`.DAGOpNode` itself. However in 1.3 this extends
to the entire object, not just it's inner ``op`` attribute. In general this type of mutation was
always unsound and not supported, but could previously have potentially worked in some cases.
fixes:
- |
Fixed an issue with :meth:`.DAGCircuit.apply_operation_back` and
:meth:`.DAGCircuit.apply_operation_front` where previously if you set a
:class:`.Clbit` object to the input for the ``qargs`` argument it would silently be accepted.
This has been fixed so the type mismatch is correctly identified and an exception is raised.
| qiskit/releasenotes/notes/dag-oxide-60b3d7219cb21703.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/dag-oxide-60b3d7219cb21703.yaml",
"repo_id": "qiskit",
"token_count": 926
} | 306 |
---
fixes:
- |
Add more Clifford gates to the :class:`.CollectCliffords()` transpiler pass.
In particular, we have added the gates :class:`ECRGate()`, :class:`DCXGate()`,
:class:`iSWAPGate()`, :class:`SXGate()` and :class:`SXdgGate()` to this transpiler pass.
| qiskit/releasenotes/notes/fix-collect-clifford-83af26d98b8c69e8.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/fix-collect-clifford-83af26d98b8c69e8.yaml",
"repo_id": "qiskit",
"token_count": 106
} | 307 |
---
fixes:
- |
Fixed an oversight in the :class:`.Commuting2qGateRouter` transpiler pass where the qreg permutations
were not added to the pass property set, so they would have to be tracked manually by the user. Now it's
possible to access the permutation through the output circuit's ``layout`` property and plug the pass
into any transpilation pipeline without loss of information.
| qiskit/releasenotes/notes/fix-swap-router-layout-f28cf0a2de7976a8.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/fix-swap-router-layout-f28cf0a2de7976a8.yaml",
"repo_id": "qiskit",
"token_count": 107
} | 308 |
---
features_synthesis:
- |
Port :func:`.synth_permutation_basic`, used to synthesize qubit permutations, to Rust.
| qiskit/releasenotes/notes/oxidize-permbasic-be27578187ac472f.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/oxidize-permbasic-be27578187ac472f.yaml",
"repo_id": "qiskit",
"token_count": 42
} | 309 |
---
features_qasm:
- |
The internal symbol table of the OpenQASM 3 exporter (:mod:`qiskit.qasm3`) has been rewritten,
which should result in cleaner outputs when using Qiskit standard-library gates that are not in
the OpenQASM 3 standard-library headers, and more deterministic outputs. For example, using
several :class:`.RZXGate`\ s will now result in only a single parametric definition, and when
naming collisions occur, the symbol table will assign a deterministic counter to make names
unique, rather than a non-deterministic integer (previously, the object identity was used).
fixes:
- |
The OpenQASM 3 exporter (:mod:`qiskit.qasm3`) will now correctly export multiple instances of
:class:`.PauliEvolutionGate` from a circuit. Previously, only a single instance would be exported,
and all other instances would silently use the same (incorrect) version.
- |
The OpenQASM 3 exporter (:mod:`qiskit.qasm3`) will now correctly escape gate names. Previously,
a gate whose name was an invalid OpenQASM 3 identifier would cause invalid OpenQASM 3 to be
generated.
| qiskit/releasenotes/notes/qasm3-symbol-table-efad35629639c77d.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/qasm3-symbol-table-efad35629639c77d.yaml",
"repo_id": "qiskit",
"token_count": 330
} | 310 |
// Originally source from the QUEKO benchmark suite
// https://github.com/UCLA-VAST/QUEKO-benchmark
// A benchmark of the impact of gate density for IBMQ Tokyo with a depth of 45
OPENQASM 2.0;
include "qelib1.inc";
qreg q[20];
cx q[12], q[9];
cx q[6], q[12];
cx q[8], q[6];
cx q[6], q[10];
cx q[7], q[6];
cx q[6], q[10];
cx q[6], q[10];
cx q[6], q[10];
cx q[11], q[6];
cx q[11], q[6];
cx q[11], q[6];
cx q[8], q[11];
cx q[8], q[7];
cx q[7], q[6];
cx q[15], q[7];
cx q[7], q[13];
cx q[13], q[9];
cx q[12], q[9];
cx q[12], q[10];
cx q[12], q[10];
cx q[12], q[10];
cx q[6], q[10];
cx q[6], q[10];
cx q[9], q[10];
cx q[6], q[10];
cx q[6], q[9];
cx q[6], q[9];
cx q[6], q[12];
cx q[6], q[12];
cx q[12], q[9];
cx q[12], q[9];
cx q[9], q[10];
cx q[6], q[10];
cx q[11], q[6];
cx q[11], q[6];
cx q[6], q[9];
cx q[6], q[10];
cx q[9], q[10];
cx q[9], q[10];
cx q[12], q[10];
cx q[12], q[10];
cx q[12], q[10];
cx q[6], q[10];
cx q[6], q[10];
cx q[9], q[10];
| qiskit/test/benchmarks/qasm/20QBT_45CYC_.0D1_.1D2_3.qasm/0 | {
"file_path": "qiskit/test/benchmarks/qasm/20QBT_45CYC_.0D1_.1D2_3.qasm",
"repo_id": "qiskit",
"token_count": 572
} | 311 |
OPENQASM 2.0;
include "qelib1.inc";
qreg q[16];
creg c[16];
h q[0];
rz(-0.7854) q[0];
cx q[0],q[1];
rz(0.7854) q[0];
cx q[0],q[1];
rz(-0.3927) q[0];
cx q[0],q[2];
rz(0.3927) q[0];
cx q[0],q[2];
rz(-0.19635) q[0];
cx q[0],q[3];
rz(0.19635) q[0];
cx q[0],q[3];
rz(-0.09815) q[0];
cx q[0],q[4];
rz(0.09815) q[0];
cx q[0],q[4];
rz(-0.0491) q[0];
cx q[0],q[5];
rz(0.0491) q[0];
cx q[0],q[5];
rz(-0.02455) q[0];
cx q[0],q[6];
rz(0.02455) q[0];
cx q[0],q[6];
rz(-0.01225) q[0];
cx q[0],q[7];
rz(0.01225) q[0];
cx q[0],q[7];
rz(-0.00615) q[0];
cx q[0],q[8];
rz(0.00615) q[0];
cx q[0],q[8];
rz(-0.00305) q[0];
cx q[0],q[9];
rz(0.00305) q[0];
cx q[0],q[9];
rz(-0.00155) q[0];
cx q[0],q[10];
rz(0.00155) q[0];
cx q[0],q[10];
rz(-0.00075) q[0];
cx q[0],q[11];
rz(0.00075) q[0];
cx q[0],q[11];
rz(-0.0004) q[0];
cx q[0],q[12];
rz(0.0004) q[0];
cx q[0],q[12];
rz(-0.0002) q[0];
cx q[0],q[13];
rz(0.0002) q[0];
cx q[0],q[13];
rz(-0.0001) q[0];
cx q[0],q[14];
rz(0.0001) q[0];
cx q[0],q[14];
rz(-0.00005) q[0];
cx q[0],q[15];
rz(0.00005) q[0];
cx q[0],q[15];
h q[1];
rz(-0.7854) q[1];
cx q[1],q[2];
rz(0.7854) q[1];
cx q[1],q[2];
rz(-0.3927) q[1];
cx q[1],q[3];
rz(0.3927) q[1];
cx q[1],q[3];
rz(-0.19635) q[1];
cx q[1],q[4];
rz(0.19635) q[1];
cx q[1],q[4];
rz(-0.09815) q[1];
cx q[1],q[5];
rz(0.09815) q[1];
cx q[1],q[5];
rz(-0.0491) q[1];
cx q[1],q[6];
rz(0.0491) q[1];
cx q[1],q[6];
rz(-0.02455) q[1];
cx q[1],q[7];
rz(0.02455) q[1];
cx q[1],q[7];
rz(-0.01225) q[1];
cx q[1],q[8];
rz(0.01225) q[1];
cx q[1],q[8];
rz(-0.00615) q[1];
cx q[1],q[9];
rz(0.00615) q[1];
cx q[1],q[9];
rz(-0.00305) q[1];
cx q[1],q[10];
rz(0.00305) q[1];
cx q[1],q[10];
rz(-0.00155) q[1];
cx q[1],q[11];
rz(0.00155) q[1];
cx q[1],q[11];
rz(-0.00075) q[1];
cx q[1],q[12];
rz(0.00075) q[1];
cx q[1],q[12];
rz(-0.0004) q[1];
cx q[1],q[13];
rz(0.0004) q[1];
cx q[1],q[13];
rz(-0.0002) q[1];
cx q[1],q[14];
rz(0.0002) q[1];
cx q[1],q[14];
rz(-0.0001) q[1];
cx q[1],q[15];
rz(0.0001) q[1];
cx q[1],q[15];
h q[2];
rz(-0.7854) q[2];
cx q[2],q[3];
rz(0.7854) q[2];
cx q[2],q[3];
rz(-0.3927) q[2];
cx q[2],q[4];
rz(0.3927) q[2];
cx q[2],q[4];
rz(-0.19635) q[2];
cx q[2],q[5];
rz(0.19635) q[2];
cx q[2],q[5];
rz(-0.09815) q[2];
cx q[2],q[6];
rz(0.09815) q[2];
cx q[2],q[6];
rz(-0.0491) q[2];
cx q[2],q[7];
rz(0.0491) q[2];
cx q[2],q[7];
rz(-0.02455) q[2];
cx q[2],q[8];
rz(0.02455) q[2];
cx q[2],q[8];
rz(-0.01225) q[2];
cx q[2],q[9];
rz(0.01225) q[2];
cx q[2],q[9];
rz(-0.00615) q[2];
cx q[2],q[10];
rz(0.00615) q[2];
cx q[2],q[10];
rz(-0.00305) q[2];
cx q[2],q[11];
rz(0.00305) q[2];
cx q[2],q[11];
rz(-0.00155) q[2];
cx q[2],q[12];
rz(0.00155) q[2];
cx q[2],q[12];
rz(-0.00075) q[2];
cx q[2],q[13];
rz(0.00075) q[2];
cx q[2],q[13];
rz(-0.0004) q[2];
cx q[2],q[14];
rz(0.0004) q[2];
cx q[2],q[14];
rz(-0.0002) q[2];
cx q[2],q[15];
rz(0.0002) q[2];
cx q[2],q[15];
h q[3];
rz(-0.7854) q[3];
cx q[3],q[4];
rz(0.7854) q[3];
cx q[3],q[4];
rz(-0.3927) q[3];
cx q[3],q[5];
rz(0.3927) q[3];
cx q[3],q[5];
rz(-0.19635) q[3];
cx q[3],q[6];
rz(0.19635) q[3];
cx q[3],q[6];
rz(-0.09815) q[3];
cx q[3],q[7];
rz(0.09815) q[3];
cx q[3],q[7];
rz(-0.0491) q[3];
cx q[3],q[8];
rz(0.0491) q[3];
cx q[3],q[8];
rz(-0.02455) q[3];
cx q[3],q[9];
rz(0.02455) q[3];
cx q[3],q[9];
rz(-0.01225) q[3];
cx q[3],q[10];
rz(0.01225) q[3];
cx q[3],q[10];
rz(-0.00615) q[3];
cx q[3],q[11];
rz(0.00615) q[3];
cx q[3],q[11];
rz(-0.00305) q[3];
cx q[3],q[12];
rz(0.00305) q[3];
cx q[3],q[12];
rz(-0.00155) q[3];
cx q[3],q[13];
rz(0.00155) q[3];
cx q[3],q[13];
rz(-0.00075) q[3];
cx q[3],q[14];
rz(0.00075) q[3];
cx q[3],q[14];
rz(-0.0004) q[3];
cx q[3],q[15];
rz(0.0004) q[3];
cx q[3],q[15];
h q[4];
rz(-0.7854) q[4];
cx q[4],q[5];
rz(0.7854) q[4];
cx q[4],q[5];
rz(-0.3927) q[4];
cx q[4],q[6];
rz(0.3927) q[4];
cx q[4],q[6];
rz(-0.19635) q[4];
cx q[4],q[7];
rz(0.19635) q[4];
cx q[4],q[7];
rz(-0.09815) q[4];
cx q[4],q[8];
rz(0.09815) q[4];
cx q[4],q[8];
rz(-0.0491) q[4];
cx q[4],q[9];
rz(0.0491) q[4];
cx q[4],q[9];
rz(-0.02455) q[4];
cx q[4],q[10];
rz(0.02455) q[4];
cx q[4],q[10];
rz(-0.01225) q[4];
cx q[4],q[11];
rz(0.01225) q[4];
cx q[4],q[11];
rz(-0.00615) q[4];
cx q[4],q[12];
rz(0.00615) q[4];
cx q[4],q[12];
rz(-0.00305) q[4];
cx q[4],q[13];
rz(0.00305) q[4];
cx q[4],q[13];
rz(-0.00155) q[4];
cx q[4],q[14];
rz(0.00155) q[4];
cx q[4],q[14];
rz(-0.00075) q[4];
cx q[4],q[15];
rz(0.00075) q[4];
cx q[4],q[15];
h q[5];
rz(-0.7854) q[5];
cx q[5],q[6];
rz(0.7854) q[5];
cx q[5],q[6];
rz(-0.3927) q[5];
cx q[5],q[7];
rz(0.3927) q[5];
cx q[5],q[7];
rz(-0.19635) q[5];
cx q[5],q[8];
rz(0.19635) q[5];
cx q[5],q[8];
rz(-0.09815) q[5];
cx q[5],q[9];
rz(0.09815) q[5];
cx q[5],q[9];
rz(-0.0491) q[5];
cx q[5],q[10];
rz(0.0491) q[5];
cx q[5],q[10];
rz(-0.02455) q[5];
cx q[5],q[11];
rz(0.02455) q[5];
cx q[5],q[11];
rz(-0.01225) q[5];
cx q[5],q[12];
rz(0.01225) q[5];
cx q[5],q[12];
rz(-0.00615) q[5];
cx q[5],q[13];
rz(0.00615) q[5];
cx q[5],q[13];
rz(-0.00305) q[5];
cx q[5],q[14];
rz(0.00305) q[5];
cx q[5],q[14];
rz(-0.00155) q[5];
cx q[5],q[15];
rz(0.00155) q[5];
cx q[5],q[15];
h q[6];
rz(-0.7854) q[6];
cx q[6],q[7];
rz(0.7854) q[6];
cx q[6],q[7];
rz(-0.3927) q[6];
cx q[6],q[8];
rz(0.3927) q[6];
cx q[6],q[8];
rz(-0.19635) q[6];
cx q[6],q[9];
rz(0.19635) q[6];
cx q[6],q[9];
rz(-0.09815) q[6];
cx q[6],q[10];
rz(0.09815) q[6];
cx q[6],q[10];
rz(-0.0491) q[6];
cx q[6],q[11];
rz(0.0491) q[6];
cx q[6],q[11];
rz(-0.02455) q[6];
cx q[6],q[12];
rz(0.02455) q[6];
cx q[6],q[12];
rz(-0.01225) q[6];
cx q[6],q[13];
rz(0.01225) q[6];
cx q[6],q[13];
rz(-0.00615) q[6];
cx q[6],q[14];
rz(0.00615) q[6];
cx q[6],q[14];
rz(-0.00305) q[6];
cx q[6],q[15];
rz(0.00305) q[6];
cx q[6],q[15];
h q[7];
rz(-0.7854) q[7];
cx q[7],q[8];
rz(0.7854) q[7];
cx q[7],q[8];
rz(-0.3927) q[7];
cx q[7],q[9];
rz(0.3927) q[7];
cx q[7],q[9];
rz(-0.19635) q[7];
cx q[7],q[10];
rz(0.19635) q[7];
cx q[7],q[10];
rz(-0.09815) q[7];
cx q[7],q[11];
rz(0.09815) q[7];
cx q[7],q[11];
rz(-0.0491) q[7];
cx q[7],q[12];
rz(0.0491) q[7];
cx q[7],q[12];
rz(-0.02455) q[7];
cx q[7],q[13];
rz(0.02455) q[7];
cx q[7],q[13];
rz(-0.01225) q[7];
cx q[7],q[14];
rz(0.01225) q[7];
cx q[7],q[14];
rz(-0.00615) q[7];
cx q[7],q[15];
rz(0.00615) q[7];
cx q[7],q[15];
h q[8];
rz(-0.7854) q[8];
cx q[8],q[9];
rz(0.7854) q[8];
cx q[8],q[9];
rz(-0.3927) q[8];
cx q[8],q[10];
rz(0.3927) q[8];
cx q[8],q[10];
rz(-0.19635) q[8];
cx q[8],q[11];
rz(0.19635) q[8];
cx q[8],q[11];
rz(-0.09815) q[8];
cx q[8],q[12];
rz(0.09815) q[8];
cx q[8],q[12];
rz(-0.0491) q[8];
cx q[8],q[13];
rz(0.0491) q[8];
cx q[8],q[13];
rz(-0.02455) q[8];
cx q[8],q[14];
rz(0.02455) q[8];
cx q[8],q[14];
rz(-0.01225) q[8];
cx q[8],q[15];
rz(0.01225) q[8];
cx q[8],q[15];
h q[9];
rz(-0.7854) q[9];
cx q[9],q[10];
rz(0.7854) q[9];
cx q[9],q[10];
rz(-0.3927) q[9];
cx q[9],q[11];
rz(0.3927) q[9];
cx q[9],q[11];
rz(-0.19635) q[9];
cx q[9],q[12];
rz(0.19635) q[9];
cx q[9],q[12];
rz(-0.09815) q[9];
cx q[9],q[13];
rz(0.09815) q[9];
cx q[9],q[13];
rz(-0.0491) q[9];
cx q[9],q[14];
rz(0.0491) q[9];
cx q[9],q[14];
rz(-0.02455) q[9];
cx q[9],q[15];
rz(0.02455) q[9];
cx q[9],q[15];
h q[10];
rz(-0.7854) q[10];
cx q[10],q[11];
rz(0.7854) q[10];
cx q[10],q[11];
rz(-0.3927) q[10];
cx q[10],q[12];
rz(0.3927) q[10];
cx q[10],q[12];
rz(-0.19635) q[10];
cx q[10],q[13];
rz(0.19635) q[10];
cx q[10],q[13];
rz(-0.09815) q[10];
cx q[10],q[14];
rz(0.09815) q[10];
cx q[10],q[14];
rz(-0.0491) q[10];
cx q[10],q[15];
rz(0.0491) q[10];
cx q[10],q[15];
h q[11];
rz(-0.7854) q[11];
cx q[11],q[12];
rz(0.7854) q[11];
cx q[11],q[12];
rz(-0.3927) q[11];
cx q[11],q[13];
rz(0.3927) q[11];
cx q[11],q[13];
rz(-0.19635) q[11];
cx q[11],q[14];
rz(0.19635) q[11];
cx q[11],q[14];
rz(-0.09815) q[11];
cx q[11],q[15];
rz(0.09815) q[11];
cx q[11],q[15];
h q[12];
rz(-0.7854) q[12];
cx q[12],q[13];
rz(0.7854) q[12];
cx q[12],q[13];
rz(-0.3927) q[12];
cx q[12],q[14];
rz(0.3927) q[12];
cx q[12],q[14];
rz(-0.19635) q[12];
cx q[12],q[15];
rz(0.19635) q[12];
cx q[12],q[15];
h q[13];
rz(-0.7854) q[13];
cx q[13],q[14];
rz(0.7854) q[13];
cx q[13],q[14];
rz(-0.3927) q[13];
cx q[13],q[15];
rz(0.3927) q[13];
cx q[13],q[15];
h q[14];
rz(-0.7854) q[14];
cx q[14],q[15];
rz(0.7854) q[14];
cx q[14],q[15];
h q[15];
h q[0];
h q[1];
h q[2];
h q[3];
h q[4];
h q[5];
h q[6];
h q[7];
h q[8];
h q[9];
h q[10];
h q[11];
h q[12];
h q[13];
h q[14];
h q[15];
| qiskit/test/benchmarks/qasm/time_qft_16.qasm/0 | {
"file_path": "qiskit/test/benchmarks/qasm/time_qft_16.qasm",
"repo_id": "qiskit",
"token_count": 5976
} | 312 |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the global rotation circuit."""
import unittest
import numpy as np
from qiskit.circuit import QuantumCircuit
from qiskit.circuit.library import GR, GRX, GRY, GRZ, RGate, RZGate
from test import QiskitTestCase # pylint: disable=wrong-import-order
class TestGlobalRLibrary(QiskitTestCase):
"""Test library of global R gates."""
def test_gr_equivalence(self):
"""Test global R gate is same as 3 individual R gates."""
circuit = GR(num_qubits=3, theta=np.pi / 3, phi=2 * np.pi / 3)
expected = QuantumCircuit(3, name="gr")
for i in range(3):
expected.append(RGate(theta=np.pi / 3, phi=2 * np.pi / 3), [i])
self.assertEqual(expected, circuit.decompose())
def test_grx_equivalence(self):
"""Test global RX gates is same as 3 individual RX gates."""
circuit = GRX(num_qubits=3, theta=np.pi / 3)
expected = GR(num_qubits=3, theta=np.pi / 3, phi=0)
self.assertEqual(expected, circuit)
def test_gry_equivalence(self):
"""Test global RY gates is same as 3 individual RY gates."""
circuit = GRY(num_qubits=3, theta=np.pi / 3)
expected = GR(num_qubits=3, theta=np.pi / 3, phi=np.pi / 2)
self.assertEqual(expected, circuit)
def test_grz_equivalence(self):
"""Test global RZ gate is same as 3 individual RZ gates."""
circuit = GRZ(num_qubits=3, phi=2 * np.pi / 3)
expected = QuantumCircuit(3, name="grz")
for i in range(3):
expected.append(RZGate(phi=2 * np.pi / 3), [i])
self.assertEqual(expected, circuit)
if __name__ == "__main__":
unittest.main()
| qiskit/test/python/circuit/library/test_global_r.py/0 | {
"file_path": "qiskit/test/python/circuit/library/test_global_r.py",
"repo_id": "qiskit",
"token_count": 839
} | 313 |
# 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 the phase oracle circuits."""
import unittest
from ddt import ddt, data, unpack
from numpy import sqrt, isclose
from qiskit.circuit import QuantumCircuit
from qiskit.circuit.library import PhaseOracle
from qiskit.quantum_info import Statevector
from qiskit.utils.optionals import HAS_TWEEDLEDUM
from test import QiskitTestCase # pylint: disable=wrong-import-order
@unittest.skipUnless(HAS_TWEEDLEDUM, "Tweedledum is required for these tests")
@ddt
class TestPhaseOracle(QiskitTestCase):
"""Test phase oracle object."""
@data(
("x | x", "1", True),
("x & x", "0", False),
("(x0 & x1 | ~x2) ^ x4", "0110", False),
("xx & xxx | ( ~z ^ zz)", "0111", True),
)
@unpack
def test_evaluate_bitstring(self, expression, input_bitstring, expected):
"""PhaseOracle(...).evaluate_bitstring"""
oracle = PhaseOracle(expression)
result = oracle.evaluate_bitstring(input_bitstring)
self.assertEqual(result, expected)
@data(
("x | x", [1]),
("x & y", [3]),
("(x0 & x1 | ~x2) ^ x4", [0, 1, 2, 3, 7, 12, 13, 14]),
("x & y ^ ( ~z1 | z2)", [0, 1, 2, 7, 8, 9, 10, 12, 13, 14]),
)
@unpack
def test_statevector(self, expression, good_states):
"""Circuit generation"""
oracle = PhaseOracle(expression)
num_qubits = oracle.num_qubits
circuit = QuantumCircuit(num_qubits)
circuit.h(range(num_qubits))
circuit.compose(oracle, inplace=True)
statevector = Statevector.from_instruction(circuit)
valid_state = -1 / sqrt(2**num_qubits)
invalid_state = 1 / sqrt(2**num_qubits)
states = list(range(2**num_qubits))
expected_valid = [state in good_states for state in states]
result_valid = [isclose(statevector.data[state], valid_state) for state in states]
expected_invalid = [state not in good_states for state in states]
result_invalid = [isclose(statevector.data[state], invalid_state) for state in states]
self.assertListEqual(expected_valid, result_valid)
self.assertListEqual(expected_invalid, result_invalid)
@data(
("((A & C) | (B & D)) & ~(C & D)", None, [3, 7, 12, 13]),
("((A & C) | (B & D)) & ~(C & D)", ["A", "B", "C", "D"], [5, 7, 10, 11]),
)
@unpack
def test_variable_order(self, expression, var_order, good_states):
"""Circuit generation"""
oracle = PhaseOracle(expression, var_order=var_order)
num_qubits = oracle.num_qubits
circuit = QuantumCircuit(num_qubits)
circuit.h(range(num_qubits))
circuit.compose(oracle, inplace=True)
statevector = Statevector.from_instruction(circuit)
valid_state = -1 / sqrt(2**num_qubits)
invalid_state = 1 / sqrt(2**num_qubits)
states = list(range(2**num_qubits))
expected_valid = [state in good_states for state in states]
result_valid = [isclose(statevector.data[state], valid_state) for state in states]
expected_invalid = [state not in good_states for state in states]
result_invalid = [isclose(statevector.data[state], invalid_state) for state in states]
self.assertListEqual(expected_valid, result_valid)
self.assertListEqual(expected_invalid, result_invalid)
if __name__ == "__main__":
unittest.main()
| qiskit/test/python/circuit/library/test_phase_oracle.py/0 | {
"file_path": "qiskit/test/python/circuit/library/test_phase_oracle.py",
"repo_id": "qiskit",
"token_count": 1549
} | 314 |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test Qiskit's QuantumCircuit class."""
import copy
import pickle
import numpy as np
from ddt import data, ddt
from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister
from qiskit.circuit import Gate, Instruction, Measure, Parameter, Barrier, AnnotatedOperation
from qiskit.circuit.bit import Bit
from qiskit.circuit.classical import expr, types
from qiskit.circuit.classicalregister import Clbit
from qiskit.circuit.exceptions import CircuitError
from qiskit.circuit.controlflow import IfElseOp
from qiskit.circuit.library import CXGate, HGate
from qiskit.circuit.library.standard_gates import SGate
from qiskit.circuit.quantumcircuit import BitLocations
from qiskit.circuit.quantumcircuitdata import CircuitInstruction
from qiskit.circuit.quantumregister import AncillaQubit, AncillaRegister, Qubit
from qiskit.providers.basic_provider import BasicSimulator
from qiskit.pulse import DriveChannel, Gaussian, Play, Schedule
from qiskit.quantum_info import Operator
from test import QiskitTestCase # pylint: disable=wrong-import-order
@ddt
class TestCircuitOperations(QiskitTestCase):
"""QuantumCircuit Operations tests."""
@data(0, 1, -1, -2)
def test_append_resolves_integers(self, index):
"""Test that integer arguments to append are correctly resolved."""
# We need to assume that appending ``Bit`` instances will always work, so we have something
# to test against.
qubits = [Qubit(), Qubit()]
clbits = [Clbit(), Clbit()]
test = QuantumCircuit(qubits, clbits)
test.append(Measure(), [index], [index])
expected = QuantumCircuit(qubits, clbits)
expected.append(Measure(), [qubits[index]], [clbits[index]])
self.assertEqual(test, expected)
@data(np.int32(0), np.int8(-1), np.uint64(1))
def test_append_resolves_numpy_integers(self, index):
"""Test that Numpy's integers can be used to reference qubits and clbits."""
qubits = [Qubit(), Qubit()]
clbits = [Clbit(), Clbit()]
test = QuantumCircuit(qubits, clbits)
test.append(Measure(), [index], [index])
expected = QuantumCircuit(qubits, clbits)
expected.append(Measure(), [qubits[int(index)]], [clbits[int(index)]])
self.assertEqual(test, expected)
@data(
slice(0, 2),
slice(None, 1),
slice(1, None),
slice(None, None),
slice(0, 2, 2),
slice(2, -1, -1),
slice(1000, 1003),
)
def test_append_resolves_slices(self, index):
"""Test that slices can be used to reference qubits and clbits with the same semantics that
they have on lists."""
qregs = [QuantumRegister(2), QuantumRegister(1)]
cregs = [ClassicalRegister(1), ClassicalRegister(2)]
test = QuantumCircuit(*qregs, *cregs)
test.append(Measure(), [index], [index])
expected = QuantumCircuit(*qregs, *cregs)
for qubit, clbit in zip(expected.qubits[index], expected.clbits[index]):
expected.append(Measure(), [qubit], [clbit])
self.assertEqual(test, expected)
def test_append_resolves_scalar_numpy_array(self):
"""Test that size-1 Numpy arrays can be used to index arguments. These arrays can be passed
to ``int``, which means they sometimes might be involved in spurious casts."""
test = QuantumCircuit(1, 1)
test.append(Measure(), [np.array([0])], [np.array([0])])
expected = QuantumCircuit(1, 1)
expected.measure(0, 0)
self.assertEqual(test, expected)
@data([3], [-3], [0, 1, 3])
def test_append_rejects_out_of_range_input(self, specifier):
"""Test that append rejects an integer that's out of range."""
test = QuantumCircuit(2, 2)
with self.subTest("qubit"), self.assertRaisesRegex(CircuitError, "out of range"):
opaque = Instruction("opaque", len(specifier), 1, [])
test.append(opaque, specifier, [0])
with self.subTest("clbit"), self.assertRaisesRegex(CircuitError, "out of range"):
opaque = Instruction("opaque", 1, len(specifier), [])
test.append(opaque, [0], specifier)
def test_append_rejects_bits_not_in_circuit(self):
"""Test that append rejects bits that are not in the circuit."""
test = QuantumCircuit(2, 2)
with self.subTest("qubit"), self.assertRaisesRegex(CircuitError, "not in the circuit"):
test.append(Measure(), [Qubit()], [test.clbits[0]])
with self.subTest("clbit"), self.assertRaisesRegex(CircuitError, "not in the circuit"):
test.append(Measure(), [test.qubits[0]], [Clbit()])
with self.subTest("qubit list"), self.assertRaisesRegex(CircuitError, "not in the circuit"):
test.append(Measure(), [[test.qubits[0], Qubit()]], [test.clbits])
with self.subTest("clbit list"), self.assertRaisesRegex(CircuitError, "not in the circuit"):
test.append(Measure(), [test.qubits], [[test.clbits[0], Clbit()]])
def test_append_rejects_bit_of_wrong_type(self):
"""Test that append rejects bits of the wrong type in an argument list."""
qubits = [Qubit(), Qubit()]
clbits = [Clbit(), Clbit()]
test = QuantumCircuit(qubits, clbits)
with self.subTest("c to q"), self.assertRaisesRegex(CircuitError, "Incorrect bit type"):
test.append(Measure(), [clbits[0]], [clbits[1]])
with self.subTest("q to c"), self.assertRaisesRegex(CircuitError, "Incorrect bit type"):
test.append(Measure(), [qubits[0]], [qubits[1]])
with self.subTest("none to q"), self.assertRaisesRegex(CircuitError, "Incorrect bit type"):
test.append(Measure(), [Bit()], [clbits[0]])
with self.subTest("none to c"), self.assertRaisesRegex(CircuitError, "Incorrect bit type"):
test.append(Measure(), [qubits[0]], [Bit()])
with self.subTest("none list"), self.assertRaisesRegex(CircuitError, "Incorrect bit type"):
test.append(Measure(), [[qubits[0], Bit()]], [[clbits[0], Bit()]])
@data(0.0, 1.0, 1.0 + 0.0j, "0")
def test_append_rejects_wrong_types(self, specifier):
"""Test that various bad inputs are rejected, both given loose or in sublists."""
test = QuantumCircuit(2, 2)
# Use a default Instruction to be sure that there's not overridden broadcasting.
opaque = Instruction("opaque", 1, 1, [])
with self.subTest("q"), self.assertRaisesRegex(CircuitError, "Invalid bit index"):
test.append(opaque, [specifier], [0])
with self.subTest("c"), self.assertRaisesRegex(CircuitError, "Invalid bit index"):
test.append(opaque, [0], [specifier])
with self.subTest("q list"), self.assertRaisesRegex(CircuitError, "Invalid bit index"):
test.append(opaque, [[specifier]], [[0]])
with self.subTest("c list"), self.assertRaisesRegex(CircuitError, "Invalid bit index"):
test.append(opaque, [[0]], [[specifier]])
@data([], [0], [0, 1, 2])
def test_append_rejects_bad_arguments_opaque(self, bad_arg):
"""Test that a suitable exception is raised when there is an argument mismatch."""
inst = QuantumCircuit(2, 2).to_instruction()
qc = QuantumCircuit(3, 3)
with self.assertRaisesRegex(CircuitError, "The amount of qubit arguments"):
qc.append(inst, bad_arg, [0, 1])
with self.assertRaisesRegex(CircuitError, "The amount of clbit arguments"):
qc.append(inst, [0, 1], bad_arg)
with self.assertRaisesRegex(CircuitError, "The amount of qubit arguments"):
qc.append(Barrier(4), bad_arg)
def test_anding_self(self):
"""Test that qc &= qc finishes, which can be prone to infinite while-loops.
This can occur e.g. when a user tries
>>> other_qc = qc
>>> other_qc &= qc # or qc2.compose(qc)
"""
qc = QuantumCircuit(1)
qc.x(0) # must contain at least one operation to end up in a infinite while-loop
# attempt addition, times out if qc is added via reference
qc &= qc
# finally, qc should contain two X gates
self.assertEqual(["x", "x"], [x.operation.name for x in qc.data])
def test_compose_circuit(self):
"""Test composing two circuits"""
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
qc1 = QuantumCircuit(qr, cr)
qc2 = QuantumCircuit(qr, cr)
qc1.h(qr[0])
qc1.measure(qr[0], cr[0])
qc2.measure(qr[1], cr[1])
qc3 = qc1.compose(qc2)
backend = BasicSimulator()
shots = 1024
result = backend.run(qc3, shots=shots, seed_simulator=78).result()
counts = result.get_counts()
target = {"00": shots / 2, "01": shots / 2}
threshold = 0.04 * shots
self.assertDictEqual(qc3.count_ops(), {"h": 1, "measure": 2})
self.assertDictEqual(qc1.count_ops(), {"h": 1, "measure": 1}) # no changes "in-place"
self.assertDictEqual(qc2.count_ops(), {"measure": 1}) # no changes "in-place"
self.assertDictAlmostEqual(counts, target, threshold)
def test_compose_circuit_and(self):
"""Test composing two circuits using & operator"""
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
qc1 = QuantumCircuit(qr, cr)
qc2 = QuantumCircuit(qr, cr)
qc1.h(qr[0])
qc1.measure(qr[0], cr[0])
qc2.measure(qr[1], cr[1])
qc3 = qc1 & qc2
backend = BasicSimulator()
shots = 1024
result = backend.run(qc3, shots=shots, seed_simulator=78).result()
counts = result.get_counts()
target = {"00": shots / 2, "01": shots / 2}
threshold = 0.04 * shots
self.assertDictEqual(qc3.count_ops(), {"h": 1, "measure": 2})
self.assertDictEqual(qc1.count_ops(), {"h": 1, "measure": 1}) # no changes "in-place"
self.assertDictEqual(qc2.count_ops(), {"measure": 1}) # no changes "in-place"
self.assertDictAlmostEqual(counts, target, threshold)
def test_compose_circuit_iand(self):
"""Test composing circuits using &= operator (in place)"""
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
qc1 = QuantumCircuit(qr, cr)
qc2 = QuantumCircuit(qr, cr)
qc1.h(qr[0])
qc1.measure(qr[0], cr[0])
qc2.measure(qr[1], cr[1])
qc1 &= qc2
backend = BasicSimulator()
shots = 1024
result = backend.run(qc1, shots=shots, seed_simulator=78).result()
counts = result.get_counts()
target = {"00": shots / 2, "01": shots / 2}
threshold = 0.04 * shots
self.assertDictEqual(qc1.count_ops(), {"h": 1, "measure": 2}) # changes "in-place"
self.assertDictEqual(qc2.count_ops(), {"measure": 1}) # no changes "in-place"
self.assertDictAlmostEqual(counts, target, threshold)
def test_compose_circuit_fail_circ_size(self):
"""Test composing circuit fails when number of wires in circuit is not enough"""
qr1 = QuantumRegister(2)
qr2 = QuantumRegister(4)
# Creating our circuits
qc1 = QuantumCircuit(qr1)
qc1.x(0)
qc1.h(1)
qc2 = QuantumCircuit(qr2)
qc2.h([1, 2])
qc2.cx(2, 3)
# Composing will fail because qc2 requires 4 wires
self.assertRaises(CircuitError, qc1.compose, qc2)
def test_compose_circuit_fail_arg_size(self):
"""Test composing circuit fails when arg size does not match number of wires"""
qr1 = QuantumRegister(2)
qr2 = QuantumRegister(2)
qc1 = QuantumCircuit(qr1)
qc1.h(0)
qc2 = QuantumCircuit(qr2)
qc2.cx(0, 1)
self.assertRaises(CircuitError, qc1.compose, qc2, qubits=[0])
def test_tensor_circuit(self):
"""Test tensoring two circuits"""
qc1 = QuantumCircuit(1, 1)
qc2 = QuantumCircuit(1, 1)
qc2.h(0)
qc2.measure(0, 0)
qc1.measure(0, 0)
qc3 = qc1.tensor(qc2)
backend = BasicSimulator()
shots = 1024
result = backend.run(qc3, shots=shots, seed_simulator=78).result()
counts = result.get_counts()
target = {"00": shots / 2, "01": shots / 2}
threshold = 0.04 * shots
self.assertDictEqual(qc3.count_ops(), {"h": 1, "measure": 2})
self.assertDictEqual(qc2.count_ops(), {"h": 1, "measure": 1}) # no changes "in-place"
self.assertDictEqual(qc1.count_ops(), {"measure": 1}) # no changes "in-place"
self.assertDictAlmostEqual(counts, target, threshold)
def test_tensor_circuit_xor(self):
"""Test tensoring two circuits using ^ operator"""
qc1 = QuantumCircuit(1, 1)
qc2 = QuantumCircuit(1, 1)
qc2.h(0)
qc2.measure(0, 0)
qc1.measure(0, 0)
qc3 = qc1 ^ qc2
backend = BasicSimulator()
shots = 1024
result = backend.run(qc3, shots=shots, seed_simulator=78).result()
counts = result.get_counts()
target = {"00": shots / 2, "01": shots / 2}
threshold = 0.04 * shots
self.assertDictEqual(qc3.count_ops(), {"h": 1, "measure": 2})
self.assertDictEqual(qc2.count_ops(), {"h": 1, "measure": 1}) # no changes "in-place"
self.assertDictEqual(qc1.count_ops(), {"measure": 1}) # no changes "in-place"
self.assertDictAlmostEqual(counts, target, threshold)
def test_tensor_circuit_ixor(self):
"""Test tensoring two circuits using ^= operator"""
qc1 = QuantumCircuit(1, 1)
qc2 = QuantumCircuit(1, 1)
qc2.h(0)
qc2.measure(0, 0)
qc1.measure(0, 0)
qc1 ^= qc2
backend = BasicSimulator()
shots = 1024
result = backend.run(qc1, shots=shots, seed_simulator=78).result()
counts = result.get_counts()
target = {"00": shots / 2, "01": shots / 2}
threshold = 0.04 * shots
self.assertDictEqual(qc1.count_ops(), {"h": 1, "measure": 2}) # changes "in-place"
self.assertDictEqual(qc2.count_ops(), {"h": 1, "measure": 1}) # no changes "in-place"
self.assertDictAlmostEqual(counts, target, threshold)
def test_measure_args_type_cohesion(self):
"""Test for proper args types for measure function."""
quantum_reg = QuantumRegister(3)
classical_reg_0 = ClassicalRegister(1)
classical_reg_1 = ClassicalRegister(2)
quantum_circuit = QuantumCircuit(quantum_reg, classical_reg_0, classical_reg_1)
quantum_circuit.h(quantum_reg)
with self.assertRaises(CircuitError) as ctx:
quantum_circuit.measure(quantum_reg, classical_reg_1)
self.assertEqual(ctx.exception.message, "register size error")
def test_copy_circuit(self):
"""Test copy method makes a copy"""
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr)
qc.h(qr[0])
qc.measure(qr[0], cr[0])
qc.measure(qr[1], cr[1])
self.assertEqual(qc, qc.copy())
def test_copy_copies_registers(self):
"""Test copy copies the registers not via reference."""
qc = QuantumCircuit(1, 1)
copied = qc.copy()
copied.add_register(QuantumRegister(1, "additional_q"))
copied.add_register(ClassicalRegister(1, "additional_c"))
self.assertEqual(len(qc.qregs), 1)
self.assertEqual(len(copied.qregs), 2)
self.assertEqual(len(qc.cregs), 1)
self.assertEqual(len(copied.cregs), 2)
def test_copy_handles_global_phase(self):
"""Test that the global phase is included in the copy, including parameters."""
a, b = Parameter("a"), Parameter("b")
nonparametric = QuantumCircuit(global_phase=1.0).copy()
self.assertEqual(nonparametric.global_phase, 1.0)
self.assertEqual(set(nonparametric.parameters), set())
parameter_phase = QuantumCircuit(global_phase=a).copy()
self.assertEqual(parameter_phase.global_phase, a)
self.assertEqual(set(parameter_phase.parameters), {a})
# The `assign_parameters` is an indirect test that the `ParameterTable` is fully valid.
self.assertEqual(parameter_phase.assign_parameters({a: 1.0}).global_phase, 1.0)
expression_phase = QuantumCircuit(global_phase=a - b).copy()
self.assertEqual(expression_phase.global_phase, a - b)
self.assertEqual(set(expression_phase.parameters), {a, b})
self.assertEqual(expression_phase.assign_parameters({a: 3, b: 2}).global_phase, 1.0)
def test_copy_empty_like_circuit(self):
"""Test copy_empty_like method makes a clear copy."""
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr, global_phase=1.0, name="qc", metadata={"key": "value"})
qc.h(qr[0])
qc.measure(qr[0], cr[0])
qc.measure(qr[1], cr[1])
sched = Schedule(Play(Gaussian(160, 0.1, 40), DriveChannel(0)))
qc.add_calibration("h", [0, 1], sched)
copied = qc.copy_empty_like()
qc.clear()
self.assertEqual(qc, copied)
self.assertEqual(qc.global_phase, copied.global_phase)
self.assertEqual(qc.name, copied.name)
self.assertEqual(qc.metadata, copied.metadata)
self.assertEqual(qc.calibrations, copied.calibrations)
copied = qc.copy_empty_like("copy")
self.assertEqual(copied.name, "copy")
def test_copy_variables(self):
"""Test that a full copy of circuits including variables copies them across."""
a = expr.Var.new("a", types.Bool())
b = expr.Var.new("b", types.Uint(8))
c = expr.Var.new("c", types.Bool())
d = expr.Var.new("d", types.Uint(8))
qc = QuantumCircuit(inputs=[a], declarations=[(c, expr.lift(False))])
copied = qc.copy()
self.assertEqual({a}, set(copied.iter_input_vars()))
self.assertEqual({c}, set(copied.iter_declared_vars()))
self.assertEqual(
[instruction.operation for instruction in qc],
[instruction.operation for instruction in copied.data],
)
# Check that the original circuit is not mutated.
copied.add_input(b)
copied.add_var(d, 0xFF)
self.assertEqual({a, b}, set(copied.iter_input_vars()))
self.assertEqual({c, d}, set(copied.iter_declared_vars()))
self.assertEqual({a}, set(qc.iter_input_vars()))
self.assertEqual({c}, set(qc.iter_declared_vars()))
qc = QuantumCircuit(captures=[b], declarations=[(a, expr.lift(False)), (c, a)])
copied = qc.copy()
self.assertEqual({b}, set(copied.iter_captured_vars()))
self.assertEqual({a, c}, set(copied.iter_declared_vars()))
self.assertEqual(
[instruction.operation for instruction in qc],
[instruction.operation for instruction in copied.data],
)
# Check that the original circuit is not mutated.
copied.add_capture(d)
self.assertEqual({b, d}, set(copied.iter_captured_vars()))
self.assertEqual({b}, set(qc.iter_captured_vars()))
def test_copy_empty_variables(self):
"""Test that an empty copy of circuits including variables copies them across, but does not
initialise them."""
a = expr.Var.new("a", types.Bool())
b = expr.Var.new("b", types.Uint(8))
c = expr.Var.new("c", types.Bool())
d = expr.Var.new("d", types.Uint(8))
qc = QuantumCircuit(inputs=[a], declarations=[(c, expr.lift(False))])
copied = qc.copy_empty_like()
self.assertEqual({a}, set(copied.iter_input_vars()))
self.assertEqual({c}, set(copied.iter_declared_vars()))
self.assertEqual([], list(copied.data))
# Check that the original circuit is not mutated.
copied.add_input(b)
copied.add_var(d, 0xFF)
self.assertEqual({a, b}, set(copied.iter_input_vars()))
self.assertEqual({c, d}, set(copied.iter_declared_vars()))
self.assertEqual({a}, set(qc.iter_input_vars()))
self.assertEqual({c}, set(qc.iter_declared_vars()))
qc = QuantumCircuit(captures=[b], declarations=[(a, expr.lift(False)), (c, a)])
copied = qc.copy_empty_like()
self.assertEqual({b}, set(copied.iter_captured_vars()))
self.assertEqual({a, c}, set(copied.iter_declared_vars()))
self.assertEqual([], list(copied.data))
# Check that the original circuit is not mutated.
copied.add_capture(d)
self.assertEqual({b, d}, set(copied.iter_captured_vars()))
self.assertEqual({b}, set(qc.iter_captured_vars()))
def test_copy_empty_variables_alike(self):
"""Test that an empty copy of circuits including variables copies them across, but does not
initialise them. This is the same as the default, just spelled explicitly."""
a = expr.Var.new("a", types.Bool())
b = expr.Var.new("b", types.Uint(8))
c = expr.Var.new("c", types.Bool())
d = expr.Var.new("d", types.Uint(8))
qc = QuantumCircuit(inputs=[a], declarations=[(c, expr.lift(False))])
copied = qc.copy_empty_like(vars_mode="alike")
self.assertEqual({a}, set(copied.iter_input_vars()))
self.assertEqual({c}, set(copied.iter_declared_vars()))
self.assertEqual([], list(copied.data))
# Check that the original circuit is not mutated.
copied.add_input(b)
copied.add_var(d, 0xFF)
self.assertEqual({a, b}, set(copied.iter_input_vars()))
self.assertEqual({c, d}, set(copied.iter_declared_vars()))
self.assertEqual({a}, set(qc.iter_input_vars()))
self.assertEqual({c}, set(qc.iter_declared_vars()))
qc = QuantumCircuit(captures=[b], declarations=[(a, expr.lift(False)), (c, a)])
copied = qc.copy_empty_like(vars_mode="alike")
self.assertEqual({b}, set(copied.iter_captured_vars()))
self.assertEqual({a, c}, set(copied.iter_declared_vars()))
self.assertEqual([], list(copied.data))
# Check that the original circuit is not mutated.
copied.add_capture(d)
self.assertEqual({b, d}, set(copied.iter_captured_vars()))
self.assertEqual({b}, set(qc.iter_captured_vars()))
def test_copy_empty_variables_to_captures(self):
"""``vars_mode="captures"`` should convert all variables to captures."""
a = expr.Var.new("a", types.Bool())
b = expr.Var.new("b", types.Uint(8))
c = expr.Var.new("c", types.Bool())
d = expr.Var.new("d", types.Uint(8))
qc = QuantumCircuit(inputs=[a, b], declarations=[(c, expr.lift(False))])
copied = qc.copy_empty_like(vars_mode="captures")
self.assertEqual({a, b, c}, set(copied.iter_captured_vars()))
self.assertEqual({a, b, c}, set(copied.iter_vars()))
self.assertEqual([], list(copied.data))
qc = QuantumCircuit(captures=[c, d])
copied = qc.copy_empty_like(vars_mode="captures")
self.assertEqual({c, d}, set(copied.iter_captured_vars()))
self.assertEqual({c, d}, set(copied.iter_vars()))
self.assertEqual([], list(copied.data))
def test_copy_empty_variables_drop(self):
"""``vars_mode="drop"`` should not have variables in the output."""
a = expr.Var.new("a", types.Bool())
b = expr.Var.new("b", types.Uint(8))
c = expr.Var.new("c", types.Bool())
qc = QuantumCircuit(inputs=[a, b], declarations=[(c, expr.lift(False))])
copied = qc.copy_empty_like(vars_mode="drop")
self.assertEqual(set(), set(copied.iter_vars()))
self.assertEqual([], list(copied.data))
def test_copy_empty_like_parametric_phase(self):
"""Test that the parameter table of an empty circuit remains valid after copying a circuit
with a parametric global phase."""
a, b = Parameter("a"), Parameter("b")
single = QuantumCircuit(global_phase=a).copy_empty_like()
self.assertEqual(single.global_phase, a)
self.assertEqual(set(single.parameters), {a})
# The `assign_parameters` is an indirect test that the `ParameterTable` is fully valid.
self.assertEqual(single.assign_parameters({a: 1.0}).global_phase, 1.0)
stripped_instructions = QuantumCircuit(1, global_phase=a - b)
stripped_instructions.rz(a, 0)
stripped_instructions = stripped_instructions.copy_empty_like()
self.assertEqual(stripped_instructions.global_phase, a - b)
self.assertEqual(set(stripped_instructions.parameters), {a, b})
self.assertEqual(stripped_instructions.assign_parameters({a: 3, b: 2}).global_phase, 1.0)
def test_circuit_copy_rejects_invalid_types(self):
"""Test copy method rejects argument with type other than 'string' and 'None' type."""
qc = QuantumCircuit(1, 1)
qc.h(0)
with self.assertRaises(TypeError):
qc.copy([1, "2", 3])
def test_circuit_copy_empty_like_rejects_invalid_types(self):
"""Test copy_empty_like method rejects argument with type other than 'string' and 'None' type."""
qc = QuantumCircuit(1, 1)
qc.h(0)
with self.assertRaises(TypeError):
qc.copy_empty_like(123)
def test_clear_circuit(self):
"""Test clear method deletes instructions in circuit."""
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr)
qc.h(qr[0])
qc.measure(qr[0], cr[0])
qc.measure(qr[1], cr[1])
qc.clear()
self.assertEqual(len(qc.data), 0)
self.assertEqual(qc._data.num_parameters(), 0)
def test_barrier(self):
"""Test multiple argument forms of barrier."""
qr1, qr2 = QuantumRegister(3, "qr1"), QuantumRegister(4, "qr2")
qc = QuantumCircuit(qr1, qr2)
qc.barrier() # All qubits.
qc.barrier(0, 1)
qc.barrier([4, 2])
qc.barrier(qr1)
qc.barrier(slice(3, 5))
qc.barrier({1, 4, 2}, range(5, 7))
expected = QuantumCircuit(qr1, qr2)
expected.append(Barrier(expected.num_qubits), expected.qubits.copy(), [])
expected.append(Barrier(2), [expected.qubits[0], expected.qubits[1]], [])
expected.append(Barrier(2), [expected.qubits[2], expected.qubits[4]], [])
expected.append(Barrier(3), expected.qubits[0:3], [])
expected.append(Barrier(2), [expected.qubits[3], expected.qubits[4]], [])
expected.append(Barrier(5), [expected.qubits[x] for x in [1, 2, 4, 5, 6]], [])
self.assertEqual(qc, expected)
def test_barrier_in_context(self):
"""Test barrier statement in context, see gh-11345"""
qc = QuantumCircuit(2, 2)
qc.h(0)
with qc.if_test((qc.clbits[0], False)):
qc.h(0)
qc.barrier()
operation_names = [c.operation.name for c in qc]
self.assertNotIn("barrier", operation_names)
def test_measure_active(self):
"""Test measure_active
Applies measurements only to non-idle qubits. Creates a ClassicalRegister of size equal to
the amount of non-idle qubits to store the measured values.
"""
qr = QuantumRegister(4)
cr = ClassicalRegister(2, "measure")
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
circuit.h(qr[2])
circuit.measure_active()
expected = QuantumCircuit(qr)
expected.h(qr[0])
expected.h(qr[2])
expected.add_register(cr)
expected.barrier()
expected.measure([qr[0], qr[2]], [cr[0], cr[1]])
self.assertEqual(expected, circuit)
def test_measure_active_copy(self):
"""Test measure_active copy
Applies measurements only to non-idle qubits. Creates a ClassicalRegister of size equal to
the amount of non-idle qubits to store the measured values.
"""
qr = QuantumRegister(4)
cr = ClassicalRegister(2, "measure")
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
circuit.h(qr[2])
new_circuit = circuit.measure_active(inplace=False)
expected = QuantumCircuit(qr)
expected.h(qr[0])
expected.h(qr[2])
expected.add_register(cr)
expected.barrier()
expected.measure([qr[0], qr[2]], [cr[0], cr[1]])
self.assertEqual(expected, new_circuit)
self.assertFalse("measure" in circuit.count_ops().keys())
def test_measure_active_repetition(self):
"""Test measure_active in a circuit with a 'measure' creg.
measure_active should be aware that the creg 'measure' might exists.
"""
qr = QuantumRegister(2)
cr = ClassicalRegister(2, "measure")
circuit = QuantumCircuit(qr, cr)
circuit.h(qr)
circuit.measure_active()
self.assertEqual(len(circuit.cregs), 2) # Two cregs
self.assertEqual(len(circuit.cregs[0]), 2) # Both length 2
self.assertEqual(len(circuit.cregs[1]), 2)
def test_measure_all(self):
"""Test measure_all applies measurements to all qubits.
Creates a ClassicalRegister of size equal to the total amount of qubits to
store those measured values.
"""
qr = QuantumRegister(2)
cr = ClassicalRegister(2, "meas")
circuit = QuantumCircuit(qr)
circuit.measure_all()
expected = QuantumCircuit(qr, cr)
expected.barrier()
expected.measure(qr, cr)
self.assertEqual(expected, circuit)
def test_measure_all_after_copy(self):
"""
Test measure_all on a circuit that has been copied.
"""
qc = QuantumCircuit(2)
qc.h(1)
qc2 = qc.copy()
qc.measure_all()
qc2.measure_all()
expected_cregs = [ClassicalRegister(2, "meas")]
self.assertEqual(qc.cregs, expected_cregs)
self.assertEqual(qc2.cregs, expected_cregs)
self.assertEqual(qc, qc2)
def test_measure_all_after_deepcopy(self):
"""
Test measure_all on a circuit that has been deep-copied.
"""
qc = QuantumCircuit(2)
qc.h(1)
qc2 = copy.deepcopy(qc)
qc.measure_all()
qc2.measure_all()
expected_cregs = [ClassicalRegister(2, "meas")]
self.assertEqual(qc.cregs, expected_cregs)
self.assertEqual(qc2.cregs, expected_cregs)
self.assertEqual(qc, qc2)
def test_measure_all_after_pickle(self):
"""
Test measure_all on a circuit that has been pickled.
"""
qc = QuantumCircuit(2)
qc.h(1)
qc2 = pickle.loads(pickle.dumps(qc))
qc.measure_all()
qc2.measure_all()
expected_cregs = [ClassicalRegister(2, "meas")]
self.assertEqual(qc.cregs, expected_cregs)
self.assertEqual(qc2.cregs, expected_cregs)
self.assertEqual(qc, qc2)
def test_measure_all_not_add_bits_equal(self):
"""Test measure_all applies measurements to all qubits.
Does not create a new ClassicalRegister if the existing one is big enough.
"""
qr = QuantumRegister(2)
cr = ClassicalRegister(2, "meas")
circuit = QuantumCircuit(qr, cr)
circuit.measure_all(add_bits=False)
expected = QuantumCircuit(qr, cr)
expected.barrier()
expected.measure(qr, cr)
self.assertEqual(expected, circuit)
def test_measure_all_not_add_bits_bigger(self):
"""Test measure_all applies measurements to all qubits.
Does not create a new ClassicalRegister if the existing one is big enough.
"""
qr = QuantumRegister(2)
cr = ClassicalRegister(3, "meas")
circuit = QuantumCircuit(qr, cr)
circuit.measure_all(add_bits=False)
expected = QuantumCircuit(qr, cr)
expected.barrier()
expected.measure(qr, cr[0:2])
self.assertEqual(expected, circuit)
def test_measure_all_not_add_bits_smaller(self):
"""Test measure_all applies measurements to all qubits.
Raises an error if there are not enough classical bits to store the measurements.
"""
qr = QuantumRegister(3)
cr = ClassicalRegister(2, "meas")
circuit = QuantumCircuit(qr, cr)
with self.assertRaisesRegex(CircuitError, "The number of classical bits"):
circuit.measure_all(add_bits=False)
def test_measure_all_copy(self):
"""Test measure_all with inplace=False"""
qr = QuantumRegister(2)
cr = ClassicalRegister(2, "meas")
circuit = QuantumCircuit(qr)
new_circuit = circuit.measure_all(inplace=False)
expected = QuantumCircuit(qr, cr)
expected.barrier()
expected.measure(qr, cr)
self.assertEqual(expected, new_circuit)
self.assertFalse("measure" in circuit.count_ops().keys())
def test_measure_all_repetition(self):
"""Test measure_all in a circuit with a 'measure' creg.
measure_all should be aware that the creg 'measure' might exists.
"""
qr = QuantumRegister(2)
cr = ClassicalRegister(2, "measure")
circuit = QuantumCircuit(qr, cr)
circuit.measure_all()
self.assertEqual(len(circuit.cregs), 2) # Two cregs
self.assertEqual(len(circuit.cregs[0]), 2) # Both length 2
self.assertEqual(len(circuit.cregs[1]), 2)
def test_remove_final_measurements(self):
"""Test remove_final_measurements
Removes all measurements at end of circuit.
"""
qr = QuantumRegister(2)
cr = ClassicalRegister(2, "meas")
circuit = QuantumCircuit(qr, cr)
circuit.measure(qr, cr)
circuit.remove_final_measurements()
expected = QuantumCircuit(qr)
self.assertEqual(expected, circuit)
def test_remove_final_measurements_copy(self):
"""Test remove_final_measurements on copy
Removes all measurements at end of circuit.
"""
qr = QuantumRegister(2)
cr = ClassicalRegister(2, "meas")
circuit = QuantumCircuit(qr, cr)
circuit.measure(qr, cr)
new_circuit = circuit.remove_final_measurements(inplace=False)
expected = QuantumCircuit(qr)
self.assertEqual(expected, new_circuit)
self.assertTrue("measure" in circuit.count_ops().keys())
def test_remove_final_measurements_copy_with_parameters(self):
"""Test remove_final_measurements doesn't corrupt ParameterTable
See https://github.com/Qiskit/qiskit-terra/issues/6108 for more details
"""
qr = QuantumRegister(2)
cr = ClassicalRegister(2, "meas")
theta = Parameter("theta")
circuit = QuantumCircuit(qr, cr)
circuit.rz(theta, qr)
circuit.measure(qr, cr)
circuit.remove_final_measurements()
copied = circuit.copy()
self.assertEqual(copied, circuit)
def test_remove_final_measurements_multiple_measures(self):
"""Test remove_final_measurements only removes measurements at the end of the circuit
remove_final_measurements should not remove measurements in the beginning or middle of the
circuit.
"""
qr = QuantumRegister(2)
cr = ClassicalRegister(1)
circuit = QuantumCircuit(qr, cr)
circuit.measure(qr[0], cr)
circuit.h(0)
circuit.measure(qr[0], cr)
circuit.h(0)
circuit.measure(qr[0], cr)
circuit.remove_final_measurements()
expected = QuantumCircuit(qr, cr)
expected.measure(qr[0], cr)
expected.h(0)
expected.measure(qr[0], cr)
expected.h(0)
self.assertEqual(expected, circuit)
def test_remove_final_measurements_5802(self):
"""Test remove_final_measurements removes classical bits
https://github.com/Qiskit/qiskit-terra/issues/5802.
"""
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
circuit = QuantumCircuit(qr, cr)
circuit.measure(qr, cr)
circuit.remove_final_measurements()
self.assertEqual(circuit.cregs, [])
self.assertEqual(circuit.clbits, [])
def test_remove_final_measurements_7089(self):
"""Test remove_final_measurements removes resulting unused registers
even if not all bits were measured into.
https://github.com/Qiskit/qiskit-terra/issues/7089.
"""
circuit = QuantumCircuit(2, 5)
circuit.measure(0, 0)
circuit.measure(1, 1)
circuit.remove_final_measurements(inplace=True)
self.assertEqual(circuit.cregs, [])
self.assertEqual(circuit.clbits, [])
def test_remove_final_measurements_bit_locations(self):
"""Test remove_final_measurements properly recalculates clbit indices
and preserves order of remaining cregs and clbits.
"""
c0 = ClassicalRegister(1)
c1_0 = Clbit()
c2 = ClassicalRegister(1)
c3 = ClassicalRegister(1)
# add an individual bit that's not in any register of this circuit
circuit = QuantumCircuit(QuantumRegister(1), c0, [c1_0], c2, c3)
circuit.measure(0, c1_0)
circuit.measure(0, c2[0])
# assert cregs and clbits before measure removal
self.assertEqual(circuit.cregs, [c0, c2, c3])
self.assertEqual(circuit.clbits, [c0[0], c1_0, c2[0], c3[0]])
# assert clbit indices prior to measure removal
self.assertEqual(circuit.find_bit(c0[0]), BitLocations(0, [(c0, 0)]))
self.assertEqual(circuit.find_bit(c1_0), BitLocations(1, []))
self.assertEqual(circuit.find_bit(c2[0]), BitLocations(2, [(c2, 0)]))
self.assertEqual(circuit.find_bit(c3[0]), BitLocations(3, [(c3, 0)]))
circuit.remove_final_measurements()
# after measure removal, creg c2 should be gone, as should lone bit c1_0
# and c0 should still come before c3
self.assertEqual(circuit.cregs, [c0, c3])
self.assertEqual(circuit.clbits, [c0[0], c3[0]])
# there should be no gaps in clbit indices
# e.g. c3[0] is now the second clbit
self.assertEqual(circuit.find_bit(c0[0]), BitLocations(0, [(c0, 0)]))
self.assertEqual(circuit.find_bit(c3[0]), BitLocations(1, [(c3, 0)]))
def test_remove_final_measurements_parametric_global_phase(self):
"""Test that a parametric global phase is respected in the table afterwards."""
a = Parameter("a")
qc = QuantumCircuit(2, 2, global_phase=a)
qc.h(0)
qc.cx(0, 1)
qc.measure([0, 1], [0, 1])
expected = QuantumCircuit(2, global_phase=1)
expected.h(0)
expected.cx(0, 1)
self.assertEqual(
qc.remove_final_measurements(inplace=False).assign_parameters({a: 1}), expected
)
qc.remove_final_measurements(inplace=True)
self.assertEqual(qc.assign_parameters({a: 1}), expected)
def test_reverse(self):
"""Test reverse method reverses but does not invert."""
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.s(1)
qc.cx(0, 1)
qc.measure([0, 1], [0, 1])
qc.x(0)
qc.y(1)
expected = QuantumCircuit(2, 2)
expected.y(1)
expected.x(0)
expected.measure([0, 1], [0, 1])
expected.cx(0, 1)
expected.s(1)
expected.h(0)
self.assertEqual(qc.reverse_ops(), expected)
def test_reverse_with_standlone_vars(self):
"""Test that instruction-reversing works in the presence of stand-alone variables."""
a = expr.Var.new("a", types.Bool())
b = expr.Var.new("b", types.Uint(8))
c = expr.Var.new("c", types.Uint(8))
qc = QuantumCircuit(2, inputs=[a])
qc.add_var(b, 12)
qc.h(0)
qc.cx(0, 1)
with qc.if_test(a):
# We don't really comment on what should happen within control-flow operations in this
# method - it's not really defined in a non-linear CFG. This deliberately uses a body
# of length 1 (a single `Store`), so there's only one possibility.
qc.add_var(c, 12)
expected = qc.copy_empty_like()
with expected.if_test(a):
expected.add_var(c, 12)
expected.cx(0, 1)
expected.h(0)
expected.store(b, 12)
self.assertEqual(qc.reverse_ops(), expected)
def test_repeat(self):
"""Test repeating the circuit works."""
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr)
qc.h(0)
qc.cx(0, 1)
qc.barrier()
qc.h(0).c_if(cr, 1)
with self.subTest("repeat 0 times"):
rep = qc.repeat(0)
self.assertEqual(rep, QuantumCircuit(qr, cr))
with self.subTest("repeat 3 times"):
inst = qc.to_instruction()
ref = QuantumCircuit(qr, cr)
for _ in range(3):
ref.append(inst, ref.qubits, ref.clbits)
rep = qc.repeat(3)
self.assertEqual(rep, ref)
@data(0, 1, 4)
def test_repeat_global_phase(self, num):
"""Test the global phase is properly handled upon repeat."""
phase = 0.123
qc = QuantumCircuit(1, global_phase=phase)
expected = np.exp(1j * phase * num) * np.identity(2)
np.testing.assert_array_almost_equal(Operator(qc.repeat(num)).data, expected)
def test_bind_global_phase(self):
"""Test binding global phase."""
x = Parameter("x")
circuit = QuantumCircuit(1, global_phase=x)
self.assertEqual(circuit.parameters, {x})
bound = circuit.assign_parameters({x: 2})
self.assertEqual(bound.global_phase, 2)
self.assertEqual(bound.parameters, set())
def test_bind_parameter_in_phase_and_gate(self):
"""Test binding a parameter present in the global phase and the gates."""
x = Parameter("x")
circuit = QuantumCircuit(1, global_phase=x)
circuit.rx(x, 0)
self.assertEqual(circuit.parameters, {x})
ref = QuantumCircuit(1, global_phase=2)
ref.rx(2, 0)
bound = circuit.assign_parameters({x: 2})
self.assertEqual(bound, ref)
self.assertEqual(bound.parameters, set())
def test_power(self):
"""Test taking the circuit to a power works."""
qc = QuantumCircuit(2)
qc.cx(0, 1)
qc.rx(0.2, 1)
gate = qc.to_gate()
with self.subTest("power(int >= 0) equals repeat"):
self.assertEqual(qc.power(4), qc.repeat(4))
with self.subTest("explicit matrix power"):
self.assertEqual(qc.power(4, matrix_power=True).data[0].operation, gate.power(4))
with self.subTest("float power"):
self.assertEqual(qc.power(1.23).data[0].operation, gate.power(1.23))
with self.subTest("negative power"):
self.assertEqual(qc.power(-2).data[0].operation, gate.power(-2))
with self.subTest("integer circuit power via annotation"):
power_qc = qc.power(4, annotated=True)
self.assertIsInstance(power_qc[0].operation, AnnotatedOperation)
self.assertEqual(Operator(power_qc), Operator(qc).power(4))
with self.subTest("float circuit power via annotation"):
power_qc = qc.power(1.5, annotated=True)
self.assertIsInstance(power_qc[0].operation, AnnotatedOperation)
self.assertEqual(Operator(power_qc), Operator(qc).power(1.5))
with self.subTest("negative circuit power via annotation"):
power_qc = qc.power(-2, annotated=True)
self.assertIsInstance(power_qc[0].operation, AnnotatedOperation)
self.assertEqual(Operator(power_qc), Operator(qc).power(-2))
def test_power_parameterized_circuit(self):
"""Test taking a parameterized circuit to a power."""
theta = Parameter("th")
qc = QuantumCircuit(2)
qc.cx(0, 1)
qc.rx(theta, 1)
with self.subTest("power(int >= 0) equals repeat"):
self.assertEqual(qc.power(4), qc.repeat(4))
with self.subTest("cannot to matrix power if parameterized"):
with self.assertRaises(CircuitError):
_ = qc.power(0.5)
def test_control(self):
"""Test controlling the circuit."""
qc = QuantumCircuit(2, name="my_qc")
qc.cry(0.2, 0, 1)
c_qc = qc.control()
with self.subTest("return type is circuit"):
self.assertIsInstance(c_qc, QuantumCircuit)
with self.subTest("test name"):
self.assertEqual(c_qc.name, "c_my_qc")
with self.subTest("repeated control"):
cc_qc = c_qc.control()
self.assertEqual(cc_qc.num_qubits, c_qc.num_qubits + 1)
with self.subTest("controlled circuit has same parameter"):
param = Parameter("p")
qc.rx(param, 0)
c_qc = qc.control()
self.assertEqual(qc.parameters, c_qc.parameters)
with self.subTest("non-unitary operation raises"):
qc.reset(0)
with self.assertRaises(CircuitError):
_ = qc.control()
def test_control_implementation(self):
"""Run a test case for controlling the circuit, which should use ``Gate.control``."""
qc = QuantumCircuit(3)
qc.cx(0, 1)
qc.cry(0.2, 0, 1)
qc.t(0)
qc.append(SGate().control(2), [0, 1, 2])
qc.iswap(2, 0)
c_qc = qc.control(2, ctrl_state="10")
cgate = qc.to_gate().control(2, ctrl_state="10")
ref = QuantumCircuit(*c_qc.qregs)
ref.append(cgate, ref.qubits)
self.assertEqual(ref, c_qc)
@data("gate", "instruction")
def test_repeat_appended_type(self, subtype):
"""Test repeat appends Gate if circuit contains only gates and Instructions otherwise."""
sub = QuantumCircuit(2)
sub.x(0)
if subtype == "gate":
sub = sub.to_gate()
else:
sub = sub.to_instruction()
qc = QuantumCircuit(2)
qc.append(sub, [0, 1])
rep = qc.repeat(3)
if subtype == "gate":
self.assertTrue(all(isinstance(op.operation, Gate) for op in rep.data))
else:
self.assertTrue(all(isinstance(op.operation, Instruction) for op in rep.data))
def test_reverse_bits(self):
"""Test reversing order of bits."""
qc = QuantumCircuit(3, 2)
qc.h(0)
qc.s(1)
qc.cx(0, 1)
qc.measure(0, 1)
qc.x(0)
qc.y(1)
qc.global_phase = -1
expected = QuantumCircuit(3, 2)
expected.h(2)
expected.s(1)
expected.cx(2, 1)
expected.measure(2, 0)
expected.x(2)
expected.y(1)
expected.global_phase = -1
self.assertEqual(qc.reverse_bits(), expected)
def test_reverse_bits_boxed(self):
"""Test reversing order of bits in a hierarchical circuit."""
wide_cx = QuantumCircuit(3)
wide_cx.cx(0, 1)
wide_cx.cx(1, 2)
wide_cxg = wide_cx.to_gate()
cx_box = QuantumCircuit(3)
cx_box.append(wide_cxg, [0, 1, 2])
expected = QuantumCircuit(3)
expected.cx(2, 1)
expected.cx(1, 0)
self.assertEqual(cx_box.reverse_bits().decompose(), expected)
self.assertEqual(cx_box.decompose().reverse_bits(), expected)
# box one more layer to be safe.
cx_box_g = cx_box.to_gate()
cx_box_box = QuantumCircuit(4)
cx_box_box.append(cx_box_g, [0, 1, 2])
cx_box_box.cx(0, 3)
expected2 = QuantumCircuit(4)
expected2.cx(3, 2)
expected2.cx(2, 1)
expected2.cx(3, 0)
self.assertEqual(cx_box_box.reverse_bits().decompose().decompose(), expected2)
def test_reverse_bits_with_registers(self):
"""Test reversing order of bits when registers are present."""
qr1 = QuantumRegister(3, "a")
qr2 = QuantumRegister(2, "b")
qc = QuantumCircuit(qr1, qr2)
qc.h(qr1[0])
qc.cx(qr1[0], qr1[1])
qc.cx(qr1[1], qr1[2])
qc.cx(qr1[2], qr2[0])
qc.cx(qr2[0], qr2[1])
expected = QuantumCircuit(qr2, qr1)
expected.h(qr1[2])
expected.cx(qr1[2], qr1[1])
expected.cx(qr1[1], qr1[0])
expected.cx(qr1[0], qr2[1])
expected.cx(qr2[1], qr2[0])
self.assertEqual(qc.reverse_bits(), expected)
def test_reverse_bits_with_overlapped_registers(self):
"""Test reversing order of bits when registers are overlapped."""
qr1 = QuantumRegister(2, "a")
qr2 = QuantumRegister(bits=[qr1[0], qr1[1], Qubit()], name="b")
qc = QuantumCircuit(qr1, qr2)
qc.h(qr1[0])
qc.cx(qr1[0], qr1[1])
qc.cx(qr1[1], qr2[2])
qr2 = QuantumRegister(bits=[Qubit(), qr1[0], qr1[1]], name="b")
expected = QuantumCircuit(qr2, qr1)
expected.h(qr1[1])
expected.cx(qr1[1], qr1[0])
expected.cx(qr1[0], qr2[0])
self.assertEqual(qc.reverse_bits(), expected)
def test_reverse_bits_with_registerless_bits(self):
"""Test reversing order of registerless bits."""
q0 = Qubit()
q1 = Qubit()
c0 = Clbit()
c1 = Clbit()
qc = QuantumCircuit([q0, q1], [c0, c1])
qc.h(0)
qc.cx(0, 1)
qc.x(0).c_if(1, True)
qc.measure(0, 0)
expected = QuantumCircuit([c1, c0], [q1, q0])
expected.h(1)
expected.cx(1, 0)
expected.x(1).c_if(0, True)
expected.measure(1, 1)
self.assertEqual(qc.reverse_bits(), expected)
def test_reverse_bits_with_registers_and_bits(self):
"""Test reversing order of bits with registers and registerless bits."""
qr = QuantumRegister(2, "a")
q = Qubit()
qc = QuantumCircuit(qr, [q])
qc.h(qr[0])
qc.cx(qr[0], qr[1])
qc.cx(qr[1], q)
expected = QuantumCircuit([q], qr)
expected.h(qr[1])
expected.cx(qr[1], qr[0])
expected.cx(qr[0], q)
self.assertEqual(qc.reverse_bits(), expected)
def test_reverse_bits_with_mixed_overlapped_registers(self):
"""Test reversing order of bits with overlapped registers and registerless bits."""
q = Qubit()
qr1 = QuantumRegister(bits=[q, Qubit()], name="qr1")
qr2 = QuantumRegister(bits=[qr1[1], Qubit()], name="qr2")
qc = QuantumCircuit(qr1, qr2, [Qubit()])
qc.h(q)
qc.cx(qr1[0], qr1[1])
qc.cx(qr1[1], qr2[1])
qc.cx(2, 3)
qr2 = QuantumRegister(2, "qr2")
qr1 = QuantumRegister(bits=[qr2[1], q], name="qr1")
expected = QuantumCircuit([Qubit()], qr2, qr1)
expected.h(qr1[1])
expected.cx(qr1[1], qr1[0])
expected.cx(qr1[0], qr2[0])
expected.cx(1, 0)
self.assertEqual(qc.reverse_bits(), expected)
def test_cnot_alias(self):
"""Test that the cnot method alias adds a cx gate."""
qc = QuantumCircuit(2)
qc.cx(0, 1)
expected = QuantumCircuit(2)
expected.cx(0, 1)
self.assertEqual(qc, expected)
def test_inverse(self):
"""Test inverse circuit."""
qr = QuantumRegister(2)
qc = QuantumCircuit(qr, global_phase=0.5)
qc.h(0)
qc.barrier(qr)
qc.t(1)
expected = QuantumCircuit(qr)
expected.tdg(1)
expected.barrier(qr)
expected.h(0)
expected.global_phase = -0.5
self.assertEqual(qc.inverse(), expected)
def test_compare_two_equal_circuits(self):
"""Test to compare that 2 circuits are equal."""
qc1 = QuantumCircuit(2, 2)
qc1.h(0)
qc2 = QuantumCircuit(2, 2)
qc2.h(0)
self.assertTrue(qc1 == qc2)
def test_compare_two_different_circuits(self):
"""Test to compare that 2 circuits are different."""
qc1 = QuantumCircuit(2, 2)
qc1.h(0)
qc2 = QuantumCircuit(2, 2)
qc2.x(0)
self.assertFalse(qc1 == qc2)
def test_compare_circuits_with_single_bit_conditions(self):
"""Test that circuits with single-bit conditions can be compared correctly."""
qreg = QuantumRegister(1, name="q")
creg = ClassicalRegister(1, name="c")
qc1 = QuantumCircuit(qreg, creg, [Clbit()])
qc1.x(0).c_if(qc1.cregs[0], 1)
qc1.x(0).c_if(qc1.clbits[-1], True)
qc2 = QuantumCircuit(qreg, creg, [Clbit()])
qc2.x(0).c_if(qc2.cregs[0], 1)
qc2.x(0).c_if(qc2.clbits[-1], True)
self.assertEqual(qc1, qc2)
# Order of operations transposed.
qc1 = QuantumCircuit(qreg, creg, [Clbit()])
qc1.x(0).c_if(qc1.cregs[0], 1)
qc1.x(0).c_if(qc1.clbits[-1], True)
qc2 = QuantumCircuit(qreg, creg, [Clbit()])
qc2.x(0).c_if(qc2.clbits[-1], True)
qc2.x(0).c_if(qc2.cregs[0], 1)
self.assertNotEqual(qc1, qc2)
# Single-bit condition values not the same.
qc1 = QuantumCircuit(qreg, creg, [Clbit()])
qc1.x(0).c_if(qc1.cregs[0], 1)
qc1.x(0).c_if(qc1.clbits[-1], True)
qc2 = QuantumCircuit(qreg, creg, [Clbit()])
qc2.x(0).c_if(qc2.cregs[0], 1)
qc2.x(0).c_if(qc2.clbits[-1], False)
self.assertNotEqual(qc1, qc2)
def test_compare_a_circuit_with_none(self):
"""Test to compare that a circuit is different to None."""
qc1 = QuantumCircuit(2, 2)
qc1.h(0)
qc2 = None
self.assertFalse(qc1 == qc2)
def test_overlapped_add_bits_and_add_register(self):
"""Test add registers whose bits have already been added by add_bits."""
qc = QuantumCircuit()
for bit_type, reg_type in (
[Qubit, QuantumRegister],
[Clbit, ClassicalRegister],
[AncillaQubit, AncillaRegister],
):
bits = [bit_type() for _ in range(10)]
reg = reg_type(bits=bits)
qc.add_bits(bits)
qc.add_register(reg)
self.assertEqual(qc.num_qubits, 20)
self.assertEqual(qc.num_clbits, 10)
self.assertEqual(qc.num_ancillas, 10)
def test_overlapped_add_register_and_add_register(self):
"""Test add registers whose bits have already been added by add_register."""
qc = QuantumCircuit()
for bit_type, reg_type in (
[Qubit, QuantumRegister],
[Clbit, ClassicalRegister],
[AncillaQubit, AncillaRegister],
):
bits = [bit_type() for _ in range(10)]
reg1 = reg_type(bits=bits)
reg2 = reg_type(bits=bits)
qc.add_register(reg1)
qc.add_register(reg2)
self.assertEqual(qc.num_qubits, 20)
self.assertEqual(qc.num_clbits, 10)
self.assertEqual(qc.num_ancillas, 10)
def test_from_instructions(self):
"""Test from_instructions method."""
qreg = QuantumRegister(4)
creg = ClassicalRegister(3)
a, b, c, d = qreg
x, y, z = creg
circuit_1 = QuantumCircuit(2, 1)
circuit_1.x(0)
circuit_2 = QuantumCircuit(2, 1)
circuit_2.y(0)
def instructions():
yield CircuitInstruction(HGate(), [a], [])
yield CircuitInstruction(CXGate(), [a, b], [])
yield CircuitInstruction(Measure(), [a], [x])
yield CircuitInstruction(Measure(), [b], [y])
yield CircuitInstruction(IfElseOp((z, 1), circuit_1, circuit_2), [c, d], [z])
def instruction_tuples():
yield HGate(), [a], []
yield CXGate(), [a, b], []
yield CircuitInstruction(Measure(), [a], [x])
yield Measure(), [b], [y]
yield IfElseOp((z, 1), circuit_1, circuit_2), [c, d], [z]
def instruction_tuples_partial():
yield HGate(), [a]
yield CXGate(), [a, b], []
yield CircuitInstruction(Measure(), [a], [x])
yield Measure(), [b], [y]
yield IfElseOp((z, 1), circuit_1, circuit_2), [c, d], [z]
circuit = QuantumCircuit.from_instructions(instructions())
circuit_tuples = QuantumCircuit.from_instructions(instruction_tuples())
circuit_tuples_partial = QuantumCircuit.from_instructions(instruction_tuples_partial())
expected = QuantumCircuit([a, b, c, d], [x, y, z])
for instruction in instructions():
expected.append(instruction.operation, instruction.qubits, instruction.clbits)
self.assertEqual(circuit, expected)
self.assertEqual(circuit_tuples, expected)
self.assertEqual(circuit_tuples_partial, expected)
def test_from_instructions_bit_order(self):
"""Test from_instructions method bit order."""
qreg = QuantumRegister(2)
creg = ClassicalRegister(2)
a, b = qreg
c, d = creg
def instructions():
yield CircuitInstruction(HGate(), [b], [])
yield CircuitInstruction(CXGate(), [a, b], [])
yield CircuitInstruction(Measure(), [b], [d])
yield CircuitInstruction(Measure(), [a], [c])
circuit = QuantumCircuit.from_instructions(instructions())
self.assertEqual(circuit.qubits, [b, a])
self.assertEqual(circuit.clbits, [d, c])
circuit = QuantumCircuit.from_instructions(instructions(), qubits=qreg)
self.assertEqual(circuit.qubits, [a, b])
self.assertEqual(circuit.clbits, [d, c])
circuit = QuantumCircuit.from_instructions(instructions(), clbits=creg)
self.assertEqual(circuit.qubits, [b, a])
self.assertEqual(circuit.clbits, [c, d])
circuit = QuantumCircuit.from_instructions(
instructions(), qubits=iter([a, b]), clbits=[c, d]
)
self.assertEqual(circuit.qubits, [a, b])
self.assertEqual(circuit.clbits, [c, d])
def test_from_instructions_metadata(self):
"""Test from_instructions method passes metadata."""
qreg = QuantumRegister(2)
a, b = qreg
def instructions():
yield CircuitInstruction(HGate(), [a], [])
yield CircuitInstruction(CXGate(), [a, b], [])
circuit = QuantumCircuit.from_instructions(instructions(), name="test", global_phase=0.1)
expected = QuantumCircuit([a, b], global_phase=0.1)
for instruction in instructions():
expected.append(instruction.operation, instruction.qubits, instruction.clbits)
self.assertEqual(circuit, expected)
self.assertEqual(circuit.name, "test")
class TestCircuitPrivateOperations(QiskitTestCase):
"""Direct tests of some of the private methods of QuantumCircuit. These do not represent
functionality that we want to expose to users, but there are some cases where private methods
are used internally (similar to "protected" access in .NET or "friend" access in C++), and we
want to make sure they work in those cases."""
def test_previous_instruction_in_scope_failures(self):
"""Test the failure paths of the peek and pop methods for retrieving the most recent
instruction in a scope."""
test = QuantumCircuit(1, 1)
with self.assertRaisesRegex(CircuitError, r"This circuit contains no instructions\."):
test._peek_previous_instruction_in_scope()
with self.assertRaisesRegex(CircuitError, r"This circuit contains no instructions\."):
test._pop_previous_instruction_in_scope()
with test.for_loop(range(2)):
with self.assertRaisesRegex(CircuitError, r"This scope contains no instructions\."):
test._peek_previous_instruction_in_scope()
with self.assertRaisesRegex(CircuitError, r"This scope contains no instructions\."):
test._pop_previous_instruction_in_scope()
def test_pop_previous_instruction_removes_parameters(self):
"""Test that the private "pop instruction" method removes parameters from the parameter
table if that instruction is the only instance."""
x, y = Parameter("x"), Parameter("y")
test = QuantumCircuit(1, 1)
test.rx(y, 0)
last_instructions = list(test.u(x, y, 0, 0))
self.assertEqual({x, y}, set(test.parameters))
instruction = test._pop_previous_instruction_in_scope()
self.assertEqual(last_instructions, [instruction])
self.assertEqual({y}, set(test.parameters))
def test_decompose_gate_type(self):
"""Test decompose specifying gate type."""
circuit = QuantumCircuit(1)
circuit.append(SGate(label="s_gate"), [0])
decomposed = circuit.decompose(gates_to_decompose=SGate)
self.assertNotIn("s", decomposed.count_ops())
| qiskit/test/python/circuit/test_circuit_operations.py/0 | {
"file_path": "qiskit/test/python/circuit/test_circuit_operations.py",
"repo_id": "qiskit",
"token_count": 28379
} | 315 |
# 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.
"""HamiltonianGate tests"""
import numpy as np
from numpy.testing import assert_allclose
import qiskit
from qiskit.circuit.library import HamiltonianGate
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.circuit import Parameter
from qiskit.quantum_info import Operator
from qiskit.converters import circuit_to_dag, dag_to_circuit
from test import QiskitTestCase # pylint: disable=wrong-import-order
class TestHamiltonianGate(QiskitTestCase):
"""Tests for the HamiltonianGate class."""
def test_set_matrix(self):
"""Test instantiation"""
hamiltonian = HamiltonianGate([[0, 1], [1, 0]], 1)
self.assertEqual(hamiltonian.num_qubits, 1)
def test_set_matrix_raises(self):
"""test non-unitary"""
with self.assertRaises(ValueError):
HamiltonianGate([[1, 0], [1, 1]], 1)
def test_complex_time_raises(self):
"""test non-unitary"""
with self.assertRaises(ValueError):
HamiltonianGate([[1, 0], [1, 1]], 1j)
def test_conjugate(self):
"""test conjugate"""
ham = HamiltonianGate([[0, 1j], [-1j, 2]], np.pi / 4)
np.testing.assert_array_almost_equal(ham.conjugate().to_matrix(), np.conj(ham.to_matrix()))
def test_transpose(self):
"""test transpose"""
ham = HamiltonianGate([[15, 1j], [-1j, -2]], np.pi / 7)
np.testing.assert_array_almost_equal(
ham.transpose().to_matrix(), np.transpose(ham.to_matrix())
)
def test_adjoint(self):
"""test adjoint operation"""
ham = HamiltonianGate([[3, 4j], [-4j, -0.2]], np.pi * 0.143)
np.testing.assert_array_almost_equal(
ham.adjoint().to_matrix(), np.transpose(np.conj(ham.to_matrix()))
)
def test_repeat(self):
"""test repeat operation"""
ham = HamiltonianGate(np.array([[1, 0.5 + 4j], [0.5 - 4j, -0.2]]), np.pi * 0.143)
operator = Operator(ham)
self.assertTrue(np.allclose(Operator(ham.repeat(2)), operator @ operator))
class TestHamiltonianCircuit(QiskitTestCase):
"""Hamiltonian gate circuit tests."""
def test_1q_hamiltonian(self):
"""test 1 qubit hamiltonian"""
qr = QuantumRegister(1, "q0")
cr = ClassicalRegister(1, "c0")
qc = QuantumCircuit(qr, cr)
matrix = np.zeros((2, 2))
qc.x(qr[0])
theta = Parameter("theta")
qc.append(HamiltonianGate(matrix, theta), [qr[0]])
qc = qc.assign_parameters({theta: 1})
# test of text drawer
self.log.info(qc)
dag = circuit_to_dag(qc)
dag_nodes = dag.named_nodes("hamiltonian")
self.assertTrue(len(dag_nodes) == 1)
dnode = dag_nodes[0]
self.assertIsInstance(dnode.op, HamiltonianGate)
self.assertEqual(dnode.qargs, tuple(qc.qubits))
assert_allclose(dnode.op.to_matrix(), np.eye(2))
def test_2q_hamiltonian(self):
"""test 2 qubit hamiltonian"""
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr)
matrix = Operator.from_label("XY")
qc.x(qr[0])
theta = Parameter("theta")
uni2q = HamiltonianGate(matrix, theta)
qc.append(uni2q, [qr[0], qr[1]])
qc2 = qc.assign_parameters({theta: -np.pi / 2})
dag = circuit_to_dag(qc2)
nodes = dag.two_qubit_ops()
self.assertEqual(len(nodes), 1)
dnode = nodes[0]
self.assertIsInstance(dnode.op, HamiltonianGate)
self.assertEqual(dnode.qargs, (qr[0], qr[1]))
# Equality based on Pauli exponential identity
np.testing.assert_array_almost_equal(dnode.op.to_matrix(), 1j * matrix.data)
qc3 = dag_to_circuit(dag)
self.assertEqual(qc2, qc3)
def test_3q_hamiltonian(self):
"""test 3 qubit hamiltonian on non-consecutive bits"""
qr = QuantumRegister(4)
qc = QuantumCircuit(qr)
qc.x(qr[0])
matrix = Operator.from_label("XZY")
theta = Parameter("theta")
uni3q = HamiltonianGate(matrix, theta)
qc.append(uni3q, [qr[0], qr[1], qr[3]])
qc.cx(qr[3], qr[2])
# test of text drawer
self.log.info(qc)
qc = qc.assign_parameters({theta: -np.pi / 2})
dag = circuit_to_dag(qc)
nodes = dag.multi_qubit_ops()
self.assertEqual(len(nodes), 1)
dnode = nodes[0]
self.assertIsInstance(dnode.op, HamiltonianGate)
self.assertEqual(dnode.qargs, (qr[0], qr[1], qr[3]))
np.testing.assert_almost_equal(dnode.op.to_matrix(), 1j * matrix.data)
def test_qobj_with_hamiltonian(self):
"""test qobj output with hamiltonian
REMOVE once Qobj gets removed"""
qr = QuantumRegister(4)
qc = QuantumCircuit(qr)
qc.rx(np.pi / 4, qr[0])
matrix = Operator.from_label("XIZ")
theta = Parameter("theta")
uni = HamiltonianGate(matrix, theta, label="XIZ")
qc.append(uni, [qr[0], qr[1], qr[3]])
qc.cx(qr[3], qr[2])
qc = qc.assign_parameters({theta: np.pi / 2})
with self.assertWarns(DeprecationWarning):
qobj = qiskit.compiler.assemble(qc)
instr = qobj.experiments[0].instructions[1]
self.assertEqual(instr.name, "hamiltonian")
# Also test label
self.assertEqual(instr.label, "XIZ")
np.testing.assert_array_almost_equal(
np.array(instr.params[0]).astype(np.complex64), matrix.data
)
def test_decomposes_into_correct_unitary(self):
"""test 2 qubit hamiltonian"""
qc = QuantumCircuit(2)
matrix = Operator.from_label("XY")
theta = Parameter("theta")
uni2q = HamiltonianGate(matrix, theta)
qc.append(uni2q, [0, 1])
qc = qc.assign_parameters({theta: -np.pi / 2}).decompose()
decomposed_ham = qc.data[0].operation
self.assertEqual(Operator(decomposed_ham), 1j * Operator.from_label("XY"))
| qiskit/test/python/circuit/test_hamiltonian_gate.py/0 | {
"file_path": "qiskit/test/python/circuit/test_hamiltonian_gate.py",
"repo_id": "qiskit",
"token_count": 2993
} | 316 |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for circuit templates."""
import unittest
from inspect import getmembers, isfunction
from ddt import ddt
import numpy as np
from qiskit import QuantumCircuit
from qiskit.quantum_info.operators import Operator
import qiskit.circuit.library.templates as templib
from test import combine # pylint: disable=wrong-import-order
from test import QiskitTestCase # pylint: disable=wrong-import-order
@ddt
class TestTemplates(QiskitTestCase):
"""Tests for the circuit templates."""
circuits = [o[1]() for o in getmembers(templib) if isfunction(o[1])]
for circuit in circuits:
if isinstance(circuit, QuantumCircuit):
circuit.assign_parameters({param: 0.2 for param in circuit.parameters}, inplace=True)
@combine(template_circuit=circuits)
def test_template(self, template_circuit):
"""test to verify that all templates are equivalent to the identity"""
target = Operator(template_circuit)
value = Operator(np.eye(2**template_circuit.num_qubits))
self.assertTrue(target.equiv(value))
if __name__ == "__main__":
unittest.main()
| qiskit/test/python/circuit/test_templates.py/0 | {
"file_path": "qiskit/test/python/circuit/test_templates.py",
"repo_id": "qiskit",
"token_count": 518
} | 317 |
# 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.
"""Tests classicalfunction compiler synthesis."""
import unittest
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.circuit.library.standard_gates import XGate
from qiskit.utils.optionals import HAS_TWEEDLEDUM
from test import QiskitTestCase # pylint: disable=wrong-import-order
if HAS_TWEEDLEDUM:
from qiskit.circuit.classicalfunction import classical_function as compile_classical_function
from . import examples
@unittest.skipUnless(HAS_TWEEDLEDUM, "Tweedledum is required for these tests.")
class TestSynthesis(QiskitTestCase):
# pylint: disable=possibly-used-before-assignment
"""Tests ClassicalFunction.synth method."""
def test_grover_oracle(self):
"""Synthesis of grover_oracle example"""
oracle = compile_classical_function(examples.grover_oracle)
quantum_circuit = oracle.synth()
expected = QuantumCircuit(5)
expected.append(XGate().control(4, ctrl_state="1010"), [0, 1, 2, 3, 4])
self.assertEqual(quantum_circuit.name, "grover_oracle")
self.assertEqual(quantum_circuit, expected)
def test_grover_oracle_arg_regs(self):
"""Synthesis of grover_oracle example with arg_regs"""
oracle = compile_classical_function(examples.grover_oracle)
quantum_circuit = oracle.synth(registerless=False)
qr_a = QuantumRegister(1, "a")
qr_b = QuantumRegister(1, "b")
qr_c = QuantumRegister(1, "c")
qr_d = QuantumRegister(1, "d")
qr_return = QuantumRegister(1, "return")
expected = QuantumCircuit(qr_a, qr_b, qr_c, qr_d, qr_return)
expected.append(
XGate().control(4, ctrl_state="1010"),
[qr_a[0], qr_b[0], qr_c[0], qr_d[0], qr_return[0]],
)
self.assertEqual(quantum_circuit.name, "grover_oracle")
self.assertEqual(quantum_circuit, expected)
| qiskit/test/python/classical_function_compiler/test_synthesis.py/0 | {
"file_path": "qiskit/test/python/classical_function_compiler/test_synthesis.py",
"repo_id": "qiskit",
"token_count": 912
} | 318 |
# 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 the converters."""
import math
import numpy as np
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.circuit import Gate, Qubit
from qiskit.circuit.classical import expr, types
from qiskit.quantum_info import Operator
from qiskit.exceptions import QiskitError
from test import QiskitTestCase # pylint: disable=wrong-import-order
class TestCircuitToGate(QiskitTestCase):
"""Test QuantumCircuit to Gate"""
def test_simple_circuit(self):
"""test simple circuit"""
qr1 = QuantumRegister(4, "qr1")
qr2 = QuantumRegister(3, "qr2")
qr3 = QuantumRegister(3, "qr3")
circ = QuantumCircuit(qr1, qr2, qr3)
circ.cx(qr1[1], qr2[2])
gate = circ.to_gate()
q = QuantumRegister(10, "q")
self.assertIsInstance(gate, Gate)
self.assertEqual(gate.definition[0].qubits, (q[1], q[6]))
def test_circuit_with_registerless_bits(self):
"""Test a circuit with registerless bits can be converted to a gate."""
qr1 = QuantumRegister(2)
qubits = [Qubit(), Qubit(), Qubit()]
qr2 = QuantumRegister(3)
circ = QuantumCircuit(qr1, qubits, qr2)
circ.cx(3, 5)
gate = circ.to_gate()
self.assertIsInstance(gate, Gate)
self.assertEqual(gate.num_qubits, len(qr1) + len(qubits) + len(qr2))
gate_definition = gate.definition
cx = gate_definition.data[0]
self.assertEqual(cx.qubits, (gate_definition.qubits[3], gate_definition.qubits[5]))
self.assertEqual(cx.clbits, ())
def test_circuit_with_overlapping_registers(self):
"""Test that the conversion works when the given circuit has bits that are contained in more
than one register."""
qubits = [Qubit() for _ in [None] * 10]
qr1 = QuantumRegister(bits=qubits[:6])
qr2 = QuantumRegister(bits=qubits[4:])
circ = QuantumCircuit(qubits, qr1, qr2)
circ.cx(3, 5)
gate = circ.to_gate()
self.assertIsInstance(gate, Gate)
self.assertEqual(gate.num_qubits, len(qubits))
gate_definition = gate.definition
cx = gate_definition.data[0]
self.assertEqual(cx.qubits, (gate_definition.qubits[3], gate_definition.qubits[5]))
self.assertEqual(cx.clbits, ())
def test_raises(self):
"""test circuit which can't be converted raises"""
circ1 = QuantumCircuit(3)
circ1.x(0)
circ1.cx(0, 1)
circ1.barrier()
circ2 = QuantumCircuit(1, 1)
circ2.measure(0, 0)
circ3 = QuantumCircuit(1)
circ3.x(0)
circ3.reset(0)
with self.assertRaises(QiskitError): # TODO: accept barrier
circ1.to_gate()
with self.assertRaises(QiskitError): # measure and reset are not valid
circ2.to_gate()
def test_generated_gate_inverse(self):
"""Test inverse of generated gate works."""
qr1 = QuantumRegister(2, "qr1")
circ = QuantumCircuit(qr1)
circ.cx(qr1[1], qr1[0])
gate = circ.to_gate()
out_gate = gate.inverse()
self.assertIsInstance(out_gate, Gate)
def test_to_gate_label(self):
"""Test label setting."""
qr1 = QuantumRegister(2, "qr1")
circ = QuantumCircuit(qr1, name="a circuit name")
circ.cx(qr1[1], qr1[0])
gate = circ.to_gate(label="a label")
self.assertEqual(gate.label, "a label")
def test_zero_operands(self):
"""Test that a gate can be created, even if it has zero operands."""
base = QuantumCircuit(global_phase=math.pi)
gate = base.to_gate()
self.assertEqual(gate.num_qubits, 0)
self.assertEqual(gate.num_clbits, 0)
self.assertEqual(gate.definition, base)
compound = QuantumCircuit(1)
compound.append(gate, [], [])
np.testing.assert_allclose(-np.eye(2), Operator(compound), atol=1e-16)
def test_realtime_vars_rejected(self):
"""Gates can't have realtime variables."""
qc = QuantumCircuit(1, inputs=[expr.Var.new("a", types.Bool())])
with self.assertRaisesRegex(QiskitError, "circuits with realtime classical variables"):
qc.to_gate()
qc = QuantumCircuit(1, captures=[expr.Var.new("a", types.Bool())])
with self.assertRaisesRegex(QiskitError, "circuits with realtime classical variables"):
qc.to_gate()
qc = QuantumCircuit(1)
qc.add_var("a", False)
with self.assertRaisesRegex(QiskitError, "circuits with realtime classical variables"):
qc.to_gate()
| qiskit/test/python/converters/test_circuit_to_gate.py/0 | {
"file_path": "qiskit/test/python/converters/test_circuit_to_gate.py",
"repo_id": "qiskit",
"token_count": 2206
} | 319 |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2022, 2023.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for BasePrimitive."""
import json
from ddt import data, ddt, unpack
from numpy import array, float32, float64, int32, int64
from qiskit import QuantumCircuit, pulse, transpile
from qiskit.circuit.random import random_circuit
from qiskit.primitives.base import validation
from qiskit.primitives.utils import _circuit_key
from qiskit.providers.fake_provider import GenericBackendV2
from test import QiskitTestCase # pylint: disable=wrong-import-order
@ddt
class TestCircuitValidation(QiskitTestCase):
"""Test circuits validation logic."""
@data(
(random_circuit(2, 2, seed=0), (random_circuit(2, 2, seed=0),)),
(
[random_circuit(2, 2, seed=0), random_circuit(2, 2, seed=1)],
(random_circuit(2, 2, seed=0), random_circuit(2, 2, seed=1)),
),
)
@unpack
def test_validate_circuits(self, circuits, expected):
"""Test circuits standardization."""
self.assertEqual(validation._validate_circuits(circuits), expected)
@data(None, "ERROR", True, 0, 1.0, 1j, [0.0])
def test_type_error(self, circuits):
"""Test type error if invalid input."""
with self.assertRaises(TypeError):
validation._validate_circuits(circuits)
@data((), [], "")
def test_value_error(self, circuits):
"""Test value error if no circuits are provided."""
with self.assertRaises(ValueError):
validation._validate_circuits(circuits)
@ddt
class TestParameterValuesValidation(QiskitTestCase):
"""Test parameter_values validation logic."""
@data(
((), ((),)),
([], ((),)),
(0, ((0,),)),
(1.2, ((1.2,),)),
((0,), ((0,),)),
([0], ((0,),)),
([1.2], ((1.2,),)),
((0, 1), ((0, 1),)),
([0, 1], ((0, 1),)),
([0, 1.2], ((0, 1.2),)),
([0.3, 1.2], ((0.3, 1.2),)),
(((0, 1)), ((0, 1),)),
(([0, 1]), ((0, 1),)),
([(0, 1)], ((0, 1),)),
([[0, 1]], ((0, 1),)),
([[0, 1.2]], ((0, 1.2),)),
([[0.3, 1.2]], ((0.3, 1.2),)),
# Test for numpy dtypes
(int32(5), ((float(int32(5)),),)),
(int64(6), ((float(int64(6)),),)),
(float32(3.2), ((float(float32(3.2)),),)),
(float64(6.4), ((float(float64(6.4)),),)),
([int32(5), float32(3.2)], ((float(int32(5)), float(float32(3.2))),)),
)
@unpack
def test_validate_parameter_values(self, _parameter_values, expected):
"""Test parameter_values standardization."""
for parameter_values in [_parameter_values, array(_parameter_values)]: # Numpy
self.assertEqual(validation._validate_parameter_values(parameter_values), expected)
self.assertEqual(
validation._validate_parameter_values(None, default=parameter_values), expected
)
@data(
"ERROR",
("E", "R", "R", "O", "R"),
(["E", "R", "R"], ["O", "R"]),
1j,
(1j,),
((1j,),),
True,
False,
float("inf"),
float("-inf"),
float("nan"),
)
def test_type_error(self, parameter_values):
"""Test type error if invalid input."""
with self.assertRaises(TypeError):
validation._validate_parameter_values(parameter_values)
def test_value_error(self):
"""Test value error if no parameter_values or default are provided."""
with self.assertRaises(ValueError):
validation._validate_parameter_values(None)
class TestCircuitKey(QiskitTestCase):
"""Tests for _circuit_key function"""
def test_different_circuits(self):
"""Test collision of quantum circuits."""
with self.subTest("Ry circuit"):
def test_func(n):
qc = QuantumCircuit(1, 1, name="foo")
qc.ry(n, 0)
return qc
keys = [_circuit_key(test_func(i)) for i in range(5)]
self.assertEqual(len(keys), len(set(keys)))
with self.subTest("pulse circuit"):
def test_with_scheduling(n):
custom_gate = pulse.Schedule(name="custom_x_gate")
custom_gate.insert(
0, pulse.Play(pulse.Constant(160 * n, 0.1), pulse.DriveChannel(0)), inplace=True
)
qc = QuantumCircuit(1)
qc.x(0)
qc.add_calibration("x", qubits=(0,), schedule=custom_gate)
backend = GenericBackendV2(
num_qubits=2, basis_gates=["id", "u1", "u2", "u3", "cx"], seed=42
)
return transpile(qc, backend, scheduling_method="alap", optimization_level=1)
keys = [_circuit_key(test_with_scheduling(i)) for i in range(1, 5)]
self.assertEqual(len(keys), len(set(keys)))
def test_circuit_key_controlflow(self):
"""Test for a circuit with control flow."""
qc = QuantumCircuit(2, 1)
with qc.for_loop(range(5)):
qc.h(0)
qc.cx(0, 1)
qc.measure(0, 0)
qc.break_loop().c_if(0, True)
self.assertIsInstance(hash(_circuit_key(qc)), int)
self.assertIsInstance(json.dumps(_circuit_key(qc)), str)
| qiskit/test/python/primitives/test_primitive.py/0 | {
"file_path": "qiskit/test/python/primitives/test_primitive.py",
"repo_id": "qiskit",
"token_count": 2669
} | 320 |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2023, 2024.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
""" Test of GenericBackendV2 backend"""
import math
from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister, transpile
from qiskit.providers.fake_provider import GenericBackendV2
from qiskit.quantum_info import Operator
from qiskit.transpiler import CouplingMap
from qiskit.exceptions import QiskitError
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
from test import QiskitTestCase # pylint: disable=wrong-import-order
class TestGenericBackendV2(QiskitTestCase):
"""Test class for GenericBackendV2 backend"""
def setUp(self):
super().setUp()
self.cmap = CouplingMap(
[(0, 2), (0, 1), (1, 3), (2, 4), (2, 3), (3, 5), (4, 6), (4, 5), (5, 7), (6, 7)]
)
def test_supported_basis_gates(self):
"""Test that target raises error if basis_gate not in ``supported_names``."""
with self.assertRaises(QiskitError):
GenericBackendV2(num_qubits=8, basis_gates=["cx", "id", "rz", "sx", "zz"], seed=42)
def test_cx_1Q(self):
"""Test failing with a backend with single qubit but with a two-qubit basis gate"""
with self.assertRaises(QiskitError):
GenericBackendV2(num_qubits=1, basis_gates=["cx", "id"], seed=42)
def test_ccx_2Q(self):
"""Test failing with a backend with two qubits but with a three-qubit basis gate"""
with self.assertRaises(QiskitError):
GenericBackendV2(num_qubits=2, basis_gates=["ccx", "id"], seed=42)
def test_calibration_no_noise_info(self):
"""Test failing with a backend with calibration and no noise info"""
with self.assertRaises(QiskitError):
GenericBackendV2(
num_qubits=2,
basis_gates=["ccx", "id"],
calibrate_instructions=True,
noise_info=False,
seed=42,
)
def test_no_noise(self):
"""Test no noise info when parameter is false"""
backend = GenericBackendV2(
num_qubits=5, coupling_map=CouplingMap.from_line(5), noise_info=False, seed=42
)
qc = QuantumCircuit(5)
qc.h(0)
qc.cx(0, 1)
qc.cx(0, 2)
qc.cx(1, 4)
qc.cx(3, 0)
qc.cx(2, 4)
qc_res = generate_preset_pass_manager(optimization_level=2, backend=backend).run(qc)
self.assertTrue(Operator.from_circuit(qc_res).equiv(qc))
self.assertEqual(backend.target.qubit_properties, None)
def test_no_noise_fully_connected(self):
"""Test no noise info when parameter is false"""
backend = GenericBackendV2(num_qubits=5, noise_info=False, seed=42)
qc = QuantumCircuit(5)
qc.h(0)
qc.cx(0, 1)
qc.cx(0, 2)
qc.cx(1, 4)
qc.cx(3, 0)
qc.cx(2, 4)
qc_res = generate_preset_pass_manager(optimization_level=2, backend=backend).run(qc)
self.assertTrue(Operator.from_circuit(qc_res).equiv(qc))
self.assertEqual(backend.target.qubit_properties, None)
def test_no_info(self):
"""Test no noise info when parameter is false"""
backend = GenericBackendV2(
num_qubits=5,
coupling_map=CouplingMap.from_line(5),
noise_info=False,
pulse_channels=False,
seed=42,
)
qc = QuantumCircuit(5)
qc.h(0)
qc.cx(0, 1)
qc.cx(0, 2)
qc.cx(1, 4)
qc.cx(3, 0)
qc.cx(2, 4)
qc_res = generate_preset_pass_manager(optimization_level=2, backend=backend).run(qc)
self.assertTrue(Operator.from_circuit(qc_res).equiv(qc))
self.assertEqual(backend.target.qubit_properties, None)
def test_no_pulse_channels(self):
"""Test no/empty pulse channels when parameter is false"""
backend = GenericBackendV2(
num_qubits=5, coupling_map=CouplingMap.from_line(5), pulse_channels=False, seed=42
)
qc = QuantumCircuit(5)
qc.h(0)
qc.cx(0, 1)
qc.cx(0, 2)
qc.cx(1, 4)
qc.cx(3, 0)
qc.cx(2, 4)
qc_res = generate_preset_pass_manager(optimization_level=2, backend=backend).run(qc)
self.assertTrue(Operator.from_circuit(qc_res).equiv(qc))
self.assertTrue(len(backend.channels_map) == 0)
def test_operation_names(self):
"""Test that target basis gates include "delay", "measure" and "reset" even
if not provided by user."""
target = GenericBackendV2(num_qubits=8, seed=42)
op_names = list(target.operation_names)
op_names.sort()
self.assertEqual(op_names, ["cx", "delay", "id", "measure", "reset", "rz", "sx", "x"])
target = GenericBackendV2(num_qubits=8, basis_gates=["ecr", "id", "rz", "sx", "x"], seed=42)
op_names = list(target.operation_names)
op_names.sort()
self.assertEqual(op_names, ["delay", "ecr", "id", "measure", "reset", "rz", "sx", "x"])
def test_incompatible_coupling_map(self):
"""Test that the size of the coupling map must match num_qubits."""
with self.assertRaises(QiskitError):
GenericBackendV2(num_qubits=5, coupling_map=self.cmap, seed=42)
def test_control_flow_operation_names(self):
"""Test that control flow instructions are added to the target if control_flow is True."""
target = GenericBackendV2(
num_qubits=8,
basis_gates=["ecr", "id", "rz", "sx", "x"],
coupling_map=self.cmap,
control_flow=True,
seed=42,
).target
op_names = list(target.operation_names)
op_names.sort()
reference = [
"break",
"continue",
"delay",
"ecr",
"for_loop",
"id",
"if_else",
"measure",
"reset",
"rz",
"switch_case",
"sx",
"while_loop",
"x",
]
self.assertEqual(op_names, reference)
def test_default_coupling_map(self):
"""Test that fully-connected coupling map is generated correctly."""
# fmt: off
reference_cmap = [(0, 1), (1, 0), (0, 2), (2, 0), (0, 3), (3, 0), (0, 4), (4, 0), (1, 2), (2, 1),
(1, 3), (3, 1), (1, 4), (4, 1), (2, 3), (3, 2), (2, 4), (4, 2), (3, 4), (4, 3)]
# fmt: on
self.assertEqual(
list(GenericBackendV2(num_qubits=5, seed=42).coupling_map.get_edges()),
reference_cmap,
)
def test_run(self):
"""Test run method, confirm correct noisy simulation if Aer is installed."""
qr = QuantumRegister(5)
cr = ClassicalRegister(5)
qc = QuantumCircuit(qr, cr)
qc.h(qr[0])
for k in range(1, 4):
qc.cx(qr[0], qr[k])
qc.measure(qr, cr)
backend = GenericBackendV2(num_qubits=5, basis_gates=["cx", "id", "rz", "sx", "x"], seed=42)
tqc = transpile(qc, backend=backend, optimization_level=3, seed_transpiler=42)
result = backend.run(tqc, seed_simulator=42, shots=1000).result()
counts = result.get_counts()
self.assertTrue(math.isclose(counts["00000"], 500, rel_tol=0.1))
self.assertTrue(math.isclose(counts["01111"], 500, rel_tol=0.1))
def test_duration_defaults(self):
"""Test that the basis gates are assigned duration defaults within expected ranges."""
basis_gates = ["cx", "id", "rz", "sx", "x", "sdg", "rxx"]
expected_durations = {
"cx": (7.992e-08, 8.99988e-07),
"id": (2.997e-08, 5.994e-08),
"rz": (0.0, 0.0),
"sx": (2.997e-08, 5.994e-08),
"x": (2.997e-08, 5.994e-08),
"measure": (6.99966e-07, 1.500054e-06),
"sdg": (2.997e-08, 5.994e-08),
"rxx": (7.992e-08, 8.99988e-07),
}
for _ in range(20):
target = GenericBackendV2(num_qubits=2, basis_gates=basis_gates, seed=42).target
for inst in target:
for qargs in target.qargs_for_operation_name(inst):
duration = target[inst][qargs].duration
if inst not in ["delay", "reset"]:
self.assertGreaterEqual(duration, expected_durations[inst][0])
self.assertLessEqual(duration, expected_durations[inst][1])
| qiskit/test/python/providers/fake_provider/test_generic_backend_v2.py/0 | {
"file_path": "qiskit/test/python/providers/fake_provider/test_generic_backend_v2.py",
"repo_id": "qiskit",
"token_count": 4376
} | 321 |
# 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 continuous pulse functions."""
import numpy as np
from qiskit.pulse.library import continuous
from test import QiskitTestCase # pylint: disable=wrong-import-order
class TestContinuousPulses(QiskitTestCase):
"""Test continuous pulses."""
def test_constant(self):
"""Test constant pulse."""
amp = 0.5j
samples = 50
times = np.linspace(0, 10, samples)
constant_arr = continuous.constant(times, amp=amp)
self.assertEqual(constant_arr.dtype, np.complex128)
np.testing.assert_equal(constant_arr, amp)
self.assertEqual(len(constant_arr), samples)
def test_zero(self):
"""Test constant pulse."""
times = np.linspace(0, 10, 50)
zero_arr = continuous.zero(times)
self.assertEqual(zero_arr.dtype, np.complex128)
np.testing.assert_equal(zero_arr, 0.0)
self.assertEqual(len(zero_arr), 50)
def test_square(self):
"""Test square wave."""
amp = 0.5
freq = 0.2
samples = 100
times = np.linspace(0, 10, samples)
square_arr = continuous.square(times, amp=amp, freq=freq)
# with new phase
square_arr_phased = continuous.square(times, amp=amp, freq=freq, phase=np.pi / 2)
self.assertEqual(square_arr.dtype, np.complex128)
self.assertAlmostEqual(square_arr[0], amp)
# test constant
self.assertAlmostEqual(square_arr[1] - square_arr[0], 0.0)
self.assertAlmostEqual(square_arr[25], -amp)
self.assertAlmostEqual(square_arr_phased[0], -amp)
# Assert bounded between -amp and amp
self.assertTrue(np.all((-amp <= square_arr) & (square_arr <= amp)))
self.assertEqual(len(square_arr), samples)
def test_sawtooth(self):
"""Test sawtooth wave."""
amp = 0.5
freq = 0.2
samples = 101
times, dt = np.linspace(0, 10, samples, retstep=True)
sawtooth_arr = continuous.sawtooth(times, amp=amp, freq=freq)
# with new phase
sawtooth_arr_phased = continuous.sawtooth(times, amp=amp, freq=freq, phase=np.pi / 2)
self.assertEqual(sawtooth_arr.dtype, np.complex128)
self.assertAlmostEqual(sawtooth_arr[0], 0.0)
# test slope
self.assertAlmostEqual((sawtooth_arr[1] - sawtooth_arr[0]) / dt, 2 * amp * freq)
self.assertAlmostEqual(sawtooth_arr[24], 0.48)
self.assertAlmostEqual(sawtooth_arr[50], 0.0)
self.assertAlmostEqual(sawtooth_arr[75], -amp)
self.assertAlmostEqual(sawtooth_arr_phased[0], -amp)
# Assert bounded between -amp and amp
self.assertTrue(np.all((-amp <= sawtooth_arr) & (sawtooth_arr <= amp)))
self.assertEqual(len(sawtooth_arr), samples)
def test_triangle(self):
"""Test triangle wave."""
amp = 0.5
freq = 0.2
samples = 101
times, dt = np.linspace(0, 10, samples, retstep=True)
triangle_arr = continuous.triangle(times, amp=amp, freq=freq)
# with new phase
triangle_arr_phased = continuous.triangle(times, amp=amp, freq=freq, phase=np.pi / 2)
self.assertEqual(triangle_arr.dtype, np.complex128)
self.assertAlmostEqual(triangle_arr[0], 0.0)
# test slope
self.assertAlmostEqual((triangle_arr[1] - triangle_arr[0]) / dt, 4 * amp * freq)
self.assertAlmostEqual(triangle_arr[12], 0.48)
self.assertAlmostEqual(triangle_arr[13], 0.48)
self.assertAlmostEqual(triangle_arr[50], 0.0)
self.assertAlmostEqual(triangle_arr_phased[0], amp)
# Assert bounded between -amp and amp
self.assertTrue(np.all((-amp <= triangle_arr) & (triangle_arr <= amp)))
self.assertEqual(len(triangle_arr), samples)
def test_cos(self):
"""Test cosine wave."""
amp = 0.5
period = 5
freq = 1 / period
samples = 101
times = np.linspace(0, 10, samples)
cos_arr = continuous.cos(times, amp=amp, freq=freq)
# with new phase
cos_arr_phased = continuous.cos(times, amp=amp, freq=freq, phase=np.pi / 2)
self.assertEqual(cos_arr.dtype, np.complex128)
# Assert starts at 1
self.assertAlmostEqual(cos_arr[0], amp)
self.assertAlmostEqual(cos_arr[6], 0.3644, places=2)
self.assertAlmostEqual(cos_arr[25], -amp)
self.assertAlmostEqual(cos_arr[50], amp)
self.assertAlmostEqual(cos_arr_phased[0], 0.0)
# Assert bounded between -amp and amp
self.assertTrue(np.all((-amp <= cos_arr) & (cos_arr <= amp)))
self.assertEqual(len(cos_arr), samples)
def test_sin(self):
"""Test sine wave."""
amp = 0.5
period = 5
freq = 1 / period
samples = 101
times = np.linspace(0, 10, samples)
sin_arr = continuous.sin(times, amp=amp, freq=freq)
# with new phase
sin_arr_phased = continuous.sin(times, amp=0.5, freq=1 / 5, phase=np.pi / 2)
self.assertEqual(sin_arr.dtype, np.complex128)
# Assert starts at 1
self.assertAlmostEqual(sin_arr[0], 0.0)
self.assertAlmostEqual(sin_arr[6], 0.3427, places=2)
self.assertAlmostEqual(sin_arr[25], 0.0)
self.assertAlmostEqual(sin_arr[13], amp, places=2)
self.assertAlmostEqual(sin_arr_phased[0], amp)
# Assert bounded between -amp and amp
self.assertTrue(np.all((-amp <= sin_arr) & (sin_arr <= amp)))
self.assertEqual(len(sin_arr), samples)
def test_gaussian(self):
"""Test gaussian pulse."""
amp = 0.5
duration = 20
center = duration / 2
sigma = 2
times, dt = np.linspace(0, duration, 1001, retstep=True)
gaussian_arr = continuous.gaussian(times, amp, center, sigma)
gaussian_arr_zeroed = continuous.gaussian(
np.array([-1, center, duration + 1]),
amp,
center,
sigma,
zeroed_width=2 * (center + 1),
rescale_amp=True,
)
self.assertEqual(gaussian_arr.dtype, np.complex128)
center_time = np.argmax(gaussian_arr)
self.assertAlmostEqual(times[center_time], center)
self.assertAlmostEqual(gaussian_arr[center_time], amp)
self.assertAlmostEqual(gaussian_arr_zeroed[0], 0.0, places=6)
self.assertAlmostEqual(gaussian_arr_zeroed[1], amp)
self.assertAlmostEqual(gaussian_arr_zeroed[2], 0.0, places=6)
self.assertAlmostEqual(
np.sum(gaussian_arr * dt), amp * np.sqrt(2 * np.pi * sigma**2), places=3
)
def test_gaussian_deriv(self):
"""Test gaussian derivative pulse."""
amp = 0.5
center = 10
sigma = 2
times, dt = np.linspace(0, 20, 1000, retstep=True)
deriv_prefactor = -(sigma**2) / (times - center)
gaussian_deriv_arr = continuous.gaussian_deriv(times, amp, center, sigma)
gaussian_arr = gaussian_deriv_arr * deriv_prefactor
self.assertEqual(gaussian_deriv_arr.dtype, np.complex128)
self.assertAlmostEqual(
continuous.gaussian_deriv(np.array([0]), amp, center, sigma)[0], 0, places=5
)
self.assertAlmostEqual(
np.sum(gaussian_arr * dt), amp * np.sqrt(2 * np.pi * sigma**2), places=3
)
def test_sech(self):
"""Test sech pulse."""
amp = 0.5
duration = 40
center = duration / 2
sigma = 2
times, dt = np.linspace(0, duration, 1001, retstep=True)
sech_arr = continuous.sech(times, amp, center, sigma)
sech_arr_zeroed = continuous.sech(np.array([-1, center, duration + 1]), amp, center, sigma)
self.assertEqual(sech_arr.dtype, np.complex128)
center_time = np.argmax(sech_arr)
self.assertAlmostEqual(times[center_time], center)
self.assertAlmostEqual(sech_arr[center_time], amp)
self.assertAlmostEqual(sech_arr_zeroed[0], 0.0, places=2)
self.assertAlmostEqual(sech_arr_zeroed[1], amp)
self.assertAlmostEqual(sech_arr_zeroed[2], 0.0, places=2)
self.assertAlmostEqual(np.sum(sech_arr * dt), amp * np.pi * sigma, places=3)
def test_sech_deriv(self):
"""Test sech derivative pulse."""
amp = 0.5
center = 20
sigma = 2
times = np.linspace(0, 40, 1000)
sech_deriv_arr = continuous.sech_deriv(times, amp, center, sigma)
self.assertEqual(sech_deriv_arr.dtype, np.complex128)
self.assertAlmostEqual(
continuous.sech_deriv(np.array([0]), amp, center, sigma)[0], 0, places=3
)
def test_gaussian_square(self):
"""Test gaussian square pulse."""
amp = 0.5
center = 10
width = 2
sigma = 0.1
times, dt = np.linspace(0, 20, 2001, retstep=True)
gaussian_square_arr = continuous.gaussian_square(times, amp, center, width, sigma)
self.assertEqual(gaussian_square_arr.dtype, np.complex128)
self.assertEqual(gaussian_square_arr[1000], amp)
# test half gaussian rise/fall
self.assertAlmostEqual(
np.sum(gaussian_square_arr[:900] * dt) * 2,
amp * np.sqrt(2 * np.pi * sigma**2),
places=2,
)
self.assertAlmostEqual(
np.sum(gaussian_square_arr[1100:] * dt) * 2,
amp * np.sqrt(2 * np.pi * sigma**2),
places=2,
)
# test for continuity at gaussian/square boundaries
gauss_rise_end_time = center - width / 2
gauss_fall_start_time = center + width / 2
epsilon = 0.01
rise_times, dt_rise = np.linspace(
gauss_rise_end_time - epsilon, gauss_rise_end_time + epsilon, 1001, retstep=True
)
fall_times, dt_fall = np.linspace(
gauss_fall_start_time - epsilon, gauss_fall_start_time + epsilon, 1001, retstep=True
)
gaussian_square_rise_arr = continuous.gaussian_square(rise_times, amp, center, width, sigma)
gaussian_square_fall_arr = continuous.gaussian_square(fall_times, amp, center, width, sigma)
# should be locally approximated by amp*dt^2/(2*sigma^2)
self.assertAlmostEqual(
amp * dt_rise**2 / (2 * sigma**2),
gaussian_square_rise_arr[500] - gaussian_square_rise_arr[499],
)
self.assertAlmostEqual(
amp * dt_fall**2 / (2 * sigma**2),
gaussian_square_fall_arr[501] - gaussian_square_fall_arr[500],
)
def test_drag(self):
"""Test drag pulse."""
amp = 0.5
center = 10
sigma = 0.1
beta = 0
times = np.linspace(0, 20, 2001)
# test that we recover gaussian for beta=0
gaussian_arr = continuous.gaussian(
times, amp, center, sigma, zeroed_width=2 * (center + 1), rescale_amp=True
)
drag_arr = continuous.drag(
times, amp, center, sigma, beta=beta, zeroed_width=2 * (center + 1), rescale_amp=True
)
self.assertEqual(drag_arr.dtype, np.complex128)
np.testing.assert_equal(drag_arr, gaussian_arr)
| qiskit/test/python/pulse/test_continuous_pulses.py/0 | {
"file_path": "qiskit/test/python/pulse/test_continuous_pulses.py",
"repo_id": "qiskit",
"token_count": 5382
} | 322 |
# 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.
"""Qobj tests."""
import copy
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.compiler import assemble
from qiskit.qobj import (
QasmQobj,
PulseQobj,
QobjHeader,
PulseQobjInstruction,
PulseQobjExperiment,
PulseQobjConfig,
QobjMeasurementOption,
PulseLibraryItem,
QasmQobjInstruction,
QasmQobjExperiment,
QasmQobjConfig,
QasmExperimentCalibrations,
GateCalibration,
)
from test import QiskitTestCase # pylint: disable=wrong-import-order
class TestQASMQobj(QiskitTestCase):
"""Tests for QasmQobj."""
def setUp(self):
super().setUp()
with self.assertWarns(DeprecationWarning):
self.valid_qobj = QasmQobj(
qobj_id="12345",
header=QobjHeader(),
config=QasmQobjConfig(shots=1024, memory_slots=2),
experiments=[
QasmQobjExperiment(
instructions=[
QasmQobjInstruction(name="u1", qubits=[1], params=[0.4]),
QasmQobjInstruction(name="u2", qubits=[1], params=[0.4, 0.2]),
]
)
],
)
self.valid_dict = {
"qobj_id": "12345",
"type": "QASM",
"schema_version": "1.2.0",
"header": {},
"config": {"memory_slots": 2, "shots": 1024},
"experiments": [
{
"instructions": [
{"name": "u1", "params": [0.4], "qubits": [1]},
{"name": "u2", "params": [0.4, 0.2], "qubits": [1]},
]
}
],
}
with self.assertWarns(DeprecationWarning):
self.bad_qobj = copy.deepcopy(self.valid_qobj)
self.bad_qobj.experiments = []
def test_from_dict_per_class(self):
"""Test Qobj and its subclass representations given a dictionary."""
with self.assertWarns(DeprecationWarning):
test_parameters = {
QasmQobj: (self.valid_qobj, self.valid_dict),
QasmQobjConfig: (
QasmQobjConfig(shots=1, memory_slots=2),
{"shots": 1, "memory_slots": 2},
),
QasmQobjExperiment: (
QasmQobjExperiment(
instructions=[QasmQobjInstruction(name="u1", qubits=[1], params=[0.4])]
),
{"instructions": [{"name": "u1", "qubits": [1], "params": [0.4]}]},
),
QasmQobjInstruction: (
QasmQobjInstruction(name="u1", qubits=[1], params=[0.4]),
{"name": "u1", "qubits": [1], "params": [0.4]},
),
}
for qobj_class, (qobj_item, expected_dict) in test_parameters.items():
with self.subTest(msg=str(qobj_class)):
with self.assertWarns(DeprecationWarning):
qobj = qobj_class.from_dict(expected_dict)
self.assertEqual(qobj_item, qobj)
def test_snapshot_instruction_to_dict(self):
"""Test snapshot instruction to dict."""
with self.assertWarns(DeprecationWarning):
valid_qobj = QasmQobj(
qobj_id="12345",
header=QobjHeader(),
config=QasmQobjConfig(shots=1024, memory_slots=2),
experiments=[
QasmQobjExperiment(
instructions=[
QasmQobjInstruction(name="u1", qubits=[1], params=[0.4]),
QasmQobjInstruction(name="u2", qubits=[1], params=[0.4, 0.2]),
QasmQobjInstruction(
name="snapshot",
qubits=[1],
snapshot_type="statevector",
label="my_snap",
),
]
)
],
)
res = valid_qobj.to_dict()
expected_dict = {
"qobj_id": "12345",
"type": "QASM",
"schema_version": "1.3.0",
"header": {},
"config": {"memory_slots": 2, "shots": 1024},
"experiments": [
{
"instructions": [
{"name": "u1", "params": [0.4], "qubits": [1]},
{"name": "u2", "params": [0.4, 0.2], "qubits": [1]},
{
"name": "snapshot",
"qubits": [1],
"snapshot_type": "statevector",
"label": "my_snap",
},
],
"config": {},
"header": {},
}
],
}
self.assertEqual(expected_dict, res)
def test_snapshot_instruction_from_dict(self):
"""Test snapshot instruction from dict."""
with self.assertWarns(DeprecationWarning):
expected_qobj = QasmQobj(
qobj_id="12345",
header=QobjHeader(),
config=QasmQobjConfig(shots=1024, memory_slots=2),
experiments=[
QasmQobjExperiment(
instructions=[
QasmQobjInstruction(name="u1", qubits=[1], params=[0.4]),
QasmQobjInstruction(name="u2", qubits=[1], params=[0.4, 0.2]),
QasmQobjInstruction(
name="snapshot",
qubits=[1],
snapshot_type="statevector",
label="my_snap",
),
]
)
],
)
qobj_dict = {
"qobj_id": "12345",
"type": "QASM",
"schema_version": "1.2.0",
"header": {},
"config": {"memory_slots": 2, "shots": 1024},
"experiments": [
{
"instructions": [
{"name": "u1", "params": [0.4], "qubits": [1]},
{"name": "u2", "params": [0.4, 0.2], "qubits": [1]},
{
"name": "snapshot",
"qubits": [1],
"snapshot_type": "statevector",
"label": "my_snap",
},
]
}
],
}
with self.assertWarns(DeprecationWarning):
qobj = QasmQobj.from_dict(qobj_dict)
self.assertEqual(expected_qobj, qobj)
def test_change_qobj_after_compile(self):
"""Test modifying Qobj parameters after compile."""
qr = QuantumRegister(3)
cr = ClassicalRegister(3)
qc1 = QuantumCircuit(qr, cr)
qc2 = QuantumCircuit(qr, cr)
qc1.h(qr[0])
qc1.cx(qr[0], qr[1])
qc1.cx(qr[0], qr[2])
qc2.h(qr)
qc1.measure(qr, cr)
qc2.measure(qr, cr)
circuits = [qc1, qc2]
with self.assertWarns(DeprecationWarning):
qobj1 = assemble(circuits, shots=1024, seed=88)
qobj1.experiments[0].config.shots = 50
qobj1.experiments[1].config.shots = 1
self.assertTrue(qobj1.experiments[0].config.shots == 50)
self.assertTrue(qobj1.experiments[1].config.shots == 1)
self.assertTrue(qobj1.config.shots == 1024)
def test_gate_calibrations_to_dict(self):
"""Test gate calibrations to dict."""
with self.assertWarns(DeprecationWarning):
pulse_library = [PulseLibraryItem(name="test", samples=[1j, 1j])]
with self.assertWarns(DeprecationWarning):
valid_qobj = QasmQobj(
qobj_id="12345",
header=QobjHeader(),
config=QasmQobjConfig(shots=1024, memory_slots=2, pulse_library=pulse_library),
experiments=[
QasmQobjExperiment(
instructions=[QasmQobjInstruction(name="u1", qubits=[1], params=[0.4])],
config=QasmQobjConfig(
calibrations=QasmExperimentCalibrations(
gates=[
GateCalibration(
name="u1", qubits=[1], params=[0.4], instructions=[]
)
]
)
),
)
],
)
res = valid_qobj.to_dict()
expected_dict = {
"qobj_id": "12345",
"type": "QASM",
"schema_version": "1.3.0",
"header": {},
"config": {
"memory_slots": 2,
"shots": 1024,
"pulse_library": [{"name": "test", "samples": [1j, 1j]}],
},
"experiments": [
{
"instructions": [{"name": "u1", "params": [0.4], "qubits": [1]}],
"config": {
"calibrations": {
"gates": [
{"name": "u1", "qubits": [1], "params": [0.4], "instructions": []}
]
}
},
"header": {},
}
],
}
self.assertEqual(expected_dict, res)
class TestPulseQobj(QiskitTestCase):
"""Tests for PulseQobj."""
def setUp(self):
super().setUp()
with self.assertWarns(DeprecationWarning):
self.valid_qobj = PulseQobj(
qobj_id="12345",
header=QobjHeader(),
config=PulseQobjConfig(
shots=1024,
memory_slots=2,
meas_level=1,
memory_slot_size=8192,
meas_return="avg",
pulse_library=[
PulseLibraryItem(
name="pulse0", samples=[0.0 + 0.0j, 0.5 + 0.0j, 0.0 + 0.0j]
)
],
qubit_lo_freq=[4.9],
meas_lo_freq=[6.9],
rep_time=1000,
),
experiments=[
PulseQobjExperiment(
instructions=[
PulseQobjInstruction(name="pulse0", t0=0, ch="d0"),
PulseQobjInstruction(name="fc", t0=5, ch="d0", phase=1.57),
PulseQobjInstruction(name="fc", t0=5, ch="d0", phase=0.0),
PulseQobjInstruction(name="fc", t0=5, ch="d0", phase="P1"),
PulseQobjInstruction(name="setp", t0=10, ch="d0", phase=3.14),
PulseQobjInstruction(name="setf", t0=10, ch="d0", frequency=8.0),
PulseQobjInstruction(name="shiftf", t0=10, ch="d0", frequency=4.0),
PulseQobjInstruction(
name="acquire",
t0=15,
duration=5,
qubits=[0],
memory_slot=[0],
kernels=[
QobjMeasurementOption(
name="boxcar", params={"start_window": 0, "stop_window": 5}
)
],
),
]
)
],
)
self.valid_dict = {
"qobj_id": "12345",
"type": "PULSE",
"schema_version": "1.2.0",
"header": {},
"config": {
"memory_slots": 2,
"shots": 1024,
"meas_level": 1,
"memory_slot_size": 8192,
"meas_return": "avg",
"pulse_library": [{"name": "pulse0", "samples": [0, 0.5, 0]}],
"qubit_lo_freq": [4.9],
"meas_lo_freq": [6.9],
"rep_time": 1000,
},
"experiments": [
{
"instructions": [
{"name": "pulse0", "t0": 0, "ch": "d0"},
{"name": "fc", "t0": 5, "ch": "d0", "phase": 1.57},
{"name": "fc", "t0": 5, "ch": "d0", "phase": 0},
{"name": "fc", "t0": 5, "ch": "d0", "phase": "P1"},
{"name": "setp", "t0": 10, "ch": "d0", "phase": 3.14},
{"name": "setf", "t0": 10, "ch": "d0", "frequency": 8.0},
{"name": "shiftf", "t0": 10, "ch": "d0", "frequency": 4.0},
{
"name": "acquire",
"t0": 15,
"duration": 5,
"qubits": [0],
"memory_slot": [0],
"kernels": [
{"name": "boxcar", "params": {"start_window": 0, "stop_window": 5}}
],
},
]
}
],
}
def test_from_dict_per_class(self):
"""Test converting to Qobj and its subclass representations given a dictionary."""
with self.assertWarns(DeprecationWarning):
test_parameters = {
PulseQobj: (self.valid_qobj, self.valid_dict),
PulseQobjConfig: (
PulseQobjConfig(
meas_level=1,
memory_slot_size=8192,
meas_return="avg",
pulse_library=[PulseLibraryItem(name="pulse0", samples=[0.1 + 0.0j])],
qubit_lo_freq=[4.9],
meas_lo_freq=[6.9],
rep_time=1000,
),
{
"meas_level": 1,
"memory_slot_size": 8192,
"meas_return": "avg",
"pulse_library": [{"name": "pulse0", "samples": [0.1 + 0j]}],
"qubit_lo_freq": [4.9],
"meas_lo_freq": [6.9],
"rep_time": 1000,
},
),
PulseLibraryItem: (
PulseLibraryItem(name="pulse0", samples=[0.1 + 0.0j]),
{"name": "pulse0", "samples": [0.1 + 0j]},
),
PulseQobjExperiment: (
PulseQobjExperiment(
instructions=[PulseQobjInstruction(name="pulse0", t0=0, ch="d0")]
),
{"instructions": [{"name": "pulse0", "t0": 0, "ch": "d0"}]},
),
PulseQobjInstruction: (
PulseQobjInstruction(name="pulse0", t0=0, ch="d0"),
{"name": "pulse0", "t0": 0, "ch": "d0"},
),
}
for qobj_class, (qobj_item, expected_dict) in test_parameters.items():
with self.subTest(msg=str(qobj_class)):
with self.assertWarns(DeprecationWarning):
qobj = qobj_class.from_dict(expected_dict)
self.assertEqual(qobj_item, qobj)
def test_to_dict_per_class(self):
"""Test converting from Qobj and its subclass representations given a dictionary."""
with self.assertWarns(DeprecationWarning):
test_parameters = {
PulseQobj: (self.valid_qobj, self.valid_dict),
PulseQobjConfig: (
PulseQobjConfig(
meas_level=1,
memory_slot_size=8192,
meas_return="avg",
pulse_library=[PulseLibraryItem(name="pulse0", samples=[0.1 + 0.0j])],
qubit_lo_freq=[4.9],
meas_lo_freq=[6.9],
rep_time=1000,
),
{
"meas_level": 1,
"memory_slot_size": 8192,
"meas_return": "avg",
"pulse_library": [{"name": "pulse0", "samples": [0.1 + 0j]}],
"qubit_lo_freq": [4.9],
"meas_lo_freq": [6.9],
"rep_time": 1000,
},
),
PulseLibraryItem: (
PulseLibraryItem(name="pulse0", samples=[0.1 + 0.0j]),
{"name": "pulse0", "samples": [0.1 + 0j]},
),
PulseQobjExperiment: (
PulseQobjExperiment(
instructions=[PulseQobjInstruction(name="pulse0", t0=0, ch="d0")]
),
{"instructions": [{"name": "pulse0", "t0": 0, "ch": "d0"}]},
),
PulseQobjInstruction: (
PulseQobjInstruction(name="pulse0", t0=0, ch="d0"),
{"name": "pulse0", "t0": 0, "ch": "d0"},
),
}
for qobj_class, (qobj_item, expected_dict) in test_parameters.items():
with self.subTest(msg=str(qobj_class)):
self.assertEqual(qobj_item.to_dict(), expected_dict)
def _nop():
pass
| qiskit/test/python/qobj/test_qobj.py/0 | {
"file_path": "qiskit/test/python/qobj/test_qobj.py",
"repo_id": "qiskit",
"token_count": 11482
} | 323 |
# 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 Stinespring quantum channel representation class."""
import copy
import unittest
import numpy as np
from numpy.testing import assert_allclose
from qiskit import QiskitError
from qiskit.quantum_info.states import DensityMatrix
from qiskit.quantum_info import Stinespring
from .channel_test_case import ChannelTestCase
class TestStinespring(ChannelTestCase):
"""Tests for Stinespring channel representation."""
def test_init(self):
"""Test initialization"""
# Initialize from unitary
chan = Stinespring(self.UI)
assert_allclose(chan.data, self.UI)
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(chan.num_qubits, 1)
# Initialize from Stinespring
chan = Stinespring(self.depol_stine(0.5))
assert_allclose(chan.data, self.depol_stine(0.5))
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(chan.num_qubits, 1)
# Initialize from Non-CPTP
stine_l, stine_r = self.rand_matrix(4, 2), self.rand_matrix(4, 2)
chan = Stinespring((stine_l, stine_r))
assert_allclose(chan.data, (stine_l, stine_r))
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(chan.num_qubits, 1)
# Initialize with redundant second op
chan = Stinespring((stine_l, stine_l))
assert_allclose(chan.data, stine_l)
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(chan.num_qubits, 1)
# Wrong input or output dims should raise exception
self.assertRaises(QiskitError, Stinespring, stine_l, input_dims=4, output_dims=4)
def test_circuit_init(self):
"""Test initialization from a circuit."""
circuit, target = self.simple_circuit_no_measure()
op = Stinespring(circuit)
target = Stinespring(target)
self.assertEqual(op, target)
def test_circuit_init_except(self):
"""Test initialization from circuit with measure raises exception."""
circuit = self.simple_circuit_with_measure()
self.assertRaises(QiskitError, Stinespring, circuit)
def test_equal(self):
"""Test __eq__ method"""
stine = tuple(self.rand_matrix(4, 2) for _ in range(2))
self.assertEqual(Stinespring(stine), Stinespring(stine))
def test_copy(self):
"""Test copy method"""
mat = np.eye(4)
with self.subTest("Deep copy"):
orig = Stinespring(mat)
cpy = orig.copy()
cpy._data[0][0, 0] = 0.0
self.assertFalse(cpy == orig)
with self.subTest("Shallow copy"):
orig = Stinespring(mat)
clone = copy.copy(orig)
clone._data[0][0, 0] = 0.0
self.assertTrue(clone == orig)
def test_clone(self):
"""Test clone method"""
mat = np.eye(4)
orig = Stinespring(mat)
clone = copy.copy(orig)
clone._data[0][0, 0] = 0.0
self.assertTrue(clone == orig)
def test_is_cptp(self):
"""Test is_cptp method."""
self.assertTrue(Stinespring(self.depol_stine(0.5)).is_cptp())
self.assertTrue(Stinespring(self.UX).is_cptp())
# Non-CP
stine_l, stine_r = self.rand_matrix(4, 2), self.rand_matrix(4, 2)
self.assertFalse(Stinespring((stine_l, stine_r)).is_cptp())
self.assertFalse(Stinespring(self.UI + self.UX).is_cptp())
def test_conjugate(self):
"""Test conjugate method."""
stine_l, stine_r = self.rand_matrix(16, 2), self.rand_matrix(16, 2)
# Single Stinespring list
targ = Stinespring(stine_l.conj(), output_dims=4)
chan1 = Stinespring(stine_l, output_dims=4)
chan = chan1.conjugate()
self.assertEqual(chan, targ)
self.assertEqual(chan.dim, (2, 4))
# Double Stinespring list
targ = Stinespring((stine_l.conj(), stine_r.conj()), output_dims=4)
chan1 = Stinespring((stine_l, stine_r), output_dims=4)
chan = chan1.conjugate()
self.assertEqual(chan, targ)
self.assertEqual(chan.dim, (2, 4))
def test_transpose(self):
"""Test transpose method."""
stine_l, stine_r = self.rand_matrix(4, 2), self.rand_matrix(4, 2)
# Single square Stinespring list
targ = Stinespring(stine_l.T, 4, 2)
chan1 = Stinespring(stine_l, 2, 4)
chan = chan1.transpose()
self.assertEqual(chan, targ)
self.assertEqual(chan.dim, (4, 2))
# Double square Stinespring list
targ = Stinespring((stine_l.T, stine_r.T), 4, 2)
chan1 = Stinespring((stine_l, stine_r), 2, 4)
chan = chan1.transpose()
self.assertEqual(chan, targ)
self.assertEqual(chan.dim, (4, 2))
def test_adjoint(self):
"""Test adjoint method."""
stine_l, stine_r = self.rand_matrix(4, 2), self.rand_matrix(4, 2)
# Single square Stinespring list
targ = Stinespring(stine_l.T.conj(), 4, 2)
chan1 = Stinespring(stine_l, 2, 4)
chan = chan1.adjoint()
self.assertEqual(chan, targ)
self.assertEqual(chan.dim, (4, 2))
# Double square Stinespring list
targ = Stinespring((stine_l.T.conj(), stine_r.T.conj()), 4, 2)
chan1 = Stinespring((stine_l, stine_r), 2, 4)
chan = chan1.adjoint()
self.assertEqual(chan, targ)
self.assertEqual(chan.dim, (4, 2))
def test_compose_except(self):
"""Test compose different dimension exception"""
self.assertRaises(QiskitError, Stinespring(np.eye(2)).compose, Stinespring(np.eye(4)))
self.assertRaises(QiskitError, Stinespring(np.eye(2)).compose, 2)
def test_compose(self):
"""Test compose method."""
# Random input test state
rho_init = DensityMatrix(self.rand_rho(2))
# UnitaryChannel evolution
chan1 = Stinespring(self.UX)
chan2 = Stinespring(self.UY)
chan = chan1.compose(chan2)
rho_targ = rho_init & Stinespring(self.UZ)
self.assertEqual(rho_init.evolve(chan), rho_targ)
# 50% depolarizing channel
chan1 = Stinespring(self.depol_stine(0.5))
chan = chan1.compose(chan1)
rho_targ = rho_init & Stinespring(self.depol_stine(0.75))
self.assertEqual(rho_init.evolve(chan), rho_targ)
# Compose different dimensions
stine1, stine2 = self.rand_matrix(16, 2), self.rand_matrix(8, 4)
chan1 = Stinespring(stine1, input_dims=2, output_dims=4)
chan2 = Stinespring(stine2, input_dims=4, output_dims=2)
rho_targ = rho_init & chan1 & chan2
chan = chan1.compose(chan2)
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(rho_init.evolve(chan), rho_targ)
chan = chan1 & chan2
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(rho_init.evolve(chan), rho_targ)
def test_dot(self):
"""Test deprecated front compose method."""
# Random input test state
rho_init = DensityMatrix(self.rand_rho(2))
# UnitaryChannel evolution
chan1 = Stinespring(self.UX)
chan2 = Stinespring(self.UY)
rho_targ = rho_init.evolve(Stinespring(self.UZ))
self.assertEqual(rho_init.evolve(chan1.dot(chan2)), rho_targ)
self.assertEqual(rho_init.evolve(chan1 @ chan2), rho_targ)
# 50% depolarizing channel
chan1 = Stinespring(self.depol_stine(0.5))
rho_targ = rho_init & Stinespring(self.depol_stine(0.75))
self.assertEqual(rho_init.evolve(chan1.dot(chan1)), rho_targ)
self.assertEqual(rho_init.evolve(chan1 @ chan1), rho_targ)
# Compose different dimensions
stine1, stine2 = self.rand_matrix(16, 2), self.rand_matrix(8, 4)
chan1 = Stinespring(stine1, input_dims=2, output_dims=4)
chan2 = Stinespring(stine2, input_dims=4, output_dims=2)
rho_targ = rho_init & chan1 & chan2
self.assertEqual(rho_init.evolve(chan2.dot(chan1)), rho_targ)
self.assertEqual(rho_init.evolve(chan2 @ chan1), rho_targ)
def test_compose_front(self):
"""Test deprecated front compose method."""
# Random input test state
rho_init = DensityMatrix(self.rand_rho(2))
# UnitaryChannel evolution
chan1 = Stinespring(self.UX)
chan2 = Stinespring(self.UY)
chan = chan1.compose(chan2, front=True)
rho_targ = rho_init & Stinespring(self.UZ)
self.assertEqual(rho_init.evolve(chan), rho_targ)
# 50% depolarizing channel
chan1 = Stinespring(self.depol_stine(0.5))
chan = chan1.compose(chan1, front=True)
rho_targ = rho_init & Stinespring(self.depol_stine(0.75))
self.assertEqual(rho_init.evolve(chan), rho_targ)
# Compose different dimensions
stine1, stine2 = self.rand_matrix(16, 2), self.rand_matrix(8, 4)
chan1 = Stinespring(stine1, input_dims=2, output_dims=4)
chan2 = Stinespring(stine2, input_dims=4, output_dims=2)
rho_targ = rho_init & chan1 & chan2
chan = chan2.compose(chan1, front=True)
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(rho_init.evolve(chan), rho_targ)
def test_expand(self):
"""Test expand method."""
rho0, rho1 = np.diag([1, 0]), np.diag([0, 1])
rho_init = DensityMatrix(np.kron(rho0, rho0))
chan1 = Stinespring(self.UI)
chan2 = Stinespring(self.UX)
# X \otimes I
chan = chan1.expand(chan2)
rho_targ = DensityMatrix(np.kron(rho1, rho0))
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
# I \otimes X
chan = chan2.expand(chan1)
rho_targ = DensityMatrix(np.kron(rho0, rho1))
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
# Completely depolarizing
chan_dep = Stinespring(self.depol_stine(1))
chan = chan_dep.expand(chan_dep)
rho_targ = DensityMatrix(np.diag([1, 1, 1, 1]) / 4)
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
def test_tensor(self):
"""Test tensor method."""
rho0, rho1 = np.diag([1, 0]), np.diag([0, 1])
rho_init = DensityMatrix(np.kron(rho0, rho0))
chan1 = Stinespring(self.UI)
chan2 = Stinespring(self.UX)
# X \otimes I
chan = chan2.tensor(chan1)
rho_targ = DensityMatrix(np.kron(rho1, rho0))
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
# I \otimes X
chan = chan1.tensor(chan2)
rho_targ = DensityMatrix(np.kron(rho0, rho1))
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
# Completely depolarizing
chan_dep = Stinespring(self.depol_stine(1))
chan = chan_dep.tensor(chan_dep)
rho_targ = DensityMatrix(np.diag([1, 1, 1, 1]) / 4)
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
def test_power(self):
"""Test power method."""
# 10% depolarizing channel
rho_init = DensityMatrix(np.diag([1, 0]))
p_id = 0.9
chan1 = Stinespring(self.depol_stine(1 - p_id))
# Compose 3 times
p_id3 = p_id**3
chan = chan1.power(3)
rho_targ = rho_init & chan1 & chan1 & chan1
self.assertEqual(rho_init & chan, rho_targ)
rho_targ = rho_init & Stinespring(self.depol_stine(1 - p_id3))
self.assertEqual(rho_init & chan, rho_targ)
def test_add(self):
"""Test add method."""
# Random input test state
rho_init = DensityMatrix(self.rand_rho(2))
stine1, stine2 = self.rand_matrix(16, 2), self.rand_matrix(16, 2)
# Random Single-Stinespring maps
chan1 = Stinespring(stine1, input_dims=2, output_dims=4)
chan2 = Stinespring(stine2, input_dims=2, output_dims=4)
rho_targ = (rho_init & chan1) + (rho_init & chan2)
chan = chan1._add(chan2)
self.assertEqual(rho_init.evolve(chan), rho_targ)
chan = chan1 + chan2
self.assertEqual(rho_init.evolve(chan), rho_targ)
# Random Single-Stinespring maps
chan = Stinespring((stine1, stine2))
rho_targ = 2 * (rho_init & chan)
chan = chan._add(chan)
self.assertEqual(rho_init.evolve(chan), rho_targ)
def test_subtract(self):
"""Test subtract method."""
# Random input test state
rho_init = DensityMatrix(self.rand_rho(2))
stine1, stine2 = self.rand_matrix(16, 2), self.rand_matrix(16, 2)
# Random Single-Stinespring maps
chan1 = Stinespring(stine1, input_dims=2, output_dims=4)
chan2 = Stinespring(stine2, input_dims=2, output_dims=4)
rho_targ = (rho_init & chan1) - (rho_init & chan2)
chan = chan1 - chan2
self.assertEqual(rho_init.evolve(chan), rho_targ)
# Random Single-Stinespring maps
chan = Stinespring((stine1, stine2))
rho_targ = 0 * (rho_init & chan)
chan = chan - chan
self.assertEqual(rho_init.evolve(chan), rho_targ)
def test_add_qargs(self):
"""Test add method with qargs."""
rho = DensityMatrix(self.rand_rho(8))
stine = self.rand_matrix(32, 8)
stine0 = self.rand_matrix(8, 2)
op = Stinespring(stine)
op0 = Stinespring(stine0)
eye = Stinespring(self.UI)
with self.subTest(msg="qargs=[0]"):
value = op + op0([0])
target = op + eye.tensor(eye).tensor(op0)
self.assertEqual(rho & value, rho & target)
with self.subTest(msg="qargs=[1]"):
value = op + op0([1])
target = op + eye.tensor(op0).tensor(eye)
self.assertEqual(rho & value, rho & target)
with self.subTest(msg="qargs=[2]"):
value = op + op0([2])
target = op + op0.tensor(eye).tensor(eye)
self.assertEqual(rho & value, rho & target)
def test_sub_qargs(self):
"""Test sub method with qargs."""
rho = DensityMatrix(self.rand_rho(8))
stine = self.rand_matrix(32, 8)
stine0 = self.rand_matrix(8, 2)
op = Stinespring(stine)
op0 = Stinespring(stine0)
eye = Stinespring(self.UI)
with self.subTest(msg="qargs=[0]"):
value = op - op0([0])
target = op - eye.tensor(eye).tensor(op0)
self.assertEqual(rho & value, rho & target)
with self.subTest(msg="qargs=[1]"):
value = op - op0([1])
target = op - eye.tensor(op0).tensor(eye)
self.assertEqual(rho & value, rho & target)
with self.subTest(msg="qargs=[2]"):
value = op - op0([2])
target = op - op0.tensor(eye).tensor(eye)
self.assertEqual(rho & value, rho & target)
def test_multiply(self):
"""Test multiply method."""
# Random initial state and Stinespring ops
rho_init = DensityMatrix(self.rand_rho(2))
val = 0.5
stine1, stine2 = self.rand_matrix(16, 2), self.rand_matrix(16, 2)
# Single Stinespring set
chan1 = Stinespring(stine1, input_dims=2, output_dims=4)
rho_targ = val * (rho_init & chan1)
chan = chan1._multiply(val)
self.assertEqual(rho_init.evolve(chan), rho_targ)
chan = val * chan1
self.assertEqual(rho_init.evolve(chan), rho_targ)
rho_targ = (rho_init & chan1) * val
chan = chan1 * val
self.assertEqual(rho_init.evolve(chan), rho_targ)
# Double Stinespring set
chan2 = Stinespring((stine1, stine2), input_dims=2, output_dims=4)
rho_targ = val * (rho_init & chan2)
chan = chan2._multiply(val)
self.assertEqual(rho_init.evolve(chan), rho_targ)
chan = val * chan2
self.assertEqual(rho_init.evolve(chan), rho_targ)
def test_multiply_except(self):
"""Test multiply method raises exceptions."""
chan = Stinespring(self.depol_stine(1))
self.assertRaises(QiskitError, chan._multiply, "s")
self.assertRaises(QiskitError, chan.__rmul__, "s")
self.assertRaises(QiskitError, chan._multiply, chan)
self.assertRaises(QiskitError, chan.__rmul__, chan)
def test_negate(self):
"""Test negate method"""
rho_init = DensityMatrix(np.diag([1, 0]))
rho_targ = DensityMatrix(np.diag([-0.5, -0.5]))
chan = -Stinespring(self.depol_stine(1))
self.assertEqual(rho_init.evolve(chan), rho_targ)
if __name__ == "__main__":
unittest.main()
| qiskit/test/python/quantum_info/operators/channel/test_stinespring.py/0 | {
"file_path": "qiskit/test/python/quantum_info/operators/channel/test_stinespring.py",
"repo_id": "qiskit",
"token_count": 8462
} | 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.
"""Test Qiskit's Result class."""
import numpy as np
from qiskit.result import models
from qiskit.result import marginal_counts
from qiskit.result import marginal_distribution
from qiskit.result import Result
from qiskit.qobj import QobjExperimentHeader
from qiskit.exceptions import QiskitError
from test import QiskitTestCase # pylint: disable=wrong-import-order
class TestResultOperations(QiskitTestCase):
"""Result operations methods."""
def setUp(self):
self.base_result_args = {
"backend_name": "test_backend",
"backend_version": "1.0.0",
"qobj_id": "id-123",
"job_id": "job-123",
"success": True,
}
super().setUp()
def generate_qiskit_result(self):
"""Generate standard Result for testing"""
memory = [hex(ii) for ii in range(8)]
counts = {m: 1 for m in memory}
data_1 = models.ExperimentResultData(counts=counts, memory=memory)
with self.assertWarns(DeprecationWarning):
exp_result_header_1 = QobjExperimentHeader(creg_sizes=[["c0", 4]], memory_slots=4)
exp_result_1 = models.ExperimentResult(
shots=8, success=True, data=data_1, header=exp_result_header_1
)
result = Result(results=[exp_result_1], **self.base_result_args)
return result
def test_counts_no_header(self):
"""Test that counts are extracted properly without header."""
raw_counts = {"0x0": 4, "0x2": 10}
no_header_processed_counts = {
bin(int(bs[2:], 16))[2:]: counts for (bs, counts) in raw_counts.items()
}
data = models.ExperimentResultData(counts=raw_counts)
exp_result = models.ExperimentResult(shots=14, success=True, meas_level=2, data=data)
result = Result(results=[exp_result], **self.base_result_args)
self.assertEqual(result.get_counts(0), no_header_processed_counts)
def test_counts_header(self):
"""Test that counts are extracted properly with header."""
raw_counts = {"0x0": 4, "0x2": 10}
processed_counts = {"0 0 00": 4, "0 0 10": 10}
data = models.ExperimentResultData(counts=raw_counts)
with self.assertWarns(DeprecationWarning):
exp_result_header = QobjExperimentHeader(
creg_sizes=[["c0", 2], ["c0", 1], ["c1", 1]], memory_slots=4
)
exp_result = models.ExperimentResult(
shots=14, success=True, meas_level=2, data=data, header=exp_result_header
)
result = Result(results=[exp_result], **self.base_result_args)
self.assertEqual(result.get_counts(0), processed_counts)
def test_counts_by_name(self):
"""Test that counts are extracted properly by name."""
raw_counts = {"0x0": 4, "0x2": 10}
processed_counts = {"0 0 00": 4, "0 0 10": 10}
data = models.ExperimentResultData(counts=raw_counts)
with self.assertWarns(DeprecationWarning):
exp_result_header = QobjExperimentHeader(
creg_sizes=[["c0", 2], ["c0", 1], ["c1", 1]], memory_slots=4, name="a_name"
)
exp_result = models.ExperimentResult(
shots=14, success=True, meas_level=2, data=data, header=exp_result_header
)
result = Result(results=[exp_result], **self.base_result_args)
self.assertEqual(result.get_counts("a_name"), processed_counts)
def test_counts_duplicate_name(self):
"""Test results containing multiple entries of a single name will warn."""
data = models.ExperimentResultData(counts={})
with self.assertWarns(DeprecationWarning):
exp_result_header = QobjExperimentHeader(name="foo")
exp_result = models.ExperimentResult(
shots=14, success=True, data=data, header=exp_result_header
)
result = Result(results=[exp_result] * 2, **self.base_result_args)
with self.assertWarnsRegex(UserWarning, r"multiple.*foo"):
result.get_counts("foo")
def test_result_repr(self):
"""Test that repr is constructed correctly for a results object."""
raw_counts = {"0x0": 4, "0x2": 10}
data = models.ExperimentResultData(counts=raw_counts)
with self.assertWarns(DeprecationWarning):
exp_result_header = QobjExperimentHeader(
creg_sizes=[["c0", 2], ["c0", 1], ["c1", 1]], memory_slots=4
)
exp_result = models.ExperimentResult(
shots=14, success=True, meas_level=2, data=data, header=exp_result_header
)
result = Result(results=[exp_result], **self.base_result_args)
expected = (
"Result(backend_name='test_backend', backend_version='1.0.0', "
"qobj_id='id-123', job_id='job-123', success=True, "
"results=[ExperimentResult(shots=14, success=True, "
"meas_level=2, data=ExperimentResultData(counts={'0x0': 4,"
" '0x2': 10}), header=QobjExperimentHeader(creg_sizes="
"[['c0', 2], ['c0', 1], ['c1', 1]], memory_slots=4))], date=None, "
"status=None, header=None)"
)
self.assertEqual(expected, repr(result))
def test_multiple_circuits_counts(self):
"""Test that counts are returned either as a list or a single item.
Counts are returned as a list when multiple experiments are executed
and get_counts() is called with no arguments. In all the other cases
get_counts() returns a single item containing the counts for a
single experiment.
"""
raw_counts_1 = {"0x0": 5, "0x3": 12, "0x5": 9, "0xD": 6, "0xE": 2}
processed_counts_1 = {"0000": 5, "0011": 12, "0101": 9, "1101": 6, "1110": 2}
data_1 = models.ExperimentResultData(counts=raw_counts_1)
with self.assertWarns(DeprecationWarning):
exp_result_header_1 = QobjExperimentHeader(creg_sizes=[["c0", 4]], memory_slots=4)
exp_result_1 = models.ExperimentResult(
shots=14, success=True, meas_level=2, data=data_1, header=exp_result_header_1
)
raw_counts_2 = {"0x1": 0, "0x4": 3, "0x6": 6, "0xA": 1, "0xB": 2}
processed_counts_2 = {"0001": 0, "0100": 3, "0110": 6, "1010": 1, "1011": 2}
data_2 = models.ExperimentResultData(counts=raw_counts_2)
with self.assertWarns(DeprecationWarning):
exp_result_header_2 = QobjExperimentHeader(creg_sizes=[["c0", 4]], memory_slots=4)
exp_result_2 = models.ExperimentResult(
shots=14, success=True, meas_level=2, data=data_2, header=exp_result_header_2
)
raw_counts_3 = {"0xC": 27, "0xF": 20}
processed_counts_3 = {"1100": 27, "1111": 20}
data_3 = models.ExperimentResultData(counts=raw_counts_3)
with self.assertWarns(DeprecationWarning):
exp_result_header_3 = QobjExperimentHeader(creg_sizes=[["c0", 4]], memory_slots=4)
exp_result_3 = models.ExperimentResult(
shots=14, success=True, meas_level=2, data=data_3, header=exp_result_header_3
)
mult_result = Result(
results=[exp_result_1, exp_result_2, exp_result_3], **self.base_result_args
)
sing_result = Result(results=[exp_result_1], **self.base_result_args)
self.assertEqual(
mult_result.get_counts(), [processed_counts_1, processed_counts_2, processed_counts_3]
)
self.assertEqual(sing_result.get_counts(), processed_counts_1)
def test_marginal_counts(self):
"""Test that counts are marginalized correctly."""
raw_counts = {"0x0": 4, "0x1": 7, "0x2": 10, "0x6": 5, "0x9": 11, "0xD": 9, "0xE": 8}
data = models.ExperimentResultData(counts=raw_counts)
with self.assertWarns(DeprecationWarning):
exp_result_header = QobjExperimentHeader(creg_sizes=[["c0", 4]], memory_slots=4)
exp_result = models.ExperimentResult(
shots=54, success=True, data=data, header=exp_result_header
)
result = Result(results=[exp_result], **self.base_result_args)
expected_marginal_counts = {"00": 4, "01": 27, "10": 23}
self.assertEqual(marginal_counts(result.get_counts(), [0, 1]), expected_marginal_counts)
self.assertEqual(marginal_counts(result.get_counts(), [1, 0]), expected_marginal_counts)
def test_marginal_distribution(self):
"""Test that counts are marginalized correctly."""
raw_counts = {"0x0": 4, "0x1": 7, "0x2": 10, "0x6": 5, "0x9": 11, "0xD": 9, "0xE": 8}
data = models.ExperimentResultData(counts=raw_counts)
with self.assertWarns(DeprecationWarning):
exp_result_header = QobjExperimentHeader(creg_sizes=[["c0", 4]], memory_slots=4)
exp_result = models.ExperimentResult(
shots=54, success=True, data=data, header=exp_result_header
)
result = Result(results=[exp_result], **self.base_result_args)
expected_marginal_counts = {"00": 4, "01": 27, "10": 23}
expected_reverse = {"00": 4, "10": 27, "01": 23}
self.assertEqual(
marginal_distribution(result.get_counts(), [0, 1]), expected_marginal_counts
)
self.assertEqual(marginal_distribution(result.get_counts(), [1, 0]), expected_reverse)
# test with register spacing, bitstrings are in form of "00 00" for register split
data = models.ExperimentResultData(counts=raw_counts)
with self.assertWarns(DeprecationWarning):
exp_result_header = QobjExperimentHeader(
creg_sizes=[["c0", 2], ["c1", 2]], memory_slots=4
)
exp_result = models.ExperimentResult(
shots=54, success=True, data=data, header=exp_result_header
)
result = Result(results=[exp_result], **self.base_result_args)
self.assertEqual(
marginal_distribution(result.get_counts(), [0, 1]), expected_marginal_counts
)
self.assertEqual(marginal_distribution(result.get_counts(), [1, 0]), expected_reverse)
def test_marginal_counts_result(self):
"""Test that a Result object containing counts marginalizes correctly."""
raw_counts_1 = {"0x0": 4, "0x1": 7, "0x2": 10, "0x6": 5, "0x9": 11, "0xD": 9, "0xE": 8}
data_1 = models.ExperimentResultData(counts=raw_counts_1)
with self.assertWarns(DeprecationWarning):
exp_result_header_1 = QobjExperimentHeader(creg_sizes=[["c0", 4]], memory_slots=4)
exp_result_1 = models.ExperimentResult(
shots=54, success=True, data=data_1, header=exp_result_header_1
)
raw_counts_2 = {"0x2": 5, "0x3": 8}
data_2 = models.ExperimentResultData(counts=raw_counts_2)
with self.assertWarns(DeprecationWarning):
exp_result_header_2 = QobjExperimentHeader(creg_sizes=[["c0", 2]], memory_slots=2)
exp_result_2 = models.ExperimentResult(
shots=13, success=True, data=data_2, header=exp_result_header_2
)
result = Result(results=[exp_result_1, exp_result_2], **self.base_result_args)
expected_marginal_counts_1 = {"00": 4, "01": 27, "10": 23}
expected_marginal_counts_2 = {"0": 5, "1": 8}
expected_marginal_counts_none = {
"0000": 4,
"0001": 7,
"0010": 10,
"0110": 5,
"1001": 11,
"1101": 9,
"1110": 8,
}
with self.assertWarns(DeprecationWarning):
self.assertEqual(
marginal_counts(result, [0, 1]).get_counts(0), expected_marginal_counts_1
)
self.assertEqual(marginal_counts(result, [0]).get_counts(1), expected_marginal_counts_2)
self.assertEqual(
marginal_counts(result, None).get_counts(0), expected_marginal_counts_none
)
def test_marginal_counts_result_memory(self):
"""Test that a Result object containing memory marginalizes correctly."""
result = self.generate_qiskit_result()
with self.assertWarns(DeprecationWarning):
marginal_result = marginal_counts(result, indices=[0])
marginal_memory = marginal_result.results[0].data.memory
self.assertEqual(marginal_memory, [hex(ii % 2) for ii in range(8)])
def test_marginal_counts_result_memory_nonzero_indices(self):
"""Test that a Result object containing memory marginalizes correctly."""
result = self.generate_qiskit_result()
index = 2
with self.assertWarns(DeprecationWarning):
marginal_result = marginal_counts(result, indices=[index])
marginal_memory = marginal_result.results[0].data.memory
mask = 1 << index
expected = [hex((ii & mask) >> index) for ii in range(8)]
self.assertEqual(marginal_memory, expected)
def test_marginal_counts_result_memory_indices_None(self):
"""Test that a Result object containing memory marginalizes correctly."""
result = self.generate_qiskit_result()
memory = "should not be touched"
result.results[0].data.memory = memory
with self.assertWarns(DeprecationWarning):
marginal_result = marginal_counts(result, indices=None)
marginal_memory = marginal_result.results[0].data.memory
self.assertEqual(marginal_memory, memory)
def test_marginal_counts_result_invalid_indices(self):
"""Test that a Result object containing memory marginalizes correctly inplace."""
result = self.generate_qiskit_result()
with self.assertRaises(QiskitError):
_ = marginal_counts(result, indices=[0, 1, 100], inplace=True)
def test_marginal_counts_result_marginalize_memory(self):
"""Test that a Result object containing memory marginalizes correctly inplace."""
result = self.generate_qiskit_result()
marginal_result = marginal_counts(
result, indices=[0], inplace=True, marginalize_memory=False
)
self.assertFalse(hasattr(marginal_result.results[0].data, "memory"))
result = self.generate_qiskit_result()
marginal_result = marginal_counts(
result, indices=[0], inplace=True, marginalize_memory=None
)
self.assertTrue(hasattr(marginal_result.results[0].data, "memory"))
result = self.generate_qiskit_result()
marginal_result = marginal_counts(
result, indices=[0], inplace=True, marginalize_memory=True
)
self.assertTrue(hasattr(marginal_result.results[0].data, "memory"))
result = self.generate_qiskit_result()
with self.assertWarns(DeprecationWarning):
marginal_result = marginal_counts(
result, indices=[0], inplace=False, marginalize_memory=False
)
self.assertFalse(hasattr(marginal_result.results[0].data, "memory"))
with self.assertWarns(DeprecationWarning):
marginal_result = marginal_counts(
result, indices=[0], inplace=False, marginalize_memory=None
)
self.assertTrue(hasattr(marginal_result.results[0].data, "memory"))
with self.assertWarns(DeprecationWarning):
marginal_result = marginal_counts(
result, indices=[0], inplace=False, marginalize_memory=True
)
self.assertTrue(hasattr(marginal_result.results[0].data, "memory"))
def test_marginal_counts_result_inplace(self):
"""Test that a Result object containing memory marginalizes correctly inplace."""
result = self.generate_qiskit_result()
marginal_result = marginal_counts(result, indices=[0], inplace=True)
self.assertEqual(id(result), id(marginal_result))
marginal_memory = marginal_result.results[0].data.memory
self.assertEqual(marginal_memory, [hex(ii % 2) for ii in range(8)])
def test_marginal_counts_result_creg_sizes(self):
"""Test that marginal_counts with Result input properly changes creg_sizes."""
raw_counts = {"0x0": 4, "0x1": 7, "0x2": 10, "0x6": 5, "0x9": 11, "0xD": 9, "0xE": 8}
data = models.ExperimentResultData(counts=raw_counts)
with self.assertWarns(DeprecationWarning):
exp_result_header = QobjExperimentHeader(
creg_sizes=[["c0", 1], ["c1", 3]], memory_slots=4
)
exp_result = models.ExperimentResult(
shots=54, success=True, data=data, header=exp_result_header
)
result = Result(results=[exp_result], **self.base_result_args)
expected_marginal_counts = {"0 0": 14, "0 1": 18, "1 0": 13, "1 1": 9}
expected_creg_sizes = [["c0", 1], ["c1", 1]]
expected_memory_slots = 2
with self.assertWarns(DeprecationWarning):
marginal_counts_result = marginal_counts(result, [0, 2])
self.assertEqual(marginal_counts_result.results[0].header.creg_sizes, expected_creg_sizes)
self.assertEqual(
marginal_counts_result.results[0].header.memory_slots, expected_memory_slots
)
self.assertEqual(marginal_counts_result.get_counts(0), expected_marginal_counts)
def test_marginal_counts_result_format(self):
"""Test that marginal_counts with format_marginal true properly formats output."""
raw_counts_1 = {"0x0": 4, "0x1": 7, "0x2": 10, "0x6": 5, "0x9": 11, "0xD": 9, "0x12": 8}
data_1 = models.ExperimentResultData(counts=raw_counts_1)
with self.assertWarns(DeprecationWarning):
exp_result_header_1 = QobjExperimentHeader(
creg_sizes=[["c0", 2], ["c1", 3]], memory_slots=5
)
exp_result_1 = models.ExperimentResult(
shots=54, success=True, data=data_1, header=exp_result_header_1
)
result = Result(results=[exp_result_1], **self.base_result_args)
expected_marginal_counts_1 = {
"0_0 _0": 14,
"0_0 _1": 18,
"0_1 _0": 5,
"0_1 _1": 9,
"1_0 _0": 8,
}
marginal_counts_result = marginal_counts(
result.get_counts(), [0, 2, 4], format_marginal=True
)
self.assertEqual(marginal_counts_result, expected_marginal_counts_1)
def test_marginal_counts_inplace_true(self):
"""Test marginal_counts(Result, inplace = True)"""
raw_counts_1 = {"0x0": 4, "0x1": 7, "0x2": 10, "0x6": 5, "0x9": 11, "0xD": 9, "0xE": 8}
data_1 = models.ExperimentResultData(counts=raw_counts_1)
with self.assertWarns(DeprecationWarning):
exp_result_header_1 = QobjExperimentHeader(creg_sizes=[["c0", 4]], memory_slots=4)
exp_result_1 = models.ExperimentResult(
shots=54, success=True, data=data_1, header=exp_result_header_1
)
raw_counts_2 = {"0x2": 5, "0x3": 8}
data_2 = models.ExperimentResultData(counts=raw_counts_2)
with self.assertWarns(DeprecationWarning):
exp_result_header_2 = QobjExperimentHeader(creg_sizes=[["c0", 2]], memory_slots=2)
exp_result_2 = models.ExperimentResult(
shots=13, success=True, data=data_2, header=exp_result_header_2
)
result = Result(results=[exp_result_1, exp_result_2], **self.base_result_args)
expected_marginal_counts = {"0": 27, "1": 27}
self.assertEqual(
marginal_counts(result, [0], inplace=True).get_counts(0), expected_marginal_counts
)
self.assertEqual(result.get_counts(0), expected_marginal_counts)
def test_marginal_counts_inplace_false(self):
"""Test marginal_counts(Result, inplace=False)"""
raw_counts_1 = {"0x0": 4, "0x1": 7, "0x2": 10, "0x6": 5, "0x9": 11, "0xD": 9, "0xE": 8}
data_1 = models.ExperimentResultData(counts=raw_counts_1)
with self.assertWarns(DeprecationWarning):
exp_result_header_1 = QobjExperimentHeader(creg_sizes=[["c0", 4]], memory_slots=4)
exp_result_1 = models.ExperimentResult(
shots=54, success=True, data=data_1, header=exp_result_header_1
)
raw_counts_2 = {"0x2": 5, "0x3": 8}
data_2 = models.ExperimentResultData(counts=raw_counts_2)
with self.assertWarns(DeprecationWarning):
exp_result_header_2 = QobjExperimentHeader(creg_sizes=[["c0", 2]], memory_slots=2)
exp_result_2 = models.ExperimentResult(
shots=13, success=True, data=data_2, header=exp_result_header_2
)
result = Result(results=[exp_result_1, exp_result_2], **self.base_result_args)
expected_marginal_counts = {"0": 27, "1": 27}
with self.assertWarns(DeprecationWarning):
self.assertEqual(
marginal_counts(result, [0], inplace=False).get_counts(0), expected_marginal_counts
)
self.assertNotEqual(result.get_counts(0), expected_marginal_counts)
def test_marginal_counts_with_dict(self):
"""Test the marginal_counts method with dictionary instead of Result object."""
dict_counts_1 = {
"0000": 4,
"0001": 7,
"0010": 10,
"0110": 5,
"1001": 11,
"1101": 9,
"1110": 8,
}
dict_counts_2 = {"10": 5, "11": 8}
expected_marginal_counts_1 = {"00": 4, "01": 27, "10": 23}
expected_marginal_counts_2 = {"0": 5, "1": 8}
self.assertEqual(marginal_counts(dict_counts_1, [0, 1]), expected_marginal_counts_1)
self.assertEqual(
marginal_counts(dict_counts_2, [0], inplace=True), expected_marginal_counts_2
)
self.assertNotEqual(dict_counts_2, expected_marginal_counts_2)
self.assertRaises(
AttributeError, lambda: marginal_counts(dict_counts_1, [0, 1]).get_counts(0)
)
def test_memory_counts_no_header(self):
"""Test that memory bitstrings are extracted properly without header."""
raw_memory = ["0x0", "0x0", "0x2", "0x2", "0x2", "0x2", "0x2"]
no_header_processed_memory = [bin(int(bs[2:], 16))[2:] for bs in raw_memory]
data = models.ExperimentResultData(memory=raw_memory)
exp_result = models.ExperimentResult(
shots=14, success=True, meas_level=2, memory=True, data=data
)
result = Result(results=[exp_result], **self.base_result_args)
self.assertEqual(result.get_memory(0), no_header_processed_memory)
def test_memory_counts_header(self):
"""Test that memory bitstrings are extracted properly with header."""
raw_memory = ["0x0", "0x0", "0x2", "0x2", "0x2", "0x2", "0x2"]
no_header_processed_memory = [
"0 0 00",
"0 0 00",
"0 0 10",
"0 0 10",
"0 0 10",
"0 0 10",
"0 0 10",
]
data = models.ExperimentResultData(memory=raw_memory)
with self.assertWarns(DeprecationWarning):
exp_result_header = QobjExperimentHeader(
creg_sizes=[["c0", 2], ["c0", 1], ["c1", 1]], memory_slots=4
)
exp_result = models.ExperimentResult(
shots=14, success=True, meas_level=2, memory=True, data=data, header=exp_result_header
)
result = Result(results=[exp_result], **self.base_result_args)
self.assertEqual(result.get_memory(0), no_header_processed_memory)
def test_meas_level_1_avg(self):
"""Test measurement level 1 average result."""
# 3 qubits
raw_memory = [[0.0, 1.0], [1.0, 0.0], [0.5, 0.5]]
processed_memory = np.array([1.0j, 1.0, 0.5 + 0.5j], dtype=np.complex128)
data = models.ExperimentResultData(memory=raw_memory)
exp_result = models.ExperimentResult(
shots=2, success=True, meas_level=1, meas_return="avg", data=data
)
result = Result(results=[exp_result], **self.base_result_args)
memory = result.get_memory(0)
self.assertEqual(memory.shape, (3,))
self.assertEqual(memory.dtype, np.complex128)
np.testing.assert_almost_equal(memory, processed_memory)
def test_meas_level_1_single(self):
"""Test measurement level 1 single result."""
# 3 qubits
raw_memory = [[[0.0, 1.0], [1.0, 0.0], [0.5, 0.5]], [[0.5, 0.5], [1.0, 0.0], [0.0, 1.0]]]
processed_memory = np.array(
[[1.0j, 1.0, 0.5 + 0.5j], [0.5 + 0.5j, 1.0, 1.0j]], dtype=np.complex128
)
data = models.ExperimentResultData(memory=raw_memory)
exp_result = models.ExperimentResult(
shots=2, success=True, meas_level=1, meas_return="single", data=data
)
result = Result(results=[exp_result], **self.base_result_args)
memory = result.get_memory(0)
self.assertEqual(memory.shape, (2, 3))
self.assertEqual(memory.dtype, np.complex128)
np.testing.assert_almost_equal(memory, processed_memory)
def test_meas_level_0_avg(self):
"""Test measurement level 0 average result."""
# 3 qubits
raw_memory = [[[0.0, 1.0], [0.0, 1.0], [0.0, 1.0]], [[1.0, 0.0], [1.0, 0.0], [1.0, 0.0]]]
processed_memory = np.array([[1.0j, 1.0j, 1.0j], [1.0, 1.0, 1.0]], dtype=np.complex128)
data = models.ExperimentResultData(memory=raw_memory)
exp_result = models.ExperimentResult(
shots=2, success=True, meas_level=0, meas_return="avg", data=data
)
result = Result(results=[exp_result], **self.base_result_args)
memory = result.get_memory(0)
self.assertEqual(memory.shape, (2, 3))
self.assertEqual(memory.dtype, np.complex128)
np.testing.assert_almost_equal(memory, processed_memory)
def test_meas_level_0_single(self):
"""Test measurement level 0 single result."""
# 3 qubits
raw_memory = [
[[[0.0, 1.0], [0.0, 1.0], [0.0, 1.0]], [[1.0, 0.0], [1.0, 0.0], [1.0, 0.0]]],
[[[0.0, 1.0], [0.0, 1.0], [0.0, 1.0]], [[1.0, 0.0], [1.0, 0.0], [1.0, 0.0]]],
]
processed_memory = np.array(
[[[1.0j, 1.0j, 1.0j], [1.0, 1.0, 1.0]], [[1.0j, 1.0j, 1.0j], [1.0, 1.0, 1.0]]],
dtype=np.complex128,
)
data = models.ExperimentResultData(memory=raw_memory)
exp_result = models.ExperimentResult(
shots=2, success=True, meas_level=0, meas_return="single", data=data
)
result = Result(results=[exp_result], **self.base_result_args)
memory = result.get_memory(0)
self.assertEqual(memory.shape, (2, 2, 3))
self.assertEqual(memory.dtype, np.complex128)
np.testing.assert_almost_equal(memory, processed_memory)
def test_circuit_statevector_repr_without_decimal(self):
"""Test postprocessing of statevector without giving any decimals arg."""
raw_statevector = np.array(
[
0.35355339 + 0.0j,
0.35355339 + 0.0j,
0.35355339 + 0.0j,
0.35355339 + 0.0j,
0.35355339 + 0.0j,
0.35355339 + 0.0j,
0.35355339 + 0.0j,
0.35355339 + 0.0j,
],
dtype=np.complex128,
)
processed_sv = np.array(
[
0.35355339 + 0.0j,
0.35355339 + 0.0j,
0.35355339 + 0.0j,
0.35355339 + 0.0j,
0.35355339 + 0.0j,
0.35355339 + 0.0j,
0.35355339 + 0.0j,
0.35355339 + 0.0j,
],
dtype=np.complex128,
)
data = models.ExperimentResultData(statevector=raw_statevector)
exp_result = models.ExperimentResult(shots=1, success=True, data=data)
result = Result(results=[exp_result], **self.base_result_args)
statevector = result.get_statevector()
self.assertEqual(statevector.shape, (8,))
self.assertEqual(statevector.dtype, np.complex128)
np.testing.assert_almost_equal(statevector, processed_sv)
def test_circuit_statevector_repr_decimal(self):
"""Test postprocessing of statevector giving decimals arg."""
raw_statevector = np.array(
[
0.35355339 + 0.0j,
0.35355339 + 0.0j,
0.35355339 + 0.0j,
0.35355339 + 0.0j,
0.35355339 + 0.0j,
0.35355339 + 0.0j,
0.35355339 + 0.0j,
0.35355339 + 0.0j,
],
dtype=np.complex128,
)
processed_sv = np.array(
[
0.354 + 0.0j,
0.354 + 0.0j,
0.354 + 0.0j,
0.354 + 0.0j,
0.354 + 0.0j,
0.354 + 0.0j,
0.354 + 0.0j,
0.354 + 0.0j,
],
dtype=np.complex128,
)
data = models.ExperimentResultData(statevector=raw_statevector)
exp_result = models.ExperimentResult(shots=1, success=True, data=data)
result = Result(results=[exp_result], **self.base_result_args)
statevector = result.get_statevector(decimals=3)
self.assertEqual(statevector.shape, (8,))
self.assertEqual(statevector.dtype, np.complex128)
np.testing.assert_almost_equal(statevector, processed_sv)
def test_circuit_unitary_repr_without_decimal(self):
"""Test postprocessing of unitary without giving any decimals arg."""
raw_unitary = np.array(
[
[0.70710678 + 0.00000000e00j, 0.70710678 - 8.65956056e-17j],
[0.70710678 + 0.00000000e00j, -0.70710678 + 8.65956056e-17j],
],
dtype=np.complex128,
)
processed_unitary = np.array(
[
[0.70710678 + 0.00000000e00j, 0.70710678 - 8.65956056e-17j],
[0.70710678 + 0.00000000e00j, -0.70710678 + 8.65956056e-17j],
],
dtype=np.complex128,
)
data = models.ExperimentResultData(unitary=raw_unitary)
exp_result = models.ExperimentResult(shots=1, success=True, data=data)
result = Result(results=[exp_result], **self.base_result_args)
unitary = result.get_unitary()
self.assertEqual(unitary.shape, (2, 2))
self.assertEqual(unitary.dtype, np.complex128)
np.testing.assert_almost_equal(unitary, processed_unitary)
def test_circuit_unitary_repr_decimal(self):
"""Test postprocessing of unitary giving decimals arg."""
raw_unitary = np.array(
[
[0.70710678 + 0.00000000e00j, 0.70710678 - 8.65956056e-17j],
[0.70710678 + 0.00000000e00j, -0.70710678 + 8.65956056e-17j],
],
dtype=np.complex128,
)
processed_unitary = np.array(
[[0.707 + 0.0j, 0.707 - 0.0j], [0.707 + 0.0j, -0.707 + 0.0j]], dtype=np.complex128
)
data = models.ExperimentResultData(unitary=raw_unitary)
exp_result = models.ExperimentResult(shots=1, success=True, data=data)
result = Result(results=[exp_result], **self.base_result_args)
unitary = result.get_unitary(decimals=3)
self.assertEqual(unitary.shape, (2, 2))
self.assertEqual(unitary.dtype, np.complex128)
np.testing.assert_almost_equal(unitary, processed_unitary)
def test_additional_result_data(self):
"""Test construction of ExperimentResult with additional data"""
target_probs = {"0x0": 0.5, "0x1": 0.5}
data = models.ExperimentResultData(probabilities=target_probs)
exp_result = models.ExperimentResult(shots=1, success=True, data=data)
result = Result(results=[exp_result], **self.base_result_args)
result_probs = result.data(0)["probabilities"]
self.assertEqual(result_probs, target_probs)
class TestResultOperationsFailed(QiskitTestCase):
"""Result operations methods."""
def setUp(self):
self.base_result_args = {
"backend_name": "test_backend",
"backend_version": "1.0.0",
"qobj_id": "id-123",
"job_id": "job-123",
"success": True,
}
super().setUp()
def test_counts_int_out(self):
"""Test that fails when get_count is called with a nonexistent int."""
raw_counts = {"0x0": 4, "0x2": 10}
data = models.ExperimentResultData(counts=raw_counts)
exp_result = models.ExperimentResult(shots=14, success=True, meas_level=2, data=data)
result = Result(results=[exp_result], **self.base_result_args)
with self.assertRaises(Exception) as context:
result.get_counts(99)
self.assertEqual(
'Result for experiment "99" could not be found.', context.exception.message
)
def test_counts_name_out(self):
"""Test that fails when get_count is called with a nonexistent name."""
raw_counts = {"0x0": 4, "0x2": 10}
data = models.ExperimentResultData(counts=raw_counts)
with self.assertWarns(DeprecationWarning):
exp_result_header = QobjExperimentHeader(
creg_sizes=[["c0", 2], ["c0", 1], ["c1", 1]], memory_slots=4, name="a_name"
)
exp_result = models.ExperimentResult(
shots=14, success=True, meas_level=2, data=data, header=exp_result_header
)
result = Result(results=[exp_result], **self.base_result_args)
with self.assertRaises(Exception) as context:
result.get_counts("another_name")
self.assertEqual(
'Data for experiment "another_name" could not be found.', context.exception.message
)
def test_memory_int_out(self):
"""Test that memory bitstrings are extracted properly without header."""
raw_memory = ["0x0", "0x0", "0x2", "0x2", "0x2", "0x2", "0x2"]
data = models.ExperimentResultData(memory=raw_memory)
exp_result = models.ExperimentResult(
shots=14, success=True, meas_level=2, memory=True, data=data
)
result = Result(results=[exp_result], **self.base_result_args)
with self.assertRaises(Exception) as context:
result.get_memory(99)
self.assertEqual(
'Result for experiment "99" could not be found.', context.exception.message
)
def test_marginal_counts_no_cregs(self):
"""Test that marginal_counts without cregs See qiskit-terra/6430."""
raw_counts_1 = {"0x0": 4, "0x1": 7, "0x2": 10, "0x6": 5, "0x9": 11, "0xD": 9, "0x12": 8}
data_1 = models.ExperimentResultData(counts=raw_counts_1)
with self.assertWarns(DeprecationWarning):
exp_result_header_1 = QobjExperimentHeader(memory_slots=5)
exp_result_1 = models.ExperimentResult(
shots=54, success=True, data=data_1, header=exp_result_header_1
)
result = Result(results=[exp_result_1], **self.base_result_args)
with self.assertWarns(DeprecationWarning):
_ = marginal_counts(result, indices=[0])
marginal_counts_result = marginal_counts(result, indices=[0])
self.assertEqual(marginal_counts_result.get_counts(), {"0": 27, "1": 27})
| qiskit/test/python/result/test_result.py/0 | {
"file_path": "qiskit/test/python/result/test_result.py",
"repo_id": "qiskit",
"token_count": 16729
} | 325 |
# 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 analytical gradient vs the one computed via finite differences.
"""
import unittest
import numpy as np
from qiskit.synthesis.unitary.aqc.cnot_structures import make_cnot_network
from qiskit.synthesis.unitary.aqc.cnot_unit_objective import DefaultCNOTUnitObjective
from test import QiskitTestCase # pylint: disable=wrong-import-order
from test.python.synthesis.aqc.sample_data import ( # pylint: disable=wrong-import-order
ORIGINAL_CIRCUIT,
INITIAL_THETAS,
)
class TestGradientAgainstFiniteDiff(QiskitTestCase):
"""
Compares analytical gradient vs the one computed via finite difference
approximation. Also, the test demonstrates that the difference between
analytical and numerical gradients is up to quadratic term in Taylor
expansion for small deltas.
"""
def setUp(self):
super().setUp()
np.random.seed(0x0696969)
def test_gradient(self):
"""
Gradient test for specified number of qubits and circuit depth.
"""
num_qubits = 3
num_cnots = 14
cnots = make_cnot_network(
num_qubits=num_qubits, network_layout="spin", connectivity_type="full", depth=num_cnots
)
# we pick a target matrix from the existing sample data
target_matrix = ORIGINAL_CIRCUIT
objective = DefaultCNOTUnitObjective(num_qubits, cnots)
objective.target_matrix = target_matrix
# thetas = np.random.rand(objective.num_thetas) * (2.0 * np.pi)
thetas = INITIAL_THETAS
fobj0 = objective.objective(thetas)
grad0 = objective.gradient(thetas)
grad0_dir = grad0 / np.linalg.norm(grad0)
numerical_grad = np.zeros(thetas.size)
thetas_delta = np.zeros(thetas.size)
# Every angle has a magnitude between 0 and 2*pi. We choose the
# angle increment (tau) about the same order of magnitude, tau <= 1,
# and then gradually decrease it towards zero.
tau = 1.0
diff_prev = 0.0
orders = []
errors = []
steps = 9
for step in range(steps):
# Estimate gradient approximation error.
for i in range(thetas.size):
np.copyto(thetas_delta, thetas)
thetas_delta[i] -= tau
fobj1 = objective.objective(thetas_delta)
np.copyto(thetas_delta, thetas)
thetas_delta[i] += tau
fobj2 = objective.objective(thetas_delta)
numerical_grad[i] = (fobj2 - fobj1) / (2.0 * tau)
errors.append(np.linalg.norm(grad0 - numerical_grad) / np.linalg.norm(grad0))
# Estimate approximation order (should be quadratic for small tau).
# Note, we take perturbation in gradient direction. More rigorous
# approach would take a random direction, although quadratic
# convergence is less pronounced in this case.
perturbation = grad0_dir * tau
# circuit.set_thetas(thetas + perturbation)
fobj = objective.objective(thetas + perturbation)
diff = abs(fobj - fobj0 - np.dot(grad0, perturbation))
orders.append(
0.0 if step == 0 else float((np.log(diff_prev) - np.log(diff)) / np.log(2.0))
)
tau /= 2.0
diff_prev = diff
# check errors
prev_error = errors[0]
for error in errors[1:]:
self.assertLess(error, prev_error * 0.75)
prev_error = error
# check orders, skipping first zero
self.assertTrue(np.count_nonzero(np.asarray(orders[1:]) > 1.8) >= 3)
self.assertTrue(np.count_nonzero(np.asarray(orders[1:]) < 3.0) >= 3)
if __name__ == "__main__":
unittest.main()
| qiskit/test/python/synthesis/aqc/test_gradient.py/0 | {
"file_path": "qiskit/test/python/synthesis/aqc/test_gradient.py",
"repo_id": "qiskit",
"token_count": 1812
} | 326 |
# 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.
"""
Tests for synthesis/xx_decompose/qiskit.py .
"""
from statistics import mean
import unittest
import ddt
import numpy as np
from scipy.stats import unitary_group
import qiskit
from qiskit.circuit.quantumcircuit import QuantumCircuit
from qiskit.quantum_info.operators import Operator
from qiskit.synthesis.two_qubit.xx_decompose.decomposer import (
XXDecomposer,
TwoQubitWeylDecomposition,
)
from .utilities import canonical_matrix
EPSILON = 1e-8
@ddt.ddt
class TestXXDecomposer(unittest.TestCase):
"""Tests for decomposition of two-qubit unitaries over discrete gates from XX family."""
decomposer = XXDecomposer(euler_basis="PSX")
def __init__(self, *args, seed=42, **kwargs):
super().__init__(*args, **kwargs)
self._random_state = np.random.Generator(np.random.PCG64(seed))
def test_random_compilation(self):
"""Test that compilation gives correct results."""
for _ in range(100):
unitary = unitary_group.rvs(4, random_state=self._random_state)
unitary /= np.linalg.det(unitary) ** (1 / 4)
# decompose into CX, CX/2, and CX/3
circuit = self.decomposer(unitary, approximate=False)
decomposed_unitary = Operator(circuit).data
self.assertTrue(np.all(unitary - decomposed_unitary < EPSILON))
def test_compilation_determinism(self):
"""Test that compilation is stable under multiple calls."""
for _ in range(10):
unitary = unitary_group.rvs(4, random_state=self._random_state)
unitary /= np.linalg.det(unitary) ** (1 / 4)
# decompose into CX, CX/2, and CX/3
circuit1 = self.decomposer(unitary, approximate=False)
circuit2 = self.decomposer(unitary, approximate=False)
self.assertEqual(circuit1, circuit2)
@ddt.data(np.pi / 3, np.pi / 5, np.pi / 2)
def test_default_embodiment(self, angle):
"""Test that _default_embodiment actually does yield XX gates."""
embodiment = self.decomposer._default_embodiment(angle)
embodiment_matrix = Operator(embodiment).data
self.assertTrue(np.all(canonical_matrix(angle, 0, 0) - embodiment_matrix < EPSILON))
def test_check_embodiment(self):
"""Test that XXDecomposer._check_embodiments correctly diagnoses il/legal embodiments."""
# build the member of the XX family corresponding to a single CX
good_angle = np.pi / 2
good_embodiment = qiskit.QuantumCircuit(2)
good_embodiment.h(0)
good_embodiment.cx(0, 1)
good_embodiment.h(1)
good_embodiment.rz(np.pi / 2, 0)
good_embodiment.rz(np.pi / 2, 1)
good_embodiment.h(1)
good_embodiment.h(0)
good_embodiment.global_phase += np.pi / 4
# mismatch two members of the XX family
bad_angle = np.pi / 10
bad_embodiment = qiskit.QuantumCircuit(2)
# "self.assertDoesNotRaise"
XXDecomposer(embodiments={good_angle: good_embodiment})
self.assertRaises(
qiskit.exceptions.QiskitError, XXDecomposer, embodiments={bad_angle: bad_embodiment}
)
def test_compilation_improvement(self):
"""Test that compilation to CX, CX/2, CX/3 improves over CX alone."""
slope, offset = (64 * 90) / 1000000, 909 / 1000000 + 1 / 1000
strength_table = self.decomposer._strength_to_infidelity(
basis_fidelity={
strength: 1 - (slope * strength / (np.pi / 2) + offset)
for strength in [np.pi / 2, np.pi / 4, np.pi / 6]
},
approximate=True,
)
limited_strength_table = {np.pi / 2: strength_table[np.pi / 2]}
clever_costs = []
naive_costs = []
for _ in range(200):
unitary = unitary_group.rvs(4, random_state=self._random_state)
unitary /= np.linalg.det(unitary) ** (1 / 4)
weyl_decomposition = TwoQubitWeylDecomposition(unitary)
target = [getattr(weyl_decomposition, x) for x in ("a", "b", "c")]
if target[-1] < -EPSILON:
target = [np.pi / 2 - target[0], target[1], -target[2]]
# decompose into CX, CX/2, and CX/3
clever_costs.append(self.decomposer._best_decomposition(target, strength_table)["cost"])
naive_costs.append(
self.decomposer._best_decomposition(target, limited_strength_table)["cost"]
)
# the following are taken from Fig 14 of the XX synthesis paper
self.assertAlmostEqual(mean(clever_costs), 1.445e-2, delta=5e-3)
self.assertAlmostEqual(mean(naive_costs), 2.058e-2, delta=5e-3)
def test_error_on_empty_basis_fidelity(self):
"""Test synthesizing entangling gate with no entangling basis fails."""
decomposer = XXDecomposer(basis_fidelity={})
qc = QuantumCircuit(2)
qc.cx(0, 1)
mat = Operator(qc).to_matrix()
with self.assertRaisesRegex(
qiskit.exceptions.QiskitError,
"Attempting to synthesize entangling gate with no controlled gates in basis set.",
):
decomposer(mat)
def test_no_error_on_empty_basis_fidelity_trivial_target(self):
"""Test synthesizing non-entangling gate with no entangling basis succeeds."""
decomposer = XXDecomposer(basis_fidelity={})
qc = QuantumCircuit(2)
qc.x(0)
qc.y(1)
mat = Operator(qc).to_matrix()
dqc = decomposer(mat)
self.assertTrue(np.allclose(mat, Operator(dqc).to_matrix()))
| qiskit/test/python/synthesis/xx_decompose/test_decomposer.py/0 | {
"file_path": "qiskit/test/python/synthesis/xx_decompose/test_decomposer.py",
"repo_id": "qiskit",
"token_count": 2662
} | 327 |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the BasicSwap pass"""
import unittest
from qiskit.transpiler.passes import BasicSwap
from qiskit.transpiler.passmanager import PassManager
from qiskit.transpiler.layout import Layout
from qiskit.transpiler import CouplingMap, Target
from qiskit.circuit.library import CXGate
from qiskit.converters import circuit_to_dag
from qiskit import QuantumRegister, QuantumCircuit
from test import QiskitTestCase # pylint: disable=wrong-import-order
class TestBasicSwap(QiskitTestCase):
"""Tests the BasicSwap pass."""
def test_trivial_case(self):
"""No need to have any swap, the CX are distance 1 to each other
q0:--(+)-[U]-(+)-
| |
q1:---.-------|--
|
q2:-----------.--
CouplingMap map: [1]--[0]--[2]
"""
coupling = CouplingMap([[0, 1], [0, 2]])
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.h(qr[0])
circuit.cx(qr[0], qr[2])
dag = circuit_to_dag(circuit)
pass_ = BasicSwap(coupling)
after = pass_.run(dag)
self.assertEqual(dag, after)
def test_trivial_in_same_layer(self):
"""No need to have any swap, two CXs distance 1 to each other, in the same layer
q0:--(+)--
|
q1:---.---
q2:--(+)--
|
q3:---.---
CouplingMap map: [0]--[1]--[2]--[3]
"""
coupling = CouplingMap([[0, 1], [1, 2], [2, 3]])
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[2], qr[3])
circuit.cx(qr[0], qr[1])
dag = circuit_to_dag(circuit)
pass_ = BasicSwap(coupling)
after = pass_.run(dag)
self.assertEqual(dag, after)
def test_a_single_swap(self):
"""Adding a swap
q0:-------
q1:--(+)--
|
q2:---.---
CouplingMap map: [1]--[0]--[2]
q0:--X---.---
| |
q1:--X---|---
|
q2:-----(+)--
"""
coupling = CouplingMap([[0, 1], [0, 2]])
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[1], qr[2])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr)
expected.swap(qr[1], qr[0])
expected.cx(qr[0], qr[2])
pass_ = BasicSwap(coupling)
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_a_single_swap_with_target(self):
"""Adding a swap
q0:-------
q1:--(+)--
|
q2:---.---
CouplingMap map: [1]--[0]--[2]
q0:--X---.---
| |
q1:--X---|---
|
q2:-----(+)--
"""
target = Target()
target.add_instruction(CXGate(), {(0, 1): None, (0, 2): None})
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[1], qr[2])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr)
expected.swap(qr[1], qr[0])
expected.cx(qr[0], qr[2])
pass_ = BasicSwap(target)
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_a_single_swap_bigger_cm(self):
"""Swapper in a bigger coupling map
q0:-------
q1:---.---
|
q2:--(+)--
CouplingMap map: [1]--[0]--[2]--[3]
q0:--X---.---
| |
q1:--X---|---
|
q2:-----(+)--
"""
coupling = CouplingMap([[0, 1], [0, 2], [2, 3]])
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[1], qr[2])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr)
expected.swap(qr[1], qr[0])
expected.cx(qr[0], qr[2])
pass_ = BasicSwap(coupling)
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_keep_layout(self):
"""After a swap, the following gates also change the wires.
qr0:---.---[H]--
|
qr1:---|--------
|
qr2:--(+)-------
CouplingMap map: [0]--[1]--[2]
qr0:--X-----------
|
qr1:--X---.--[H]--
|
qr2:-----(+)------
"""
coupling = CouplingMap([[1, 0], [1, 2]])
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[2])
circuit.h(qr[0])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr)
expected.swap(qr[0], qr[1])
expected.cx(qr[1], qr[2])
expected.h(qr[1])
pass_ = BasicSwap(coupling)
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_far_swap(self):
"""A far swap that affects coming CXs.
qr0:--(+)---.--
| |
qr1:---|----|--
| |
qr2:---|----|--
| |
qr3:---.---(+)-
CouplingMap map: [0]--[1]--[2]--[3]
qr0:--X--------------
|
qr1:--X--X-----------
|
qr2:-----X--(+)---.--
| |
qr3:---------.---(+)-
"""
coupling = CouplingMap([[0, 1], [1, 2], [2, 3]])
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[3])
circuit.cx(qr[3], qr[0])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr)
expected.swap(qr[0], qr[1])
expected.swap(qr[1], qr[2])
expected.cx(qr[2], qr[3])
expected.cx(qr[3], qr[2])
pass_ = BasicSwap(coupling)
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_far_swap_with_gate_the_front(self):
"""A far swap with a gate in the front.
q0:------(+)--
|
q1:-------|---
|
q2:-------|---
|
q3:--[H]--.---
CouplingMap map: [0]--[1]--[2]--[3]
q0:-----------(+)--
|
q1:---------X--.---
|
q2:------X--X------
|
q3:-[H]--X---------
"""
coupling = CouplingMap([[0, 1], [1, 2], [2, 3]])
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
circuit.h(qr[3])
circuit.cx(qr[3], qr[0])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr)
expected.h(qr[3])
expected.swap(qr[3], qr[2])
expected.swap(qr[2], qr[1])
expected.cx(qr[1], qr[0])
pass_ = BasicSwap(coupling)
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_far_swap_with_gate_the_back(self):
"""A far swap with a gate in the back.
q0:--(+)------
|
q1:---|-------
|
q2:---|-------
|
q3:---.--[H]--
CouplingMap map: [0]--[1]--[2]--[3]
q0:-------(+)------
|
q1:-----X--.--[H]--
|
q2:--X--X----------
|
q3:--X-------------
"""
coupling = CouplingMap([[0, 1], [1, 2], [2, 3]])
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[3], qr[0])
circuit.h(qr[3])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr)
expected.swap(qr[3], qr[2])
expected.swap(qr[2], qr[1])
expected.cx(qr[1], qr[0])
expected.h(qr[1])
pass_ = BasicSwap(coupling)
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_far_swap_with_gate_the_middle(self):
"""A far swap with a gate in the middle.
q0:--(+)-------.--
| |
q1:---|--------|--
|
q2:---|--------|--
| |
q3:---.--[H]--(+)-
CouplingMap map: [0]--[1]--[2]--[3]
q0:-------(+)-------.---
| |
q1:-----X--.--[H]--(+)--
|
q2:--X--X---------------
|
q3:--X------------------
"""
coupling = CouplingMap([[0, 1], [1, 2], [2, 3]])
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[3], qr[0])
circuit.h(qr[3])
circuit.cx(qr[0], qr[3])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr)
expected.swap(qr[3], qr[2])
expected.swap(qr[2], qr[1])
expected.cx(qr[1], qr[0])
expected.h(qr[1])
expected.cx(qr[0], qr[1])
pass_ = BasicSwap(coupling)
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_fake_run(self):
"""A fake run, doesn't change dag
q0:--(+)-------.--
| |
q1:---|--------|--
|
q2:---|--------|--
| |
q3:---.--[H]--(+)-
CouplingMap map: [0]--[1]--[2]--[3]
q0:-------(+)-------.---
| |
q1:-----X--.--[H]--(+)--
|
q2:--X--X---------------
|
q3:--X------------------
"""
coupling = CouplingMap([[0, 1], [1, 2], [2, 3]])
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[3], qr[0])
circuit.h(qr[3])
circuit.cx(qr[0], qr[3])
fake_pm = PassManager([BasicSwap(coupling, fake_run=True)])
real_pm = PassManager([BasicSwap(coupling, fake_run=False)])
self.assertEqual(circuit, fake_pm.run(circuit))
self.assertNotEqual(circuit, real_pm.run(circuit))
self.assertIsInstance(fake_pm.property_set["final_layout"], Layout)
self.assertEqual(fake_pm.property_set["final_layout"], real_pm.property_set["final_layout"])
if __name__ == "__main__":
unittest.main()
| qiskit/test/python/transpiler/test_basic_swap.py/0 | {
"file_path": "qiskit/test/python/transpiler/test_basic_swap.py",
"repo_id": "qiskit",
"token_count": 6009
} | 328 |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 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.
# pylint: disable=missing-docstring
import unittest
import numpy as np
import rustworkx as rx
from qiskit.transpiler import CouplingMap
from qiskit.transpiler.exceptions import CouplingError
from qiskit.utils import optionals
from test import QiskitTestCase # pylint: disable=wrong-import-order
from ..visualization.visualization import QiskitVisualizationTestCase, path_to_diagram_reference
from ..legacy_cmaps import RUESCHLIKON_CMAP
class CouplingTest(QiskitTestCase):
def test_empty_coupling_class(self):
coupling = CouplingMap()
self.assertEqual(0, coupling.size())
self.assertEqual([], coupling.physical_qubits)
self.assertEqual([], coupling.get_edges())
self.assertFalse(coupling.is_connected())
self.assertEqual("", str(coupling))
def test_coupling_str(self):
coupling_list = [[0, 1], [0, 2], [1, 2]]
coupling = CouplingMap(coupling_list)
expected = "[[0, 1], [0, 2], [1, 2]]"
self.assertEqual(expected, str(coupling))
def test_coupling_distance(self):
coupling_list = [(0, 1), (0, 2), (1, 2)]
coupling = CouplingMap(coupling_list)
self.assertTrue(coupling.is_connected())
physical_qubits = coupling.physical_qubits
result = coupling.distance(physical_qubits[0], physical_qubits[1])
self.assertIsInstance(result, int)
self.assertEqual(1, result)
def test_add_physical_qubits(self):
coupling = CouplingMap()
self.assertEqual("", str(coupling))
coupling.add_physical_qubit(0)
self.assertEqual([0], coupling.physical_qubits)
self.assertEqual("", str(coupling))
def test_add_physical_qubits_not_int(self):
coupling = CouplingMap()
self.assertRaises(CouplingError, coupling.add_physical_qubit, "q")
def test_add_edge(self):
coupling = CouplingMap()
self.assertEqual("", str(coupling))
coupling.add_edge(0, 1)
expected = "[[0, 1]]"
self.assertEqual(expected, str(coupling))
def test_neighbors(self):
"""Test neighboring qubits are found correctly."""
coupling = CouplingMap([[0, 1], [0, 2], [1, 0]])
physical_qubits = coupling.physical_qubits
self.assertEqual(set(coupling.neighbors(physical_qubits[0])), {1, 2})
self.assertEqual(set(coupling.neighbors(physical_qubits[1])), {0})
self.assertEqual(set(coupling.neighbors(physical_qubits[2])), set())
def test_distance_error(self):
"""Test distance between unconnected physical_qubits."""
graph = CouplingMap()
graph.add_physical_qubit(0)
graph.add_physical_qubit(1)
self.assertRaises(CouplingError, graph.distance, 0, 1)
def test_distance_self_loop(self):
"""Test distance between the same physical qubit."""
graph = CouplingMap()
graph.add_physical_qubit(0)
graph.add_physical_qubit(1)
self.assertEqual(0.0, graph.distance(0, 0))
def test_init_with_couplinglist(self):
coupling_list = [[0, 1], [1, 2]]
coupling = CouplingMap(coupling_list)
qubits_expected = [0, 1, 2]
edges_expected = [(0, 1), (1, 2)]
self.assertEqual(coupling.physical_qubits, qubits_expected)
self.assertEqual(coupling.get_edges(), edges_expected)
self.assertEqual(2, coupling.distance(0, 2))
def test_successful_reduced_map(self):
"""Generate a reduced map"""
cmap = RUESCHLIKON_CMAP
coupling_map = CouplingMap(cmap)
out = coupling_map.reduce([12, 11, 10, 9]).get_edges()
ans = [(1, 2), (3, 2), (0, 1)]
self.assertEqual(set(out), set(ans))
def test_bad_reduced_map(self):
"""Generate disconnected reduced map"""
cmap = RUESCHLIKON_CMAP
coupling_map = CouplingMap(cmap)
with self.assertRaises(CouplingError):
coupling_map.reduce([12, 11, 10, 3])
def test_disconnected_reduced_map_allowed(self):
"""Generate disconnected reduced map but do not error"""
cmap = RUESCHLIKON_CMAP
coupling_map = CouplingMap(cmap)
reduced_map = coupling_map.reduce([12, 11, 10, 3], check_if_connected=False)
reduced_edges = reduced_map.get_edges()
qubits_expected = [0, 1, 2, 3]
edges_expected = [(0, 1), (1, 2)]
self.assertEqual(qubits_expected, reduced_map.physical_qubits)
self.assertEqual(set(reduced_edges), set(edges_expected))
def test_symmetric_small_true(self):
coupling_list = [[0, 1], [1, 0]]
coupling = CouplingMap(coupling_list)
self.assertTrue(coupling.is_symmetric)
def test_symmetric_big_false(self):
coupling_list = [
[1, 0],
[1, 2],
[2, 3],
[4, 3],
[4, 10],
[5, 4],
[5, 6],
[5, 9],
[6, 8],
[9, 8],
[9, 10],
[7, 8],
[11, 3],
[11, 10],
[11, 12],
[12, 2],
[13, 1],
[13, 12],
]
coupling = CouplingMap(coupling_list)
self.assertFalse(coupling.is_symmetric)
def test_make_symmetric(self):
coupling_list = [[0, 1], [0, 2]]
coupling = CouplingMap(coupling_list)
coupling.make_symmetric()
edges = coupling.get_edges()
self.assertEqual(set(edges), {(0, 1), (0, 2), (2, 0), (1, 0)})
def test_full_factory(self):
coupling = CouplingMap.from_full(4)
edges = coupling.get_edges()
expected = [
(0, 1),
(0, 2),
(0, 3),
(1, 0),
(1, 2),
(1, 3),
(2, 0),
(2, 1),
(2, 3),
(3, 0),
(3, 1),
(3, 2),
]
self.assertEqual(set(edges), set(expected))
def test_line_factory(self):
coupling = CouplingMap.from_line(4)
edges = coupling.get_edges()
expected = [(0, 1), (1, 0), (1, 2), (2, 1), (2, 3), (3, 2)]
self.assertEqual(set(edges), set(expected))
def test_grid_factory(self):
coupling = CouplingMap.from_grid(2, 3)
edges = coupling.get_edges()
expected = [
(0, 3),
(0, 1),
(3, 0),
(3, 4),
(1, 0),
(1, 4),
(1, 2),
(4, 1),
(4, 3),
(4, 5),
(2, 1),
(2, 5),
(5, 2),
(5, 4),
]
self.assertEqual(set(edges), set(expected))
def test_grid_factory_unidirectional(self):
coupling = CouplingMap.from_grid(2, 3, bidirectional=False)
edges = coupling.get_edges()
expected = [(0, 3), (0, 1), (3, 4), (1, 4), (1, 2), (4, 5), (2, 5)]
self.assertEqual(set(edges), set(expected))
def test_heavy_hex_factory(self):
coupling = CouplingMap.from_heavy_hex(3, bidirectional=False)
edges = coupling.get_edges()
expected = [
(0, 9),
(0, 13),
(1, 13),
(1, 14),
(2, 14),
(3, 9),
(3, 15),
(4, 15),
(4, 16),
(5, 12),
(5, 16),
(6, 17),
(7, 17),
(7, 18),
(8, 12),
(8, 18),
(10, 14),
(10, 16),
(11, 15),
(11, 17),
]
self.assertEqual(set(edges), set(expected))
def test_heavy_hex_factory_bidirectional(self):
coupling = CouplingMap.from_heavy_hex(3, bidirectional=True)
edges = coupling.get_edges()
expected = [
(0, 9),
(0, 13),
(1, 13),
(1, 14),
(2, 14),
(3, 9),
(3, 15),
(4, 15),
(4, 16),
(5, 12),
(5, 16),
(6, 17),
(7, 17),
(7, 18),
(8, 12),
(8, 18),
(9, 0),
(9, 3),
(10, 14),
(10, 16),
(11, 15),
(11, 17),
(12, 5),
(12, 8),
(13, 0),
(13, 1),
(14, 1),
(14, 2),
(14, 10),
(15, 3),
(15, 4),
(15, 11),
(16, 4),
(16, 5),
(16, 10),
(17, 6),
(17, 7),
(17, 11),
(18, 7),
(18, 8),
]
self.assertEqual(set(edges), set(expected))
def test_heavy_square_factory(self):
coupling = CouplingMap.from_heavy_square(3, bidirectional=False)
edges = coupling.get_edges()
expected = [
(0, 15),
(1, 16),
(2, 11),
(3, 12),
(3, 17),
(4, 18),
(5, 11),
(6, 12),
(6, 19),
(7, 20),
(9, 15),
(9, 17),
(10, 16),
(10, 18),
(13, 17),
(13, 19),
(14, 18),
(14, 20),
(15, 1),
(16, 2),
(17, 4),
(18, 5),
(19, 7),
(20, 8),
]
self.assertEqual(set(edges), set(expected))
def test_heavy_square_factory_bidirectional(self):
coupling = CouplingMap.from_heavy_square(3, bidirectional=True)
edges = coupling.get_edges()
expected = [
(0, 15),
(1, 15),
(1, 16),
(2, 11),
(2, 16),
(3, 12),
(3, 17),
(4, 17),
(4, 18),
(5, 11),
(5, 18),
(6, 12),
(6, 19),
(7, 19),
(7, 20),
(8, 20),
(9, 15),
(9, 17),
(10, 16),
(10, 18),
(11, 2),
(11, 5),
(12, 3),
(12, 6),
(13, 17),
(13, 19),
(14, 18),
(14, 20),
(15, 0),
(15, 1),
(15, 9),
(16, 1),
(16, 2),
(16, 10),
(17, 3),
(17, 4),
(17, 9),
(17, 13),
(18, 4),
(18, 5),
(18, 10),
(18, 14),
(19, 6),
(19, 7),
(19, 13),
(20, 7),
(20, 8),
(20, 14),
]
self.assertEqual(set(edges), set(expected))
def test_hexagonal_lattice_2_2_factory(self):
coupling = CouplingMap.from_hexagonal_lattice(2, 2, bidirectional=False)
edges = coupling.get_edges()
expected = [
(0, 1),
(1, 2),
(2, 3),
(3, 4),
(5, 6),
(6, 7),
(7, 8),
(8, 9),
(9, 10),
(11, 12),
(12, 13),
(13, 14),
(14, 15),
(0, 5),
(2, 7),
(4, 9),
(6, 11),
(8, 13),
(10, 15),
]
self.assertEqual(set(edges), set(expected))
def test_hexagonal_lattice_2_2_factory_bidirectional(self):
coupling = CouplingMap.from_hexagonal_lattice(2, 2, bidirectional=True)
edges = coupling.get_edges()
expected = [
(0, 1),
(1, 0),
(1, 2),
(2, 1),
(2, 3),
(3, 2),
(3, 4),
(4, 3),
(5, 6),
(6, 5),
(6, 7),
(7, 6),
(7, 8),
(8, 7),
(8, 9),
(9, 8),
(9, 10),
(10, 9),
(11, 12),
(12, 11),
(12, 13),
(13, 12),
(13, 14),
(14, 13),
(14, 15),
(15, 14),
(0, 5),
(5, 0),
(2, 7),
(7, 2),
(4, 9),
(9, 4),
(6, 11),
(11, 6),
(8, 13),
(13, 8),
(10, 15),
(15, 10),
]
self.assertEqual(set(edges), set(expected))
def test_implements_iter(self):
"""Test that the object is implicitly iterable."""
coupling = CouplingMap.from_line(3)
expected = [(0, 1), (1, 0), (1, 2), (2, 1)]
self.assertEqual(sorted(coupling), expected)
def test_disjoint_coupling_map(self):
cmap = CouplingMap([[0, 1], [1, 0], [2, 3], [3, 2]])
self.assertFalse(cmap.is_connected())
distance_matrix = cmap.distance_matrix
expected = np.array(
[
[0, 1, np.inf, np.inf],
[1, 0, np.inf, np.inf],
[np.inf, np.inf, 0, 1],
[np.inf, np.inf, 1, 0],
]
)
np.testing.assert_array_equal(expected, distance_matrix)
def test_disjoint_coupling_map_distance_no_path_qubits(self):
cmap = CouplingMap([[0, 1], [1, 0], [2, 3], [3, 2]])
self.assertFalse(cmap.is_connected())
with self.assertRaises(CouplingError):
cmap.distance(0, 3)
def test_component_mapping(self):
cmap = CouplingMap([[0, 1], [1, 0], [2, 3], [3, 2]])
components = cmap.connected_components()
self.assertEqual(components[1].graph[0], 2)
self.assertEqual(components[1].graph[1], 3)
self.assertEqual(components[0].graph[0], 0)
self.assertEqual(components[0].graph[1], 1)
def test_components_connected_graph(self):
cmap = CouplingMap.from_line(5)
self.assertTrue(cmap.is_connected())
subgraphs = cmap.connected_components()
self.assertEqual(len(subgraphs), 1)
self.assertTrue(rx.is_isomorphic(cmap.graph, subgraphs[0].graph))
def test_components_disconnected_graph(self):
cmap = CouplingMap([[0, 1], [1, 2], [3, 4], [4, 5]])
self.assertFalse(cmap.is_connected())
subgraphs = cmap.connected_components()
self.assertEqual(len(subgraphs), 2)
expected_subgraph = CouplingMap([[0, 1], [1, 2]])
self.assertTrue(rx.is_isomorphic(expected_subgraph.graph, subgraphs[0].graph))
self.assertTrue(rx.is_isomorphic(expected_subgraph.graph, subgraphs[1].graph))
def test_equality(self):
"""Test that equality checks that the graphs have the same nodes, node labels, and edges."""
# two coupling maps with 4 nodes and the same edges
coupling0 = CouplingMap([(0, 1), (0, 2), (2, 3)])
coupling1 = CouplingMap([(0, 1), (0, 2), (2, 3)])
self.assertEqual(coupling0, coupling1)
# coupling map with 5 nodes not equal to the previous 2
coupling2 = CouplingMap([(0, 1), (0, 2), (2, 4)])
self.assertNotEqual(coupling0, coupling2)
# coupling map isomorphic to coupling0, but with cyclically shifted labels
coupling3 = CouplingMap([(1, 2), (1, 3), (3, 0)])
self.assertNotEqual(coupling0, coupling3)
# additional test for comparison to a non-CouplingMap object
self.assertNotEqual(coupling0, 1)
class CouplingVisualizationTest(QiskitVisualizationTestCase):
@unittest.skipUnless(optionals.HAS_GRAPHVIZ, "Graphviz not installed")
@unittest.skipUnless(optionals.HAS_PIL, "Pillow not installed")
def test_coupling_draw(self):
"""Test that the coupling map drawing with respect to the reference file is correct."""
cmap = CouplingMap([[0, 1], [1, 2], [2, 3], [2, 4], [2, 5], [2, 6]])
image_ref = path_to_diagram_reference("coupling_map.png")
image = cmap.draw()
self.assertImagesAreEqual(image, image_ref, diff_tolerance=0.01)
| qiskit/test/python/transpiler/test_coupling.py/0 | {
"file_path": "qiskit/test/python/transpiler/test_coupling.py",
"repo_id": "qiskit",
"token_count": 9026
} | 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.
"""Test the CX Direction pass"""
import unittest
from math import pi
import ddt
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit, pulse
from qiskit.circuit import Parameter, Gate
from qiskit.circuit.library import (
CXGate,
CZGate,
ECRGate,
RXXGate,
RYYGate,
RZXGate,
RZZGate,
SwapGate,
)
from qiskit.compiler import transpile
from qiskit.transpiler import TranspilerError, CouplingMap, Target
from qiskit.transpiler.passes import GateDirection
from qiskit.converters import circuit_to_dag
from test import QiskitTestCase # pylint: disable=wrong-import-order
@ddt.ddt
class TestGateDirection(QiskitTestCase):
"""Tests the GateDirection pass."""
def test_no_cnots(self):
"""Trivial map in a circuit without entanglement
qr0:---[H]---
qr1:---[H]---
qr2:---[H]---
CouplingMap map: None
"""
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.h(qr)
coupling = CouplingMap()
dag = circuit_to_dag(circuit)
pass_ = GateDirection(coupling)
after = pass_.run(dag)
self.assertEqual(dag, after)
def test_direction_error(self):
"""The mapping cannot be fixed by direction mapper
qr0:---------
qr1:---(+)---
|
qr2:----.----
CouplingMap map: [2] <- [0] -> [1]
"""
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[1], qr[2])
coupling = CouplingMap([[0, 1], [0, 2]])
dag = circuit_to_dag(circuit)
pass_ = GateDirection(coupling)
with self.assertRaises(TranspilerError):
pass_.run(dag)
def test_direction_correct(self):
"""The CX is in the right direction
qr0:---(+)---
|
qr1:----.----
CouplingMap map: [0] -> [1]
"""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
coupling = CouplingMap([[0, 1]])
dag = circuit_to_dag(circuit)
pass_ = GateDirection(coupling)
after = pass_.run(dag)
self.assertEqual(dag, after)
def test_multi_register(self):
"""The CX is in the right direction
qr0:---(+)---
|
qr1:----.----
CouplingMap map: [0] -> [1]
"""
qr1 = QuantumRegister(1, "qr1")
qr2 = QuantumRegister(1, "qr2")
circuit = QuantumCircuit(qr1, qr2)
circuit.cx(qr1, qr2)
coupling = CouplingMap([[0, 1]])
dag = circuit_to_dag(circuit)
pass_ = GateDirection(coupling)
after = pass_.run(dag)
self.assertEqual(dag, after)
def test_direction_flip(self):
"""Flip a CX
qr0:----.----
|
qr1:---(+)---
CouplingMap map: [0] -> [1]
qr0:-[H]-(+)-[H]--
|
qr1:-[H]--.--[H]--
"""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[1], qr[0])
coupling = CouplingMap([[0, 1]])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr)
expected.h(qr[0])
expected.h(qr[1])
expected.cx(qr[0], qr[1])
expected.h(qr[0])
expected.h(qr[1])
pass_ = GateDirection(coupling)
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_ecr_flip(self):
"""Flip a ECR gate.
ββββββββ
q_0: β€1 β
β ECR β
q_1: β€0 β
ββββββββ
CouplingMap map: [0, 1]
"""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.ecr(qr[1], qr[0])
coupling = CouplingMap([[0, 1]])
dag = circuit_to_dag(circuit)
# βββββββββββ βββββββββββββ
# qr_0: β€ Ry(Ο/2) βββ€0 ββ€ H β
# βββββββββββ΄ββ Ecr ββββββ€
# qr_1: β€ Ry(-Ο/2) ββ€1 ββ€ H β
# βββββββββββββββββββββββββ
expected = QuantumCircuit(qr, global_phase=-pi / 2)
expected.s(1)
expected.sx(1)
expected.sdg(1)
expected.sdg(0)
expected.sx(0)
expected.s(0)
expected.ecr(0, 1)
expected.h(0)
expected.h(1)
pass_ = GateDirection(coupling)
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_flip_with_measure(self):
"""
qr0: -(+)-[m]-
| |
qr1: --.---|--
|
cr0: ------.--
CouplingMap map: [0] -> [1]
qr0: -[H]--.--[H]-[m]-
| |
qr1: -[H]-(+)-[H]--|--
|
cr0: --------------.--
"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.cx(qr[1], qr[0])
circuit.measure(qr[0], cr[0])
coupling = CouplingMap([[0, 1]])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr, cr)
expected.h(qr[0])
expected.h(qr[1])
expected.cx(qr[0], qr[1])
expected.h(qr[0])
expected.h(qr[1])
expected.measure(qr[0], cr[0])
pass_ = GateDirection(coupling)
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_preserves_conditions(self):
"""Verify GateDirection preserves conditional on CX gates.
βββββ βββββ
q_0: |0>ββββ βββββ€ X βββββ βββ€ X β
βββ΄ββ βββ¬ββ βββ΄βββββ¬ββ
q_1: |0>ββ€ X ββββββ ββββ€ X ββββ ββ
βββ¬ββ β βββββ
ββββ΄βββββββ΄βββ
c_0: 0 β‘ = 0 ββ‘ = 0 βββββββββββ
ββββββββββββββ
"""
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(1, "c")
circuit = QuantumCircuit(qr, cr)
circuit.cx(qr[0], qr[1]).c_if(cr, 0)
circuit.cx(qr[1], qr[0]).c_if(cr, 0)
circuit.cx(qr[0], qr[1])
circuit.cx(qr[1], qr[0])
coupling = CouplingMap([[0, 1]])
dag = circuit_to_dag(circuit)
# βββββ βββββ βββββ βββββ
# q_0: ββββ ββββββββββββ€ H ββββββ ββββββββββββ€ H βββββ βββ€ H ββββ βββ€ H β
# βββ΄ββ βββββ βββ₯ββ βββ΄ββ βββββ βββ₯ββ βββ΄βββββββ€βββ΄βββββββ€
# q_1: ββ€ X ββββ€ H ββββββ«βββββ€ X ββββ€ H ββββββ«ββββ€ X ββ€ H ββ€ X ββ€ H β
# βββ₯ββ βββ₯ββ β βββ₯ββ βββ₯ββ β ββββββββββββββββββββ
# ββββ¨βββββββ¨βββββββ¨βββββββ¨βββββββ¨βββββββ¨βββ
# c: 1/β‘ 0x0 ββ‘ 0x0 ββ‘ 0x0 ββ‘ 0x0 ββ‘ 0x0 ββ‘ 0x0 βββββββββββββββββββββ
# ββββββββββββββββββββββββββββββββββββββββββ
expected = QuantumCircuit(qr, cr)
expected.cx(qr[0], qr[1]).c_if(cr, 0)
# Order of H gates is important because DAG comparison will consider
# different conditional order on a creg to be a different circuit.
# See https://github.com/Qiskit/qiskit-terra/issues/3164
expected.h(qr[1]).c_if(cr, 0)
expected.h(qr[0]).c_if(cr, 0)
expected.cx(qr[0], qr[1]).c_if(cr, 0)
expected.h(qr[1]).c_if(cr, 0)
expected.h(qr[0]).c_if(cr, 0)
expected.cx(qr[0], qr[1])
expected.h(qr[1])
expected.h(qr[0])
expected.cx(qr[0], qr[1])
expected.h(qr[1])
expected.h(qr[0])
pass_ = GateDirection(coupling)
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_regression_gh_8387(self):
"""Regression test for flipping of CZ gate"""
qc = QuantumCircuit(3)
qc.cz(1, 0)
qc.barrier()
qc.cz(2, 0)
coupling_map = CouplingMap([[0, 1], [1, 2]])
_ = transpile(
qc,
basis_gates=["cz", "cx", "u3", "u2", "u1"],
coupling_map=coupling_map,
optimization_level=2,
)
@ddt.data(CXGate(), CZGate(), ECRGate())
def test_target_static(self, gate):
"""Test that static 2q gates are swapped correctly both if available and not available."""
circuit = QuantumCircuit(2)
circuit.append(gate, [0, 1], [])
matching = Target(num_qubits=2)
matching.add_instruction(gate, {(0, 1): None})
self.assertEqual(GateDirection(None, target=matching)(circuit), circuit)
swapped = Target(num_qubits=2)
swapped.add_instruction(gate, {(1, 0): None})
self.assertNotEqual(GateDirection(None, target=swapped)(circuit), circuit)
@ddt.data(CZGate(), RZXGate(pi / 3), RXXGate(pi / 3), RYYGate(pi / 3), RZZGate(pi / 3))
def test_target_trivial(self, gate):
"""Test that trivial 2q gates are swapped correctly both if available and not available."""
circuit = QuantumCircuit(2)
circuit.append(gate, [0, 1], [])
matching = Target(num_qubits=2)
matching.add_instruction(gate, {(0, 1): None})
self.assertEqual(GateDirection(None, target=matching)(circuit), circuit)
swapped = Target(num_qubits=2)
swapped.add_instruction(gate, {(1, 0): None})
self.assertNotEqual(GateDirection(None, target=swapped)(circuit), circuit)
@ddt.data(CZGate(), SwapGate(), RXXGate(pi / 3), RYYGate(pi / 3), RZZGate(pi / 3))
def test_symmetric_gates(self, gate):
"""Test symmetric gates on single direction coupling map."""
circuit = QuantumCircuit(2)
circuit.append(gate, [1, 0], [])
expected = QuantumCircuit(2)
expected.append(gate, [0, 1], [])
coupling = CouplingMap.from_line(2, bidirectional=False)
pass_ = GateDirection(coupling)
self.assertEqual(pass_(circuit), expected)
def test_target_parameter_any(self):
"""Test that a parametrized 2q gate is replaced correctly both if available and not
available."""
circuit = QuantumCircuit(2)
circuit.rzx(1.5, 0, 1)
matching = Target(num_qubits=2)
matching.add_instruction(RZXGate(Parameter("a")), {(0, 1): None})
self.assertEqual(GateDirection(None, target=matching)(circuit), circuit)
swapped = Target(num_qubits=2)
swapped.add_instruction(RZXGate(Parameter("a")), {(1, 0): None})
self.assertNotEqual(GateDirection(None, target=swapped)(circuit), circuit)
def test_target_parameter_exact(self):
"""Test that a parametrized 2q gate is detected correctly both if available and not
available."""
circuit = QuantumCircuit(2)
circuit.rzx(1.5, 0, 1)
matching = Target(num_qubits=2)
matching.add_instruction(RZXGate(1.5), {(0, 1): None})
self.assertEqual(GateDirection(None, target=matching)(circuit), circuit)
swapped = Target(num_qubits=2)
swapped.add_instruction(RZXGate(1.5), {(1, 0): None})
self.assertNotEqual(GateDirection(None, target=swapped)(circuit), circuit)
def test_target_parameter_mismatch(self):
"""Test that the pass raises if a gate is not supported due to a parameter mismatch."""
circuit = QuantumCircuit(2)
circuit.rzx(1.5, 0, 1)
matching = Target(num_qubits=2)
matching.add_instruction(RZXGate(2.5), {(0, 1): None})
pass_ = GateDirection(None, target=matching)
with self.assertRaises(TranspilerError):
pass_(circuit)
swapped = Target(num_qubits=2)
swapped.add_instruction(RZXGate(2.5), {(1, 0): None})
pass_ = GateDirection(None, target=swapped)
with self.assertRaises(TranspilerError):
pass_(circuit)
def test_coupling_map_control_flow(self):
"""Test that gates are replaced within nested control-flow blocks."""
circuit = QuantumCircuit(4, 1)
circuit.h(0)
circuit.measure(0, 0)
with circuit.for_loop((1, 2)):
circuit.cx(1, 0)
circuit.cx(0, 1)
with circuit.if_test((circuit.clbits[0], True)) as else_:
circuit.ecr(3, 2)
with else_:
with circuit.while_loop((circuit.clbits[0], True)):
circuit.rzx(2.3, 2, 1)
expected = QuantumCircuit(4, 1)
expected.h(0)
expected.measure(0, 0)
with expected.for_loop((1, 2)):
expected.h([0, 1])
expected.cx(0, 1)
expected.h([0, 1])
expected.cx(0, 1)
with expected.if_test((circuit.clbits[0], True)) as else_:
expected.global_phase -= pi / 2
expected.sdg(2)
expected.sx(2)
expected.s(2)
expected.s(3)
expected.sx(3)
expected.sdg(3)
expected.ecr(2, 3)
expected.h([2, 3])
with else_:
with expected.while_loop((circuit.clbits[0], True)):
expected.h([1, 2])
expected.rzx(2.3, 1, 2)
expected.h([1, 2])
coupling = CouplingMap.from_line(4, bidirectional=False)
pass_ = GateDirection(coupling)
self.assertEqual(pass_(circuit), expected)
def test_target_control_flow(self):
"""Test that gates are replaced within nested control-flow blocks."""
circuit = QuantumCircuit(4, 1)
circuit.h(0)
circuit.measure(0, 0)
with circuit.for_loop((1, 2)):
circuit.cx(1, 0)
circuit.cx(0, 1)
with circuit.if_test((circuit.clbits[0], True)) as else_:
circuit.ecr(3, 2)
with else_:
with circuit.while_loop((circuit.clbits[0], True)):
circuit.rzx(2.3, 2, 1)
expected = QuantumCircuit(4, 1)
expected.h(0)
expected.measure(0, 0)
with expected.for_loop((1, 2)):
expected.h([0, 1])
expected.cx(0, 1)
expected.h([0, 1])
expected.cx(0, 1)
with expected.if_test((circuit.clbits[0], True)) as else_:
expected.global_phase -= pi / 2
expected.sdg(2)
expected.sx(2)
expected.s(2)
expected.s(3)
expected.sx(3)
expected.sdg(3)
expected.ecr(2, 3)
expected.h([2, 3])
with else_:
with expected.while_loop((circuit.clbits[0], True)):
expected.h([1, 2])
expected.rzx(2.3, 1, 2)
expected.h([1, 2])
target = Target(num_qubits=4)
target.add_instruction(CXGate(), {(0, 1): None})
target.add_instruction(ECRGate(), {(2, 3): None})
target.add_instruction(RZXGate(Parameter("a")), {(1, 2): None})
pass_ = GateDirection(None, target)
self.assertEqual(pass_(circuit), expected)
def test_target_cannot_flip_message(self):
"""A suitable error message should be emitted if the gate would be supported if it were
flipped."""
gate = Gate("my_2q_gate", 2, [])
target = Target(num_qubits=2)
target.add_instruction(gate, properties={(0, 1): None})
circuit = QuantumCircuit(2)
circuit.append(gate, (1, 0))
pass_ = GateDirection(None, target)
with self.assertRaisesRegex(TranspilerError, "'my_2q_gate' would be supported.*"):
pass_(circuit)
def test_target_cannot_flip_message_calibrated(self):
"""A suitable error message should be emitted if the gate would be supported if it were
flipped."""
target = Target(num_qubits=2)
target.add_instruction(CXGate(), properties={(0, 1): None})
gate = Gate("my_2q_gate", 2, [])
circuit = QuantumCircuit(2)
circuit.append(gate, (1, 0))
circuit.add_calibration(gate, (0, 1), pulse.ScheduleBlock())
pass_ = GateDirection(None, target)
with self.assertRaisesRegex(TranspilerError, "'my_2q_gate' would be supported.*"):
pass_(circuit)
def test_target_unknown_gate_message(self):
"""A suitable error message should be emitted if the gate isn't valid in either direction on
the target."""
gate = Gate("my_2q_gate", 2, [])
target = Target(num_qubits=2)
target.add_instruction(CXGate(), properties={(0, 1): None})
circuit = QuantumCircuit(2)
circuit.append(gate, (0, 1))
pass_ = GateDirection(None, target)
with self.assertRaisesRegex(TranspilerError, "'my_2q_gate'.*not supported on qubits .*"):
pass_(circuit)
def test_allows_calibrated_gates_coupling_map(self):
"""Test that the gate direction pass allows a gate that's got a calibration to pass through
without error."""
cm = CouplingMap([(1, 0)])
gate = Gate("my_2q_gate", 2, [])
circuit = QuantumCircuit(2)
circuit.append(gate, (0, 1))
circuit.add_calibration(gate, (0, 1), pulse.ScheduleBlock())
pass_ = GateDirection(cm)
self.assertEqual(pass_(circuit), circuit)
def test_allows_calibrated_gates_target(self):
"""Test that the gate direction pass allows a gate that's got a calibration to pass through
without error."""
target = Target(num_qubits=2)
target.add_instruction(CXGate(), properties={(0, 1): None})
gate = Gate("my_2q_gate", 2, [])
circuit = QuantumCircuit(2)
circuit.append(gate, (0, 1))
circuit.add_calibration(gate, (0, 1), pulse.ScheduleBlock())
pass_ = GateDirection(None, target)
self.assertEqual(pass_(circuit), circuit)
if __name__ == "__main__":
unittest.main()
| qiskit/test/python/transpiler/test_gate_direction.py/0 | {
"file_path": "qiskit/test/python/transpiler/test_gate_direction.py",
"repo_id": "qiskit",
"token_count": 9518
} | 330 |
# 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.
"""Testing naming functionality of transpiled circuits"""
import unittest
from qiskit.circuit import QuantumCircuit
from qiskit.compiler import transpile
from qiskit.providers.basic_provider import BasicSimulator
from qiskit.transpiler.exceptions import TranspilerError
from test import QiskitTestCase # pylint: disable=wrong-import-order
class TestNamingTranspiledCircuits(QiskitTestCase):
"""Testing the naming functionality for transpiled circuits."""
def setUp(self):
super().setUp()
self.basis_gates = ["u1", "u2", "u3", "cx"]
self.backend = BasicSimulator()
self.circuit0 = QuantumCircuit(name="circuit0")
self.circuit1 = QuantumCircuit(name="circuit1")
self.circuit2 = QuantumCircuit(name="circuit2")
self.circuit3 = QuantumCircuit(name="circuit3")
def test_single_circuit_name_singleton(self):
"""Test output_name with a single circuit
Given a single circuit and a output name in form of a string, this test
checks whether that string name is assigned to the transpiled circuit.
"""
trans_cirkie = transpile(
self.circuit0, basis_gates=self.basis_gates, output_name="transpiled-cirkie"
)
self.assertEqual(trans_cirkie.name, "transpiled-cirkie")
def test_single_circuit_name_list(self):
"""Test singleton output_name and a single circuit
Given a single circuit and an output name in form of a single element
list, this test checks whether the transpiled circuit is mapped with
that assigned name in the list.
If list has more than one element, then test checks whether the
Transpile function raises an error.
"""
trans_cirkie = transpile(
self.circuit0, basis_gates=self.basis_gates, output_name=["transpiled-cirkie"]
)
self.assertEqual(trans_cirkie.name, "transpiled-cirkie")
def test_single_circuit_and_multiple_name_list(self):
"""Test multiple output_name and a single circuit"""
# If List has multiple elements, transpile function must raise error
with self.assertRaises(TranspilerError):
transpile(
self.circuit0,
basis_gates=self.basis_gates,
output_name=["cool-cirkie", "new-cirkie", "dope-cirkie", "awesome-cirkie"],
)
def test_multiple_circuits_name_singleton(self):
"""Test output_name raise error if a single name is provided to a list of circuits
Given multiple circuits and a single string as a name, this test checks
whether the Transpile function raises an error.
"""
# Raise Error if single name given to multiple circuits
with self.assertRaises(TranspilerError):
transpile([self.circuit1, self.circuit2], self.backend, output_name="circ")
def test_multiple_circuits_name_list(self):
"""Test output_name with a list of circuits
Given multiple circuits and a list for output names, if
len(list)=len(circuits), then test checks whether transpile func assigns
each element in list to respective circuit.
If lengths are not equal, then test checks whether transpile func raises
error.
"""
# combining multiple circuits
circuits = [self.circuit1, self.circuit2, self.circuit3]
# equal lengths
names = ["awesome-circ1", "awesome-circ2", "awesome-circ3"]
trans_circuits = transpile(circuits, self.backend, output_name=names)
self.assertEqual(trans_circuits[0].name, "awesome-circ1")
self.assertEqual(trans_circuits[1].name, "awesome-circ2")
self.assertEqual(trans_circuits[2].name, "awesome-circ3")
def test_greater_circuits_name_list(self):
"""Test output_names list greater than circuits list"""
# combining multiple circuits
circuits = [self.circuit1, self.circuit2, self.circuit3]
# names list greater than circuits list
names = ["awesome-circ1", "awesome-circ2", "awesome-circ3", "awesome-circ4"]
with self.assertRaises(TranspilerError):
transpile(circuits, self.backend, output_name=names)
def test_smaller_circuits_name_list(self):
"""Test output_names list smaller than circuits list"""
# combining multiple circuits
circuits = [self.circuit1, self.circuit2, self.circuit3]
# names list smaller than circuits list
names = ["awesome-circ1", "awesome-circ2"]
with self.assertRaises(TranspilerError):
transpile(circuits, self.backend, output_name=names)
if __name__ == "__main__":
unittest.main()
| qiskit/test/python/transpiler/test_naming_transpiled_circuits.py/0 | {
"file_path": "qiskit/test/python/transpiler/test_naming_transpiled_circuits.py",
"repo_id": "qiskit",
"token_count": 1964
} | 331 |
# 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 the RemoveBarriers pass"""
import unittest
from qiskit.transpiler.passes import RemoveBarriers
from qiskit.converters import circuit_to_dag
from qiskit import QuantumCircuit
from test import QiskitTestCase # pylint: disable=wrong-import-order
class TestMergeAdjacentBarriers(QiskitTestCase):
"""Test the MergeAdjacentBarriers pass"""
def test_remove_barriers(self):
"""Remove all barriers"""
circuit = QuantumCircuit(2)
circuit.barrier()
circuit.barrier()
pass_ = RemoveBarriers()
result_dag = pass_.run(circuit_to_dag(circuit))
self.assertEqual(result_dag.size(), 0)
def test_remove_barriers_other_gates(self):
"""Remove all barriers, leave other gates intact"""
circuit = QuantumCircuit(1)
circuit.barrier()
circuit.x(0)
circuit.barrier()
circuit.h(0)
pass_ = RemoveBarriers()
result_dag = pass_.run(circuit_to_dag(circuit))
op_nodes = result_dag.op_nodes()
self.assertEqual(result_dag.size(), 2)
for ii, name in enumerate(["x", "h"]):
self.assertEqual(op_nodes[ii].name, name)
def test_simple_if_else(self):
"""Test that the pass recurses into an if-else."""
pass_ = RemoveBarriers()
base_test = QuantumCircuit(1, 1)
base_test.barrier()
base_test.measure(0, 0)
base_expected = QuantumCircuit(1, 1)
base_expected.measure(0, 0)
test = QuantumCircuit(1, 1)
test.if_else(
(test.clbits[0], True), base_test.copy(), base_test.copy(), test.qubits, test.clbits
)
expected = QuantumCircuit(1, 1)
expected.if_else(
(expected.clbits[0], True),
base_expected.copy(),
base_expected.copy(),
expected.qubits,
expected.clbits,
)
self.assertEqual(pass_(test), expected)
def test_nested_control_flow(self):
"""Test that the pass recurses into nested control flow."""
pass_ = RemoveBarriers()
base_test = QuantumCircuit(1, 1)
base_test.barrier()
base_test.measure(0, 0)
base_expected = QuantumCircuit(1, 1)
base_expected.measure(0, 0)
body_test = QuantumCircuit(1, 1)
body_test.for_loop((0,), None, base_expected.copy(), body_test.qubits, body_test.clbits)
body_expected = QuantumCircuit(1, 1)
body_expected.for_loop(
(0,), None, base_expected.copy(), body_expected.qubits, body_expected.clbits
)
test = QuantumCircuit(1, 1)
test.while_loop((test.clbits[0], True), body_test, test.qubits, test.clbits)
expected = QuantumCircuit(1, 1)
expected.while_loop(
(expected.clbits[0], True), body_expected, expected.qubits, expected.clbits
)
self.assertEqual(pass_(test), expected)
if __name__ == "__main__":
unittest.main()
| qiskit/test/python/transpiler/test_remove_barriers.py/0 | {
"file_path": "qiskit/test/python/transpiler/test_remove_barriers.py",
"repo_id": "qiskit",
"token_count": 1468
} | 332 |
# 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.
# pylint: disable=missing-function-docstring,missing-class-docstring
"""Test the staged passmanager logic"""
from unittest.mock import patch
from ddt import data, ddt
from qiskit.transpiler import PassManager, StagedPassManager
from qiskit.transpiler.exceptions import TranspilerError
from qiskit.transpiler.passes import Optimize1qGates, Depth, BasicSwap, BasisTranslator
from qiskit.circuit.library.standard_gates.equivalence_library import (
StandardEquivalenceLibrary as std_eqlib,
)
from test import QiskitTestCase # pylint: disable=wrong-import-order
@ddt
class TestStagedPassManager(QiskitTestCase):
def test_default_stages(self):
spm = StagedPassManager()
self.assertEqual(
spm.stages, ("init", "layout", "routing", "translation", "optimization", "scheduling")
)
spm = StagedPassManager(
init=PassManager([Optimize1qGates()]),
routing=PassManager([BasisTranslator(std_eqlib, ["u", "cx"])]),
scheduling=PassManager([Depth()]),
)
self.assertEqual(
[x.__class__.__name__ for x in spm.to_flow_controller().tasks],
["Optimize1qGates", "BasisTranslator", "Depth"],
)
def test_inplace_edit(self):
spm = StagedPassManager(stages=["single_stage"])
spm.single_stage = PassManager([Optimize1qGates(), Depth()])
self.assertEqual(
[x.__class__.__name__ for x in spm.to_flow_controller().tasks],
["Optimize1qGates", "Depth"],
)
spm.single_stage.append(BasisTranslator(std_eqlib, ["u"]))
spm.single_stage.append(Depth())
self.assertEqual(
[x.__class__.__name__ for x in spm.to_flow_controller().tasks],
["Optimize1qGates", "Depth", "BasisTranslator", "Depth"],
)
def test_invalid_stage(self):
with self.assertRaises(AttributeError):
StagedPassManager(stages=["init"], translation=PassManager())
def test_pre_phase_is_valid_stage(self):
spm = StagedPassManager(stages=["init"], pre_init=PassManager([Depth()]))
self.assertEqual(
[x.__class__.__name__ for x in spm.to_flow_controller().tasks],
["Depth"],
)
def test_append_extend_not_implemented(self):
spm = StagedPassManager()
with self.assertRaises(NotImplementedError):
spm.append(Depth())
with self.assertRaises(NotImplementedError):
spm += PassManager()
def test_invalid_stages(self):
invalid_stages = [
"two words",
"two-words",
"two+words",
"two&words",
"[two_words]",
"<two_words>",
"{two_words}",
"(two_words)",
"two^words",
"two_words!",
"^two_words",
"@two_words",
"two~words",
r"two\words",
"two/words",
]
all_stages = invalid_stages + ["two_words", "init"]
with self.assertRaises(ValueError) as err:
StagedPassManager(all_stages)
message = str(err.exception)
for stage in invalid_stages:
self.assertIn(stage, message)
def test_repeated_stages(self):
stages = ["alpha", "omega", "alpha"]
pre_alpha = PassManager(BasisTranslator(std_eqlib, ["u", "cx"]))
alpha = PassManager(Depth())
post_alpha = PassManager(BasicSwap([[0, 1], [1, 2]]))
omega = PassManager(Optimize1qGates())
spm = StagedPassManager(
stages, pre_alpha=pre_alpha, alpha=alpha, post_alpha=post_alpha, omega=omega
)
passes = (
*pre_alpha.to_flow_controller().tasks,
*alpha.to_flow_controller().tasks,
*post_alpha.to_flow_controller().tasks,
*omega.to_flow_controller().tasks,
*pre_alpha.to_flow_controller().tasks,
*alpha.to_flow_controller().tasks,
*post_alpha.to_flow_controller().tasks,
)
self.assertEqual(spm.to_flow_controller().tasks, passes)
def test_edit_stages(self):
spm = StagedPassManager()
with self.assertRaises(AttributeError):
spm.stages = ["init"]
with self.assertRaises(AttributeError):
spm.expanded_stages = ["init"]
@data(None, ["init"], ["init", "schedule"])
def test_expanded_stages(self, stages):
spm = StagedPassManager(stages=stages)
expanded_stages = (stage for stage in spm.expanded_stages)
for stage in spm.stages:
self.assertEqual(next(expanded_stages), "pre_" + stage)
self.assertEqual(next(expanded_stages), stage)
self.assertEqual(next(expanded_stages), "post_" + stage)
def test_setattr(self):
spm = StagedPassManager()
with self.assertRaises(TranspilerError):
spm.init = spm
mock_target = "qiskit.transpiler.passmanager.StagedPassManager._update_passmanager"
with patch(mock_target, spec=True) as mock:
spm.max_iteration = spm.max_iteration
mock.assert_not_called()
spm.init = None
mock.assert_called_once()
def test_getitem(self):
pm = PassManager(Depth())
spm = StagedPassManager(init=pm)
mock_target = "qiskit.transpiler.passmanager.StagedPassManager._update_passmanager"
with patch(mock_target, spec=True) as mock:
_ = spm[0]
mock.assert_called_once()
| qiskit/test/python/transpiler/test_staged_passmanager.py/0 | {
"file_path": "qiskit/test/python/transpiler/test_staged_passmanager.py",
"repo_id": "qiskit",
"token_count": 2709
} | 333 |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021, 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 the VF2Layout pass"""
import io
import pickle
import unittest
from math import pi
import ddt
import numpy
import rustworkx
from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister
from qiskit.circuit import ControlFlowOp
from qiskit.transpiler import CouplingMap, Target, TranspilerError
from qiskit.transpiler.passes.layout.vf2_layout import VF2Layout, VF2LayoutStopReason
from qiskit._accelerate.error_map import ErrorMap
from qiskit.converters import circuit_to_dag
from qiskit.providers.fake_provider import Fake5QV1, Fake127QPulseV1, GenericBackendV2
from qiskit.circuit import Measure
from qiskit.circuit.library import GraphState, CXGate, XGate, HGate
from qiskit.transpiler import PassManager, AnalysisPass
from qiskit.transpiler.target import InstructionProperties
from qiskit.transpiler.preset_passmanagers.common import generate_embed_passmanager
from test import QiskitTestCase # pylint: disable=wrong-import-order
from ..legacy_cmaps import TENERIFE_CMAP, RUESCHLIKON_CMAP, MANHATTAN_CMAP
class LayoutTestCase(QiskitTestCase):
"""VF2Layout assertions"""
seed = 42
def assertLayout(self, dag, coupling_map, property_set, strict_direction=False):
"""Checks if the circuit in dag was a perfect layout in property_set for the given
coupling_map"""
self.assertEqual(property_set["VF2Layout_stop_reason"], VF2LayoutStopReason.SOLUTION_FOUND)
layout = property_set["layout"]
edges = coupling_map.graph.edge_list()
def run(dag, wire_map):
for gate in dag.two_qubit_ops():
if dag.has_calibration_for(gate) or isinstance(gate.op, ControlFlowOp):
continue
physical_q0 = wire_map[gate.qargs[0]]
physical_q1 = wire_map[gate.qargs[1]]
if strict_direction:
result = (physical_q0, physical_q1) in edges
else:
result = (physical_q0, physical_q1) in edges or (
physical_q1,
physical_q0,
) in edges
self.assertTrue(result)
for node in dag.op_nodes(ControlFlowOp):
for block in node.op.blocks:
inner_wire_map = {
inner: wire_map[outer] for outer, inner in zip(node.qargs, block.qubits)
}
run(circuit_to_dag(block), inner_wire_map)
run(dag, {bit: layout[bit] for bit in dag.qubits})
@ddt.ddt
class TestVF2LayoutSimple(LayoutTestCase):
"""Tests the VF2Layout pass"""
def test_1q_component_influence(self):
"""Assert that the 1q component of a connected interaction graph is scored correctly."""
target = Target()
target.add_instruction(
CXGate(),
{
(0, 1): InstructionProperties(error=0.0),
(1, 2): InstructionProperties(error=0.0),
(2, 3): InstructionProperties(error=0.0),
},
)
target.add_instruction(
HGate(),
{
(0,): InstructionProperties(error=0.0),
(1,): InstructionProperties(error=0.0),
(2,): InstructionProperties(error=0.0),
},
)
target.add_instruction(
Measure(),
{
(0,): InstructionProperties(error=0.1),
(1,): InstructionProperties(error=0.1),
(2,): InstructionProperties(error=0.9),
},
)
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.cx(0, 1)
qc.cx(1, 0)
qc.measure(0, 0)
qc.measure(1, 1)
vf2_pass = VF2Layout(target=target, seed=self.seed)
vf2_pass(qc)
layout = vf2_pass.property_set["layout"]
self.assertEqual([1, 0], list(layout._p2v.keys()))
def test_2q_circuit_2q_coupling(self):
"""A simple example, without considering the direction
0 - 1
qr1 - qr0
"""
cmap = CouplingMap([[0, 1]])
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[1], qr[0]) # qr1 -> qr0
dag = circuit_to_dag(circuit)
pass_ = VF2Layout(cmap, strict_direction=False, seed=self.seed, max_trials=1)
pass_.run(dag)
self.assertLayout(dag, cmap, pass_.property_set)
def test_2q_circuit_2q_coupling_sd(self):
"""A simple example, considering the direction
0 -> 1
qr1 -> qr0
"""
cmap = CouplingMap([[0, 1]])
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[1], qr[0]) # qr1 -> qr0
dag = circuit_to_dag(circuit)
pass_ = VF2Layout(cmap, strict_direction=True, seed=self.seed, max_trials=1)
pass_.run(dag)
self.assertLayout(dag, cmap, pass_.property_set, strict_direction=True)
@ddt.data(True, False)
def test_2q_circuit_simple_control_flow(self, strict_direction):
"""Test that simple control-flow can be routed on a 2q coupling map."""
cmap = CouplingMap([(0, 1)])
circuit = QuantumCircuit(2)
with circuit.for_loop((1,)):
circuit.cx(1, 0)
dag = circuit_to_dag(circuit)
pass_ = VF2Layout(cmap, strict_direction=strict_direction, seed=self.seed, max_trials=1)
pass_.run(dag)
self.assertLayout(dag, cmap, pass_.property_set, strict_direction=strict_direction)
@ddt.data(True, False)
def test_2q_circuit_nested_control_flow(self, strict_direction):
"""Test that simple control-flow can be routed on a 2q coupling map."""
cmap = CouplingMap([(0, 1)])
circuit = QuantumCircuit(2, 1)
with circuit.while_loop((circuit.clbits[0], True)):
with circuit.if_test((circuit.clbits[0], True)) as else_:
circuit.cx(1, 0)
with else_:
circuit.cx(1, 0)
dag = circuit_to_dag(circuit)
pass_ = VF2Layout(cmap, strict_direction=strict_direction, seed=self.seed, max_trials=1)
pass_.run(dag)
self.assertLayout(dag, cmap, pass_.property_set, strict_direction=strict_direction)
def test_3q_circuit_3q_coupling_non_induced(self):
"""A simple example, check for non-induced subgraph
1 qr0 -> qr1 -> qr2
/ \
0 - 2
"""
cmap = CouplingMap([[0, 1], [1, 2], [2, 0]])
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1]) # qr0-> qr1
circuit.cx(qr[1], qr[2]) # qr1-> qr2
dag = circuit_to_dag(circuit)
pass_ = VF2Layout(cmap, seed=-1, max_trials=1)
pass_.run(dag)
self.assertLayout(dag, cmap, pass_.property_set)
def test_3q_circuit_3q_coupling_non_induced_control_flow(self):
r"""A simple example, check for non-induced subgraph
1 qr0 -> qr1 -> qr2
/ \
0 - 2
"""
cmap = CouplingMap([[0, 1], [1, 2], [2, 0]])
circuit = QuantumCircuit(3, 1)
with circuit.for_loop((1,)):
circuit.cx(0, 1) # qr0-> qr1
with circuit.if_test((circuit.clbits[0], True)) as else_:
pass
with else_:
with circuit.while_loop((circuit.clbits[0], True)):
circuit.cx(1, 2) # qr1-> qr2
dag = circuit_to_dag(circuit)
pass_ = VF2Layout(cmap, seed=-1, max_trials=1)
pass_.run(dag)
self.assertLayout(dag, cmap, pass_.property_set)
def test_call_limit(self):
"""Test that call limit is enforce."""
cmap = CouplingMap([[0, 1], [1, 2], [2, 0]])
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1]) # qr0-> qr1
circuit.cx(qr[1], qr[2]) # qr1-> qr2
dag = circuit_to_dag(circuit)
pass_ = VF2Layout(cmap, seed=-1, call_limit=1)
pass_.run(dag)
self.assertEqual(
pass_.property_set["VF2Layout_stop_reason"], VF2LayoutStopReason.NO_SOLUTION_FOUND
)
def test_coupling_map_and_target(self):
"""Test that a Target is used instead of a CouplingMap if both are specified."""
cmap = CouplingMap([[0, 1], [1, 2]])
target = Target()
target.add_instruction(CXGate(), {(0, 1): None, (1, 2): None, (1, 0): None})
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1]) # qr0-> qr1
circuit.cx(qr[1], qr[2]) # qr1-> qr2
circuit.cx(qr[1], qr[0]) # qr1-> qr0
dag = circuit_to_dag(circuit)
pass_ = VF2Layout(cmap, seed=-1, max_trials=1, target=target)
pass_.run(dag)
self.assertLayout(dag, target.build_coupling_map(), pass_.property_set)
def test_neither_coupling_map_or_target(self):
"""Test that we raise if neither a target or coupling map is specified."""
vf2_pass = VF2Layout(seed=123, call_limit=1000, time_limit=20, max_trials=7)
circuit = QuantumCircuit(2)
dag = circuit_to_dag(circuit)
with self.assertRaises(TranspilerError):
vf2_pass.run(dag)
def test_target_no_error(self):
"""Test that running vf2layout on a pass against a target with no error rates works."""
n_qubits = 15
target = Target()
target.add_instruction(CXGate(), {(i, i + 1): None for i in range(n_qubits - 1)})
vf2_pass = VF2Layout(target=target)
circuit = QuantumCircuit(2)
circuit.cx(0, 1)
dag = circuit_to_dag(circuit)
vf2_pass.run(dag)
self.assertLayout(dag, target.build_coupling_map(), vf2_pass.property_set)
def test_target_some_error(self):
"""Test that running vf2layout on a pass against a target with some error rates works."""
n_qubits = 15
target = Target()
target.add_instruction(
XGate(), {(i,): InstructionProperties(error=0.00123) for i in range(n_qubits)}
)
target.add_instruction(CXGate(), {(i, i + 1): None for i in range(n_qubits - 1)})
vf2_pass = VF2Layout(target=target)
circuit = QuantumCircuit(2)
circuit.h(0)
circuit.cx(0, 1)
dag = circuit_to_dag(circuit)
vf2_pass.run(dag)
self.assertLayout(dag, target.build_coupling_map(), vf2_pass.property_set)
class TestVF2LayoutLattice(LayoutTestCase):
"""Fit in 25x25 hexagonal lattice coupling map"""
cmap25 = CouplingMap.from_hexagonal_lattice(25, 25, bidirectional=False)
def graph_state_from_pygraph(self, graph):
"""Creates a GraphState circuit from a PyGraph"""
adjacency_matrix = rustworkx.adjacency_matrix(graph)
return GraphState(adjacency_matrix).decompose()
def test_hexagonal_lattice_graph_20_in_25(self):
"""A 20x20 interaction map in 25x25 coupling map"""
graph_20_20 = rustworkx.generators.hexagonal_lattice_graph(20, 20)
circuit = self.graph_state_from_pygraph(graph_20_20)
dag = circuit_to_dag(circuit)
pass_ = VF2Layout(self.cmap25, seed=self.seed, max_trials=1)
pass_.run(dag)
self.assertLayout(dag, self.cmap25, pass_.property_set)
def test_hexagonal_lattice_graph_9_in_25(self):
"""A 9x9 interaction map in 25x25 coupling map"""
graph_9_9 = rustworkx.generators.hexagonal_lattice_graph(9, 9)
circuit = self.graph_state_from_pygraph(graph_9_9)
dag = circuit_to_dag(circuit)
pass_ = VF2Layout(self.cmap25, seed=self.seed, max_trials=1)
pass_.run(dag)
self.assertLayout(dag, self.cmap25, pass_.property_set)
class TestVF2LayoutBackend(LayoutTestCase):
"""Tests VF2Layout against backends"""
def test_5q_circuit_Rueschlikon_no_solution(self):
"""5 qubits in Rueschlikon, no solution
q0[1] β β q0[2]
q0[0]
q0[3] β β q0[4]
"""
cmap16 = RUESCHLIKON_CMAP
qr = QuantumRegister(5, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[2])
circuit.cx(qr[0], qr[3])
circuit.cx(qr[0], qr[4])
dag = circuit_to_dag(circuit)
pass_ = VF2Layout(CouplingMap(cmap16), seed=self.seed, max_trials=1)
pass_.run(dag)
layout = pass_.property_set["layout"]
self.assertIsNone(layout)
self.assertEqual(
pass_.property_set["VF2Layout_stop_reason"], VF2LayoutStopReason.NO_SOLUTION_FOUND
)
def test_9q_circuit_Rueschlikon_sd(self):
"""9 qubits in Rueschlikon, considering the direction
1 β 2 β 3 β 4 β 5 β 6 β 7 β 8
β β β β β β β β
0 β 15 β 14 β 13 β 12 β 11 β 10 β 9
"""
cmap16 = CouplingMap(RUESCHLIKON_CMAP)
qr0 = QuantumRegister(4, "q0")
qr1 = QuantumRegister(5, "q1")
circuit = QuantumCircuit(qr0, qr1)
circuit.cx(qr0[1], qr0[2]) # q0[1] -> q0[2]
circuit.cx(qr0[0], qr1[3]) # q0[0] -> q1[3]
circuit.cx(qr1[4], qr0[2]) # q1[4] -> q0[2]
dag = circuit_to_dag(circuit)
pass_ = VF2Layout(cmap16, strict_direction=True, seed=self.seed, max_trials=1)
pass_.run(dag)
self.assertLayout(dag, cmap16, pass_.property_set)
def test_4q_circuit_Tenerife_loose_nodes(self):
"""4 qubits in Tenerife, with loose nodes
1
β β
0 β 2 β 3
β β
4
"""
cmap5 = CouplingMap(TENERIFE_CMAP)
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[1], qr[0]) # qr1 -> qr0
circuit.cx(qr[0], qr[2]) # qr0 -> qr2
dag = circuit_to_dag(circuit)
pass_ = VF2Layout(cmap5, seed=self.seed, max_trials=1)
pass_.run(dag)
self.assertLayout(dag, cmap5, pass_.property_set)
def test_3q_circuit_Tenerife_sd(self):
"""3 qubits in Tenerife, considering the direction
1 1
β β β β
0 β 2 β 3 0 β qr2 β qr1
β β β β
4 qr0
"""
cmap5 = CouplingMap(TENERIFE_CMAP)
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[1], qr[0]) # qr1 -> qr0
circuit.cx(qr[0], qr[2]) # qr0 -> qr2
circuit.cx(qr[1], qr[2]) # qr1 -> qr2
dag = circuit_to_dag(circuit)
pass_ = VF2Layout(cmap5, strict_direction=True, seed=self.seed, max_trials=1)
pass_.run(dag)
self.assertLayout(dag, cmap5, pass_.property_set, strict_direction=True)
def test_9q_circuit_Rueschlikon(self):
"""9 qubits in Rueschlikon, without considering the direction
1 β 2 β 3 β 4 β 5 β 6 β 7 β 8
β β β β β β β β
0 β 15 β 14 β 13 β 12 β 11 β 10 β 9
1 -- q1_0 - q1_1 - 4 --- 5 -- 6 - 7 --- q0_1
| | | | | | | |
q1_2 - q1_3 - q0_0 - 13 - q0_3 - 11 - q1_4 - q0_2
"""
cmap16 = CouplingMap(RUESCHLIKON_CMAP)
qr0 = QuantumRegister(4, "q0")
qr1 = QuantumRegister(5, "q1")
circuit = QuantumCircuit(qr0, qr1)
circuit.cx(qr0[1], qr0[2]) # q0[1] -> q0[2]
circuit.cx(qr0[0], qr1[3]) # q0[0] -> q1[3]
circuit.cx(qr1[4], qr0[2]) # q1[4] -> q0[2]
dag = circuit_to_dag(circuit)
pass_ = VF2Layout(cmap16, strict_direction=False, seed=self.seed, max_trials=1)
pass_.run(dag)
self.assertLayout(dag, cmap16, pass_.property_set)
def test_3q_circuit_Tenerife(self):
"""3 qubits in Tenerife, without considering the direction
1 1
β β / |
0 β 2 β 3 0 - qr1 - qr2
β β | /
4 qr0
"""
cmap5 = CouplingMap(TENERIFE_CMAP)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[1], qr[0]) # qr1 -> qr0
circuit.cx(qr[0], qr[2]) # qr0 -> qr2
circuit.cx(qr[1], qr[2]) # qr1 -> qr2
dag = circuit_to_dag(circuit)
pass_ = VF2Layout(cmap5, strict_direction=False, seed=self.seed, max_trials=1)
pass_.run(dag)
self.assertLayout(dag, cmap5, pass_.property_set)
def test_3q_circuit_vigo_with_custom_scores(self):
"""Test custom ErrorMap from analysis pass are used for scoring."""
backend = GenericBackendV2(num_qubits=5, seed=42)
target = backend.target
class FakeScore(AnalysisPass):
"""Fake analysis pass with custom scoring."""
def run(self, dag):
error_map = ErrorMap(9)
error_map.add_error((0, 0), 0.1)
error_map.add_error((0, 1), 0.5)
error_map.add_error((1, 1), 0.2)
error_map.add_error((1, 2), 0.8)
error_map.add_error((1, 3), 0.75)
error_map.add_error((2, 2), 0.123)
error_map.add_error((3, 3), 0.333)
error_map.add_error((3, 4), 0.12345423)
error_map.add_error((4, 4), 0.2222)
self.property_set["vf2_avg_error_map"] = error_map
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[1], qr[0]) # qr1 -> qr0
circuit.cx(qr[0], qr[2]) # qr0 -> qr2
vf2_pass = VF2Layout(target=target, seed=1234568942)
property_set = {}
vf2_pass(circuit, property_set)
pm = PassManager([FakeScore(), VF2Layout(target=target, seed=1234568942)])
pm.run(circuit)
# Assert layout is different from backend properties
self.assertNotEqual(property_set["layout"], pm.property_set["layout"])
self.assertLayout(circuit_to_dag(circuit), backend.coupling_map, pm.property_set)
def test_error_map_pickle(self):
"""Test that the `ErrorMap` Rust structure correctly pickles and depickles."""
errors = {(0, 1): 0.2, (1, 0): 0.2, (0, 0): 0.05, (1, 1): 0.02}
error_map = ErrorMap.from_dict(errors)
with io.BytesIO() as fptr:
pickle.dump(error_map, fptr)
fptr.seek(0)
loaded = pickle.load(fptr)
self.assertEqual(len(loaded), len(errors))
self.assertEqual({k: loaded[k] for k in errors}, errors)
def test_perfect_fit_Manhattan(self):
"""A circuit that fits perfectly in Manhattan (65 qubits)
See https://github.com/Qiskit/qiskit-terra/issues/5694"""
cmap65 = CouplingMap(MANHATTAN_CMAP)
rows = [x[0] for x in MANHATTAN_CMAP]
cols = [x[1] for x in MANHATTAN_CMAP]
adj_matrix = numpy.zeros((65, 65))
adj_matrix[rows, cols] = 1
circuit = GraphState(adj_matrix).decompose()
circuit.measure_all()
dag = circuit_to_dag(circuit)
pass_ = VF2Layout(cmap65, seed=self.seed, max_trials=1)
pass_.run(dag)
self.assertLayout(dag, cmap65, pass_.property_set)
class TestVF2LayoutOther(LayoutTestCase):
"""Other VF2Layout tests"""
def test_seed(self):
"""Different seeds yield different results"""
seed_1 = 42
seed_2 = 45
cmap5 = TENERIFE_CMAP
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[1], qr[0]) # qr1 -> qr0
circuit.cx(qr[0], qr[2]) # qr0 -> qr2
circuit.cx(qr[1], qr[2]) # qr1 -> qr2
dag = circuit_to_dag(circuit)
pass_1 = VF2Layout(CouplingMap(cmap5), seed=seed_1, max_trials=1)
pass_1.run(dag)
layout_1 = pass_1.property_set["layout"]
self.assertEqual(
pass_1.property_set["VF2Layout_stop_reason"], VF2LayoutStopReason.SOLUTION_FOUND
)
pass_2 = VF2Layout(CouplingMap(cmap5), seed=seed_2, max_trials=1)
pass_2.run(dag)
layout_2 = pass_2.property_set["layout"]
self.assertEqual(
pass_2.property_set["VF2Layout_stop_reason"], VF2LayoutStopReason.SOLUTION_FOUND
)
self.assertNotEqual(layout_1, layout_2)
def test_3_q_gate(self):
"""The pass does not handle gates with more than 2 qubits"""
seed_1 = 42
cmap5 = TENERIFE_CMAP
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.ccx(qr[1], qr[0], qr[2])
dag = circuit_to_dag(circuit)
pass_1 = VF2Layout(CouplingMap(cmap5), seed=seed_1, max_trials=1)
pass_1.run(dag)
self.assertEqual(
pass_1.property_set["VF2Layout_stop_reason"], VF2LayoutStopReason.MORE_THAN_2Q
)
def test_target_without_coupling_map(self):
"""When a target has no coupling_map but it is provided as argument.
See: https://github.com/Qiskit/qiskit/pull/11585"""
circuit = QuantumCircuit(3)
circuit.cx(0, 1)
dag = circuit_to_dag(circuit)
target = Target(num_qubits=3)
target.add_instruction(CXGate())
vf2_pass = VF2Layout(
coupling_map=CouplingMap([[0, 2], [1, 2]]), target=target, seed=42, max_trials=1
)
vf2_pass.run(dag)
self.assertEqual(
vf2_pass.property_set["VF2Layout_stop_reason"], VF2LayoutStopReason.SOLUTION_FOUND
)
class TestMultipleTrials(QiskitTestCase):
"""Test the passes behavior with >1 trial."""
def test_no_properties(self):
"""Test it finds the lowest degree perfect layout with no properties."""
vf2_pass = VF2Layout(
CouplingMap(
[
(0, 1),
(0, 2),
(0, 3),
(1, 0),
(1, 2),
(1, 3),
(2, 0),
(2, 1),
(2, 2),
(2, 3),
(3, 0),
(3, 1),
(3, 2),
(4, 0),
(0, 4),
(5, 1),
(1, 5),
]
)
)
qr = QuantumRegister(2)
qc = QuantumCircuit(qr)
qc.x(qr)
qc.measure_all()
property_set = {}
vf2_pass(qc, property_set)
self.assertEqual(set(property_set["layout"].get_physical_bits()), {4, 5})
def test_with_properties(self):
"""Test it finds the least noise perfect layout with no properties."""
with self.assertWarns(DeprecationWarning):
backend = Fake5QV1()
qr = QuantumRegister(2)
qc = QuantumCircuit(qr)
qc.x(qr)
qc.measure_all()
cmap = CouplingMap(backend.configuration().coupling_map)
properties = backend.properties()
vf2_pass = VF2Layout(cmap, properties=properties)
property_set = {}
vf2_pass(qc, property_set)
self.assertEqual(set(property_set["layout"].get_physical_bits()), {1, 3})
def test_max_trials_exceeded(self):
"""Test it exits when max_trials is reached."""
with self.assertWarns(DeprecationWarning):
backend = Fake5QV1()
qr = QuantumRegister(2)
qc = QuantumCircuit(qr)
qc.x(qr)
qc.cx(0, 1)
qc.measure_all()
cmap = CouplingMap(backend.configuration().coupling_map)
properties = backend.properties()
vf2_pass = VF2Layout(cmap, properties=properties, seed=-1, max_trials=1)
property_set = {}
with self.assertLogs("qiskit.transpiler.passes.layout.vf2_layout", level="DEBUG") as cm:
vf2_pass(qc, property_set)
self.assertIn(
"DEBUG:qiskit.transpiler.passes.layout.vf2_layout:Trial 1 is >= configured max trials 1",
cm.output,
)
self.assertEqual(set(property_set["layout"].get_physical_bits()), {2, 0})
def test_time_limit_exceeded(self):
"""Test the pass stops after time_limit is reached."""
with self.assertWarns(DeprecationWarning):
backend = Fake5QV1()
qr = QuantumRegister(2)
qc = QuantumCircuit(qr)
qc.x(qr)
qc.cx(0, 1)
qc.measure_all()
cmap = CouplingMap(backend.configuration().coupling_map)
properties = backend.properties()
vf2_pass = VF2Layout(cmap, properties=properties, seed=-1, time_limit=0.0)
property_set = {}
with self.assertLogs("qiskit.transpiler.passes.layout.vf2_layout", level="DEBUG") as cm:
vf2_pass(qc, property_set)
for output in cm.output:
if output.startswith(
"DEBUG:qiskit.transpiler.passes.layout.vf2_layout:VF2Layout has taken"
) and output.endswith("which exceeds configured max time: 0.0"):
break
else:
self.fail("No failure debug log message found")
self.assertEqual(set(property_set["layout"].get_physical_bits()), {2, 0})
def test_reasonable_limits_for_simple_layouts_v1(self):
"""Test that the default trials is set to a reasonable number.
REMOVE ONCE Fake127QPulseV1 IS GONE"""
with self.assertWarns(DeprecationWarning):
backend = Fake127QPulseV1()
qc = QuantumCircuit(5)
qc.cx(2, 3)
qc.cx(0, 1)
cmap = CouplingMap(backend.configuration().coupling_map)
properties = backend.properties()
# Run without any limits set
vf2_pass = VF2Layout(cmap, properties=properties, seed=42)
property_set = {}
with self.assertLogs("qiskit.transpiler.passes.layout.vf2_layout", level="DEBUG") as cm:
vf2_pass(qc, property_set)
self.assertIn(
"DEBUG:qiskit.transpiler.passes.layout.vf2_layout:Trial 299 is >= configured max trials 299",
cm.output,
)
self.assertEqual(set(property_set["layout"].get_physical_bits()), {57, 58, 61, 62, 0})
def test_reasonable_limits_for_simple_layouts(self):
"""Test that the default trials is set to a reasonable number."""
backend = GenericBackendV2(27, calibrate_instructions=True, seed=42)
qc = QuantumCircuit(5)
qc.cx(2, 3)
qc.cx(0, 1)
# Run without any limits set
vf2_pass = VF2Layout(target=backend.target, seed=42)
property_set = {}
with self.assertLogs("qiskit.transpiler.passes.layout.vf2_layout", level="DEBUG") as cm:
vf2_pass(qc, property_set)
self.assertIn(
"DEBUG:qiskit.transpiler.passes.layout.vf2_layout:Trial 717 is >= configured max trials 717",
cm.output,
)
self.assertEqual(set(property_set["layout"].get_physical_bits()), {16, 24, 6, 7, 0})
def test_no_limits_with_negative(self):
"""Test that we're not enforcing a trial limit if set to negative."""
with self.assertWarns(DeprecationWarning):
backend = Fake5QV1()
qc = QuantumCircuit(3)
qc.h(0)
cmap = CouplingMap(backend.configuration().coupling_map)
properties = backend.properties()
# Run without any limits set
vf2_pass = VF2Layout(
cmap,
properties=properties,
seed=42,
max_trials=0,
)
property_set = {}
with self.assertLogs("qiskit.transpiler.passes.layout.vf2_layout", level="DEBUG") as cm:
vf2_pass(qc, property_set)
for output in cm.output:
self.assertNotIn("is >= configured max trials", output)
self.assertEqual(set(property_set["layout"].get_physical_bits()), {3, 1, 0})
def test_qregs_valid_layout_output(self):
"""Test that vf2 layout doesn't add extra qubits.
Reproduce from https://github.com/Qiskit/qiskit-terra/issues/8667
"""
backend = GenericBackendV2(
basis_gates=["cx", "id", "rz", "sx", "x"], num_qubits=16, seed=42
)
qr = QuantumRegister(16, name="qr")
cr = ClassicalRegister(5)
qc = QuantumCircuit(qr, cr)
qc.rz(pi / 2, qr[0])
qc.sx(qr[0])
qc.sx(qr[1])
qc.rz(-pi / 4, qr[1])
qc.sx(qr[1])
qc.rz(pi / 2, qr[1])
qc.rz(2.8272143, qr[0])
qc.rz(0.43324854, qr[1])
qc.sx(qr[1])
qc.rz(-0.95531662, qr[7])
qc.sx(qr[7])
qc.rz(3 * pi / 4, qr[7])
qc.barrier([qr[1], qr[10], qr[4], qr[0], qr[7]])
vf2_pass = VF2Layout(
seed=12345,
target=backend.target,
)
vf2_pass(qc)
self.assertEqual(len(vf2_pass.property_set["layout"].get_physical_bits()), 16)
self.assertEqual(len(vf2_pass.property_set["layout"].get_virtual_bits()), 16)
pm = PassManager(
[
VF2Layout(
seed=12345,
target=backend.target,
)
]
)
pm += generate_embed_passmanager(backend.coupling_map)
res = pm.run(qc)
self.assertEqual(res.num_qubits, 16)
if __name__ == "__main__":
unittest.main()
| qiskit/test/python/transpiler/test_vf2_layout.py/0 | {
"file_path": "qiskit/test/python/transpiler/test_vf2_layout.py",
"repo_id": "qiskit",
"token_count": 15253
} | 334 |
\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} : } & \ctrl{1} & \qw & \qw\\
\nghost{{q}_{1} : } & \lstick{{q}_{1} : } & \multigate{2}{\mathrm{Ctrl\mbox{-}GHZ\,Circuit}}_<<<{0} & \qw & \qw\\
\nghost{{q}_{2} : } & \lstick{{q}_{2} : } & \ghost{\mathrm{Ctrl\mbox{-}GHZ\,Circuit}}_<<<{2} & \qw & \qw\\
\nghost{{q}_{3} : } & \lstick{{q}_{3} : } & \ghost{\mathrm{Ctrl\mbox{-}GHZ\,Circuit}}_<<<{1} & \qw & \qw\\
\nghost{{q}_{4} : } & \lstick{{q}_{4} : } & \ctrlo{-1} & \qw & \qw\\
\\ }}
\end{document} | qiskit/test/python/visualization/references/test_latex_ghz_to_gate.tex/0 | {
"file_path": "qiskit/test/python/visualization/references/test_latex_ghz_to_gate.tex",
"repo_id": "qiskit",
"token_count": 377
} | 335 |
# 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=invalid-name
"""Tests for generator of timeline drawer."""
import qiskit
from qiskit.visualization.timeline import generators, types, stylesheet
from qiskit.circuit import library, Delay
from test import QiskitTestCase # pylint: disable=wrong-import-order
class TestGates(QiskitTestCase):
"""Tests for generator.gates."""
def setUp(self) -> None:
"""Setup."""
super().setUp()
self.qubit = list(qiskit.QuantumRegister(1, name="foo"))[0]
self.u1 = types.ScheduledGate(
t0=100, operand=library.U1Gate(0), duration=0, bits=[self.qubit], bit_position=0
)
self.u3 = types.ScheduledGate(
t0=100, operand=library.U3Gate(0, 0, 0), duration=20, bits=[self.qubit], bit_position=0
)
self.delay = types.ScheduledGate(
t0=100, operand=Delay(20), duration=20, bits=[self.qubit], bit_position=0
)
style = stylesheet.QiskitTimelineStyle()
self.formatter = style.formatter
def test_gen_sched_gate_with_finite_duration(self):
"""Test test_gen_sched_gate generator with finite duration gate."""
drawing_obj = generators.gen_sched_gate(self.u3, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.BoxType.SCHED_GATE.value))
self.assertListEqual(list(drawing_obj.xvals), [100, 120])
self.assertListEqual(
list(drawing_obj.yvals),
[-0.5 * self.formatter["box_height.gate"], 0.5 * self.formatter["box_height.gate"]],
)
self.assertListEqual(drawing_obj.bits, [self.qubit])
ref_meta = {
"name": "u3",
"label": "n/a",
"bits": [self.qubit],
"t0": 100,
"duration": 20,
"unitary": "[[1.+0.j 0.-0.j]\n [0.+0.j 1.+0.j]]",
"parameters": "0, 0, 0",
}
self.assertDictEqual(ref_meta, drawing_obj.meta)
ref_styles = {
"zorder": self.formatter["layer.gate"],
"facecolor": self.formatter["color.gates"]["u3"],
"alpha": self.formatter["alpha.gate"],
"linewidth": self.formatter["line_width.gate"],
}
self.assertDictEqual(ref_styles, drawing_obj.styles)
def test_gen_sched_gate_with_zero_duration(self):
"""Test test_gen_sched_gate generator with zero duration gate."""
drawing_obj = generators.gen_sched_gate(self.u1, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.SymbolType.FRAME.value))
self.assertListEqual(list(drawing_obj.xvals), [100])
self.assertListEqual(list(drawing_obj.yvals), [0])
self.assertListEqual(drawing_obj.bits, [self.qubit])
self.assertEqual(drawing_obj.text, self.formatter["unicode_symbol.frame_change"])
self.assertEqual(drawing_obj.latex, self.formatter["latex_symbol.frame_change"])
ref_styles = {
"zorder": self.formatter["layer.frame_change"],
"color": self.formatter["color.gates"]["u1"],
"size": self.formatter["text_size.frame_change"],
"va": "center",
"ha": "center",
}
self.assertDictEqual(ref_styles, drawing_obj.styles)
def test_gen_sched_gate_with_delay(self):
"""Test test_gen_sched_gate generator with delay."""
drawing_obj = generators.gen_sched_gate(self.delay, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.BoxType.DELAY.value))
def test_gen_full_gate_name_with_finite_duration(self):
"""Test gen_full_gate_name generator with finite duration gate."""
drawing_obj = generators.gen_full_gate_name(self.u3, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.LabelType.GATE_NAME.value))
self.assertListEqual(list(drawing_obj.xvals), [110.0])
self.assertListEqual(list(drawing_obj.yvals), [0.0])
self.assertListEqual(drawing_obj.bits, [self.qubit])
self.assertEqual(drawing_obj.text, "u3(0.00, 0.00, 0.00)[20]")
ref_latex = f"{self.formatter['latex_symbol.gates']['u3']}(0.00, 0.00, 0.00)[20]"
self.assertEqual(drawing_obj.latex, ref_latex)
ref_styles = {
"zorder": self.formatter["layer.gate_name"],
"color": self.formatter["color.gate_name"],
"size": self.formatter["text_size.gate_name"],
"va": "center",
"ha": "center",
}
self.assertDictEqual(ref_styles, drawing_obj.styles)
def test_gen_full_gate_name_with_zero_duration(self):
"""Test gen_full_gate_name generator with zero duration gate."""
drawing_obj = generators.gen_full_gate_name(self.u1, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.LabelType.GATE_NAME.value))
self.assertListEqual(list(drawing_obj.xvals), [100.0])
self.assertListEqual(list(drawing_obj.yvals), [self.formatter["label_offset.frame_change"]])
self.assertListEqual(drawing_obj.bits, [self.qubit])
self.assertEqual(drawing_obj.text, "u1(0.00)")
ref_latex = f"{self.formatter['latex_symbol.gates']['u1']}(0.00)"
self.assertEqual(drawing_obj.latex, ref_latex)
ref_styles = {
"zorder": self.formatter["layer.gate_name"],
"color": self.formatter["color.gate_name"],
"size": self.formatter["text_size.gate_name"],
"va": "bottom",
"ha": "center",
}
self.assertDictEqual(ref_styles, drawing_obj.styles)
def test_gen_full_gate_name_with_delay(self):
"""Test gen_full_gate_name generator with delay."""
drawing_obj = generators.gen_full_gate_name(self.delay, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.LabelType.DELAY.value))
def test_gen_short_gate_name_with_finite_duration(self):
"""Test gen_short_gate_name generator with finite duration gate."""
drawing_obj = generators.gen_short_gate_name(self.u3, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.LabelType.GATE_NAME.value))
self.assertListEqual(list(drawing_obj.xvals), [110.0])
self.assertListEqual(list(drawing_obj.yvals), [0.0])
self.assertListEqual(drawing_obj.bits, [self.qubit])
self.assertEqual(drawing_obj.text, "u3")
ref_latex = f"{self.formatter['latex_symbol.gates']['u3']}"
self.assertEqual(drawing_obj.latex, ref_latex)
ref_styles = {
"zorder": self.formatter["layer.gate_name"],
"color": self.formatter["color.gate_name"],
"size": self.formatter["text_size.gate_name"],
"va": "center",
"ha": "center",
}
self.assertDictEqual(ref_styles, drawing_obj.styles)
def test_gen_short_gate_name_with_zero_duration(self):
"""Test gen_short_gate_name generator with zero duration gate."""
drawing_obj = generators.gen_short_gate_name(self.u1, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.LabelType.GATE_NAME.value))
self.assertListEqual(list(drawing_obj.xvals), [100.0])
self.assertListEqual(list(drawing_obj.yvals), [self.formatter["label_offset.frame_change"]])
self.assertListEqual(drawing_obj.bits, [self.qubit])
self.assertEqual(drawing_obj.text, "u1")
ref_latex = f"{self.formatter['latex_symbol.gates']['u1']}"
self.assertEqual(drawing_obj.latex, ref_latex)
ref_styles = {
"zorder": self.formatter["layer.gate_name"],
"color": self.formatter["color.gate_name"],
"size": self.formatter["text_size.gate_name"],
"va": "bottom",
"ha": "center",
}
self.assertDictEqual(ref_styles, drawing_obj.styles)
def test_gen_short_gate_name_with_delay(self):
"""Test gen_short_gate_name generator with delay."""
drawing_obj = generators.gen_short_gate_name(self.delay, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.LabelType.DELAY.value))
class TestTimeslot(QiskitTestCase):
"""Tests for generator.bits."""
def setUp(self) -> None:
"""Setup."""
super().setUp()
self.program = qiskit.QuantumCircuit(qiskit.QuantumRegister(1, "bar"))
self.program._op_start_times = []
self.qubit = self.program.qubits[0]
style = stylesheet.QiskitTimelineStyle()
self.formatter = style.formatter
def test_gen_timeslot(self):
"""Test gen_timeslot generator."""
drawing_obj = generators.gen_timeslot(self.qubit, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.BoxType.TIMELINE.value))
self.assertListEqual(
list(drawing_obj.xvals), [types.AbstractCoordinate.LEFT, types.AbstractCoordinate.RIGHT]
)
self.assertListEqual(
list(drawing_obj.yvals),
[
-0.5 * self.formatter["box_height.timeslot"],
0.5 * self.formatter["box_height.timeslot"],
],
)
self.assertListEqual(drawing_obj.bits, [self.qubit])
ref_styles = {
"zorder": self.formatter["layer.timeslot"],
"alpha": self.formatter["alpha.timeslot"],
"linewidth": self.formatter["line_width.timeslot"],
"facecolor": self.formatter["color.timeslot"],
}
self.assertDictEqual(ref_styles, drawing_obj.styles)
def test_gen_bit_name(self):
"""Test gen_bit_name generator."""
with self.assertWarnsRegex(UserWarning, "bits cannot be accurately named"):
generators.gen_bit_name(self.qubit, self.formatter)
drawing_obj = generators.gen_bit_name(self.qubit, self.formatter, program=self.program)[0]
self.assertEqual(drawing_obj.data_type, str(types.LabelType.BIT_NAME.value))
self.assertListEqual(list(drawing_obj.xvals), [types.AbstractCoordinate.LEFT])
self.assertListEqual(list(drawing_obj.yvals), [0])
self.assertListEqual(drawing_obj.bits, [self.qubit])
self.assertEqual(drawing_obj.text, "bar")
# pylint: disable-next=consider-using-f-string
ref_latex = r"{{\rm {register}}}_{{{index}}}".format(register="q", index="0")
self.assertEqual(drawing_obj.latex, ref_latex)
ref_styles = {
"zorder": self.formatter["layer.bit_name"],
"color": self.formatter["color.bit_name"],
"size": self.formatter["text_size.bit_name"],
"va": "center",
"ha": "right",
}
self.assertDictEqual(ref_styles, drawing_obj.styles)
class TestBarrier(QiskitTestCase):
"""Tests for generator.barriers."""
def setUp(self) -> None:
"""Setup."""
super().setUp()
self.qubits = list(qiskit.QuantumRegister(3))
self.barrier = types.Barrier(t0=100, bits=self.qubits, bit_position=1)
style = stylesheet.QiskitTimelineStyle()
self.formatter = style.formatter
def test_gen_barrier(self):
"""Test gen_barrier generator."""
drawing_obj = generators.gen_barrier(self.barrier, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.LineType.BARRIER.value))
self.assertListEqual(list(drawing_obj.xvals), [100, 100])
self.assertListEqual(list(drawing_obj.yvals), [-0.5, 0.5])
self.assertListEqual(drawing_obj.bits, [self.qubits[1]])
ref_styles = {
"alpha": self.formatter["alpha.barrier"],
"zorder": self.formatter["layer.barrier"],
"linewidth": self.formatter["line_width.barrier"],
"linestyle": self.formatter["line_style.barrier"],
"color": self.formatter["color.barrier"],
}
self.assertDictEqual(ref_styles, drawing_obj.styles)
class TestGateLink(QiskitTestCase):
"""Tests for generator.gate_links."""
def setUp(self) -> None:
"""Setup."""
super().setUp()
self.qubits = list(qiskit.QuantumRegister(2))
self.gate_link = types.GateLink(t0=100, opname="cx", bits=self.qubits)
style = stylesheet.QiskitTimelineStyle()
self.formatter = style.formatter
def gen_bit_link(self):
"""Test gen_bit_link generator."""
drawing_obj = generators.gen_gate_link(self.gate_link, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.LineType.GATE_LINK.value))
self.assertListEqual(list(drawing_obj.xvals), [100])
self.assertListEqual(list(drawing_obj.yvals), [0])
self.assertListEqual(drawing_obj.bits, self.qubits)
ref_styles = {
"alpha": self.formatter["alpha.bit_link"],
"zorder": self.formatter["layer.bit_link"],
"linewidth": self.formatter["line_width.bit_link"],
"linestyle": self.formatter["line_style.bit_link"],
"color": self.formatter["color.gates"]["cx"],
}
self.assertDictEqual(ref_styles, drawing_obj.styles)
| qiskit/test/python/visualization/timeline/test_generators.py/0 | {
"file_path": "qiskit/test/python/visualization/timeline/test_generators.py",
"repo_id": "qiskit",
"token_count": 6148
} | 336 |
# 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.
"""Image comparison tests."""
import json
import os
from contextlib import contextmanager
from pathlib import Path
from PIL import Image, ImageChops, ImageDraw
@contextmanager
def cwd(path):
"""A context manager to run in a particular path"""
oldpwd = os.getcwd()
os.chdir(path)
try:
yield
finally:
os.chdir(oldpwd)
class VisualTestUtilities:
"""Utility methods for circuit and graph visual testing"""
@staticmethod
def _new_gray(size, color):
img = Image.new("L", size)
drawing = ImageDraw.Draw(img)
drawing.rectangle((0, 0) + size, color)
return img
@staticmethod
def _black_or_b(diff_image, image, reference, opacity=0.85):
"""Copied from https://stackoverflow.com/a/30307875"""
thresholded_diff = diff_image
for _ in range(3):
thresholded_diff = ImageChops.add(thresholded_diff, thresholded_diff)
size = diff_image.size
mask = VisualTestUtilities._new_gray(size, int(255 * (opacity)))
shade = VisualTestUtilities._new_gray(size, 0)
new = reference.copy()
new.paste(shade, mask=mask)
if image.size != new.size:
image = image.resize(new.size)
if image.size != thresholded_diff.size:
thresholded_diff = thresholded_diff.resize(image.size)
new.paste(image, mask=thresholded_diff)
return new
@staticmethod
def _get_black_pixels(image):
black_and_white_version = image.convert("1")
black_pixels = black_and_white_version.histogram()[0]
return black_pixels
@staticmethod
def _save_diff(current, expected, image_name, failure_diff_dir, failure_prefix):
diff_name = current.split(".")
diff_name.insert(-1, "diff")
diff_name = ".".join(diff_name)
current = Image.open(current)
expected = Image.open(expected)
diff = ImageChops.difference(expected, current).convert("L")
black_pixels = VisualTestUtilities._get_black_pixels(diff)
total_pixels = diff.size[0] * diff.size[1]
diff_ratio = black_pixels / total_pixels
if diff_ratio != 1:
VisualTestUtilities._black_or_b(diff, current, expected).save(
str(Path(failure_diff_dir) / (failure_prefix + image_name)), "PNG"
)
else:
VisualTestUtilities._black_or_b(diff, current, expected).save(diff_name, "PNG")
return diff_ratio
@staticmethod
def save_data_wrap(func, testname, result_dir):
"""A wrapper to save the data a test"""
def wrapper(*args, **kwargs):
image_filename = kwargs["filename"]
with cwd(result_dir):
results = func(*args, **kwargs)
VisualTestUtilities.save_data(image_filename, testname)
return results
return wrapper
@staticmethod
def save_data(image_filename, testname):
"""Saves result data of a test"""
datafilename = "result_test.json"
if os.path.exists(datafilename):
with open(datafilename, encoding="UTF-8") as datafile:
data = json.load(datafile)
else:
data = {}
data[image_filename] = {"testname": testname}
with open(datafilename, "w", encoding="UTF-8") as datafile:
json.dump(data, datafile)
| qiskit/test/visual/__init__.py/0 | {
"file_path": "qiskit/test/visual/__init__.py",
"repo_id": "qiskit",
"token_count": 1602
} | 337 |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020, 2024.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for circuit MPL drawer"""
import unittest
import os
import math
from pathlib import Path
import numpy as np
from numpy import pi
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, transpile
from qiskit.providers.fake_provider import GenericBackendV2
from qiskit.visualization.circuit.circuit_visualization import circuit_drawer
from qiskit.circuit.library import (
XGate,
MCXGate,
HGate,
RZZGate,
SwapGate,
DCXGate,
ZGate,
SGate,
SXGate,
U1Gate,
CPhaseGate,
HamiltonianGate,
Isometry,
)
from qiskit.circuit.library import MCXVChain
from qiskit.circuit.annotated_operation import (
AnnotatedOperation,
InverseModifier,
ControlModifier,
PowerModifier,
)
from qiskit.circuit import Parameter, Qubit, Clbit, IfElseOp, SwitchCaseOp
from qiskit.circuit.library import IQP
from qiskit.circuit.classical import expr, types
from qiskit.quantum_info import random_clifford
from qiskit.quantum_info.random import random_unitary
from qiskit.utils import optionals
from test.visual import VisualTestUtilities # pylint: disable=wrong-import-order
from test import QiskitTestCase # pylint: disable=wrong-import-order
from test.python.legacy_cmaps import ( # pylint: disable=wrong-import-order
TENERIFE_CMAP,
YORKTOWN_CMAP,
)
if optionals.HAS_MATPLOTLIB:
from matplotlib.pyplot import close as mpl_close
else:
raise ImportError('Must have Matplotlib installed. To install, run "pip install matplotlib".')
BASE_DIR = Path(__file__).parent
RESULT_DIR = Path(BASE_DIR) / "circuit_results"
TEST_REFERENCE_DIR = Path(BASE_DIR) / "references"
FAILURE_DIFF_DIR = Path(BASE_DIR).parent / "visual_test_failures"
FAILURE_PREFIX = "circuit_failure_"
class TestCircuitMatplotlibDrawer(QiskitTestCase):
"""Circuit MPL visualization"""
def setUp(self):
super().setUp()
self.threshold = 0.9999
self.circuit_drawer = VisualTestUtilities.save_data_wrap(
circuit_drawer, str(self), RESULT_DIR
)
if not os.path.exists(FAILURE_DIFF_DIR):
os.makedirs(FAILURE_DIFF_DIR)
if not os.path.exists(RESULT_DIR):
os.makedirs(RESULT_DIR)
def tearDown(self):
super().tearDown()
mpl_close("all")
@staticmethod
def _image_path(image_name):
return os.path.join(RESULT_DIR, image_name)
@staticmethod
def _reference_path(image_name):
return os.path.join(TEST_REFERENCE_DIR, image_name)
def test_empty_circuit(self):
"""Test empty circuit"""
circuit = QuantumCircuit()
fname = "empty_circut.png"
self.circuit_drawer(circuit, output="mpl", filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
def test_calibrations(self):
"""Test calibrations annotations
See https://github.com/Qiskit/qiskit-terra/issues/5920
"""
circuit = QuantumCircuit(2, 2)
circuit.h(0)
from qiskit import pulse
with pulse.build(name="hadamard") as h_q0:
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.DriveChannel(0)
)
circuit.add_calibration("h", [0], h_q0)
fname = "calibrations.png"
self.circuit_drawer(circuit, output="mpl", filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
def test_calibrations_with_control_gates(self):
"""Test calibrations annotations
See https://github.com/Qiskit/qiskit-terra/issues/5920
"""
circuit = QuantumCircuit(2, 2)
circuit.cx(0, 1)
circuit.ch(0, 1)
from qiskit import pulse
with pulse.build(name="cnot") as cx_q01:
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.DriveChannel(1)
)
circuit.add_calibration("cx", [0, 1], cx_q01)
with pulse.build(name="ch") as ch_q01:
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.DriveChannel(1)
)
circuit.add_calibration("ch", [0, 1], ch_q01)
fname = "calibrations_with_control_gates.png"
self.circuit_drawer(circuit, output="mpl", filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
def test_calibrations_with_swap_and_reset(self):
"""Test calibrations annotations
See https://github.com/Qiskit/qiskit-terra/issues/5920
"""
circuit = QuantumCircuit(2, 2)
circuit.swap(0, 1)
circuit.reset(0)
from qiskit import pulse
with pulse.build(name="swap") as swap_q01:
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.DriveChannel(1)
)
circuit.add_calibration("swap", [0, 1], swap_q01)
with pulse.build(name="reset") as reset_q0:
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.DriveChannel(1)
)
circuit.add_calibration("reset", [0], reset_q0)
fname = "calibrations_with_swap_and_reset.png"
self.circuit_drawer(circuit, output="mpl", filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
def test_calibrations_with_rzz_and_rxx(self):
"""Test calibrations annotations
See https://github.com/Qiskit/qiskit-terra/issues/5920
"""
circuit = QuantumCircuit(2, 2)
circuit.rzz(pi, 0, 1)
circuit.rxx(pi, 0, 1)
from qiskit import pulse
with pulse.build(name="rzz") as rzz_q01:
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.DriveChannel(1)
)
circuit.add_calibration("rzz", [0, 1], rzz_q01)
with pulse.build(name="rxx") as rxx_q01:
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.DriveChannel(1)
)
circuit.add_calibration("rxx", [0, 1], rxx_q01)
fname = "calibrations_with_rzz_and_rxx.png"
self.circuit_drawer(circuit, output="mpl", filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
def test_no_ops(self):
"""Test circuit with no ops.
See https://github.com/Qiskit/qiskit-terra/issues/5393"""
circuit = QuantumCircuit(2, 3)
fname = "no_op_circut.png"
self.circuit_drawer(circuit, output="mpl", filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
def test_long_name(self):
"""Test to see that long register names can be seen completely
As reported in #2605
"""
# add a register with a very long name
qr = QuantumRegister(4, "veryLongQuantumRegisterName")
# add another to make sure adjustments are made based on longest
qrr = QuantumRegister(1, "q0")
circuit = QuantumCircuit(qr, qrr)
# check gates are shifted over accordingly
circuit.h(qr)
circuit.h(qr)
circuit.h(qr)
fname = "long_name.png"
self.circuit_drawer(circuit, output="mpl", filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
def test_multi_underscore_reg_names(self):
"""Test that multi-underscores in register names display properly"""
q_reg1 = QuantumRegister(1, "q1_re__g__g")
q_reg3 = QuantumRegister(3, "q3_re_g__g")
c_reg1 = ClassicalRegister(1, "c1_re_g__g")
c_reg3 = ClassicalRegister(3, "c3_re_g__g")
circuit = QuantumCircuit(q_reg1, q_reg3, c_reg1, c_reg3)
fname = "multi_underscore_true.png"
self.circuit_drawer(circuit, output="mpl", cregbundle=True, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
fname2 = "multi_underscore_false.png"
self.circuit_drawer(circuit, output="mpl", cregbundle=False, filename=fname2)
ratio2 = VisualTestUtilities._save_diff(
self._image_path(fname2),
self._reference_path(fname2),
fname2,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
self.assertGreaterEqual(ratio2, self.threshold)
def test_conditional(self):
"""Test that circuits with conditionals draw correctly"""
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(2, "c")
circuit = QuantumCircuit(qr, cr)
# check gates are shifted over accordingly
circuit.h(qr)
circuit.measure(qr, cr)
circuit.h(qr[0]).c_if(cr, 2)
fname = "reg_conditional.png"
self.circuit_drawer(circuit, output="mpl", filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
def test_bit_conditional_with_cregbundle(self):
"""Test that circuits with single bit conditionals draw correctly
with cregbundle=True."""
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(2, "c")
circuit = QuantumCircuit(qr, cr)
circuit.x(qr[0])
circuit.measure(qr, cr)
circuit.h(qr[0]).c_if(cr[0], 1)
circuit.x(qr[1]).c_if(cr[1], 0)
fname = "bit_conditional_bundle.png"
self.circuit_drawer(circuit, output="mpl", filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
def test_bit_conditional_no_cregbundle(self):
"""Test that circuits with single bit conditionals draw correctly
with cregbundle=False."""
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(2, "c")
circuit = QuantumCircuit(qr, cr)
circuit.x(qr[0])
circuit.measure(qr, cr)
circuit.h(qr[0]).c_if(cr[0], 1)
circuit.x(qr[1]).c_if(cr[1], 0)
fname = "bit_conditional_no_bundle.png"
self.circuit_drawer(circuit, output="mpl", filename=fname, cregbundle=False)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
def test_plot_partial_barrier(self):
"""Test plotting of partial barriers."""
# generate a circuit with barrier and other barrier like instructions in
q = QuantumRegister(2, "q")
c = ClassicalRegister(2, "c")
circuit = QuantumCircuit(q, c)
# check for barriers
circuit.h(q[0])
circuit.barrier(0)
circuit.h(q[0])
fname = "plot_partial_barrier.png"
self.circuit_drawer(circuit, output="mpl", filename=fname, plot_barriers=True)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
def test_plot_barriers(self):
"""Test to see that plotting barriers works.
If it is set to False, no blank columns are introduced"""
# generate a circuit with barriers and other barrier like instructions in
q = QuantumRegister(2, "q")
c = ClassicalRegister(2, "c")
circuit = QuantumCircuit(q, c)
# check for barriers
circuit.h(q[0])
circuit.barrier()
# check for other barrier like commands
circuit.h(q[1])
# check the barriers plot properly when plot_barriers= True
fname = "plot_barriers_true.png"
self.circuit_drawer(circuit, output="mpl", filename=fname, plot_barriers=True)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
fname2 = "plot_barriers_false.png"
self.circuit_drawer(circuit, output="mpl", filename=fname2, plot_barriers=False)
ratio2 = VisualTestUtilities._save_diff(
self._image_path(fname2),
self._reference_path(fname2),
fname2,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
self.assertGreaterEqual(ratio2, self.threshold)
def test_no_barriers_false(self):
"""Generate the same circuit as test_plot_barriers but without the barrier commands
as this is what the circuit should look like when displayed with plot barriers false"""
q1 = QuantumRegister(2, "q")
c1 = ClassicalRegister(2, "c")
circuit = QuantumCircuit(q1, c1)
circuit.h(q1[0])
circuit.h(q1[1])
fname = "no_barriers.png"
self.circuit_drawer(circuit, output="mpl", filename=fname, plot_barriers=False)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
def test_fold_minus1(self):
"""Test to see that fold=-1 is no folding"""
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(1, "c")
circuit = QuantumCircuit(qr, cr)
for _ in range(3):
circuit.h(0)
circuit.x(0)
fname = "fold_minus1.png"
self.circuit_drawer(circuit, output="mpl", fold=-1, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
def test_fold_4(self):
"""Test to see that fold=4 is folding"""
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(1, "c")
circuit = QuantumCircuit(qr, cr)
for _ in range(3):
circuit.h(0)
circuit.x(0)
fname = "fold_4.png"
self.circuit_drawer(circuit, output="mpl", fold=4, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
def test_big_gates(self):
"""Test large gates with params"""
qr = QuantumRegister(6, "q")
circuit = QuantumCircuit(qr)
circuit.append(IQP([[6, 5, 3], [5, 4, 5], [3, 5, 1]]), [0, 1, 2])
desired_vector = [
1 / math.sqrt(16) * complex(0, 1),
1 / math.sqrt(8) * complex(1, 0),
1 / math.sqrt(16) * complex(1, 1),
0,
0,
1 / math.sqrt(8) * complex(1, 2),
1 / math.sqrt(16) * complex(1, 0),
0,
]
circuit.initialize(desired_vector, [qr[3], qr[4], qr[5]])
circuit.unitary([[1, 0], [0, 1]], [qr[0]])
matrix = np.zeros((4, 4))
theta = Parameter("theta")
circuit.append(HamiltonianGate(matrix, theta), [qr[1], qr[2]])
circuit = circuit.assign_parameters({theta: 1})
circuit.append(Isometry(np.eye(4, 4), 0, 0), list(range(3, 5)))
fname = "big_gates.png"
self.circuit_drawer(circuit, output="mpl", filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
def test_cnot(self):
"""Test different cnot gates (ccnot, mcx, etc)"""
qr = QuantumRegister(6, "q")
circuit = QuantumCircuit(qr)
circuit.x(0)
circuit.cx(0, 1)
circuit.ccx(0, 1, 2)
circuit.append(XGate().control(3, ctrl_state="010"), [qr[2], qr[3], qr[0], qr[1]])
circuit.append(MCXGate(num_ctrl_qubits=3, ctrl_state="101"), [qr[0], qr[1], qr[2], qr[4]])
circuit.append(MCXVChain(3, dirty_ancillas=True), [qr[0], qr[1], qr[2], qr[3], qr[5]])
fname = "cnot.png"
self.circuit_drawer(circuit, output="mpl", filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
def test_cz(self):
"""Test Z and Controlled-Z Gates"""
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
circuit.z(0)
circuit.cz(0, 1)
circuit.append(ZGate().control(3, ctrl_state="101"), [0, 1, 2, 3])
circuit.append(ZGate().control(2), [1, 2, 3])
circuit.append(ZGate().control(1, ctrl_state="0", label="CZ Gate"), [2, 3])
fname = "cz.png"
self.circuit_drawer(circuit, output="mpl", filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
def test_pauli_clifford(self):
"""Test Pauli(green) and Clifford(blue) gates"""
qr = QuantumRegister(5, "q")
circuit = QuantumCircuit(qr)
circuit.x(0)
circuit.y(0)
circuit.z(0)
circuit.id(0)
circuit.h(1)
circuit.cx(1, 2)
circuit.cy(1, 2)
circuit.cz(1, 2)
circuit.swap(3, 4)
circuit.s(3)
circuit.sdg(3)
circuit.iswap(3, 4)
circuit.dcx(3, 4)
fname = "pauli_clifford.png"
self.circuit_drawer(circuit, output="mpl", filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
def test_creg_initial(self):
"""Test cregbundle and initial state options"""
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(2, "c")
circuit = QuantumCircuit(qr, cr)
circuit.x(0)
circuit.h(0)
circuit.x(1)
fname = "creg_initial_true.png"
self.circuit_drawer(
circuit, output="mpl", filename=fname, cregbundle=True, initial_state=True
)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
fname2 = "creg_initial_false.png"
self.circuit_drawer(
circuit, output="mpl", filename=fname2, cregbundle=False, initial_state=False
)
ratio2 = VisualTestUtilities._save_diff(
self._image_path(fname2),
self._reference_path(fname2),
fname2,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
self.assertGreaterEqual(ratio2, self.threshold)
def test_r_gates(self):
"""Test all R gates"""
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
circuit.r(3 * pi / 4, 3 * pi / 8, 0)
circuit.rx(pi / 2, 1)
circuit.ry(-pi / 2, 2)
circuit.rz(3 * pi / 4, 3)
circuit.rxx(pi / 2, 0, 1)
circuit.ryy(3 * pi / 4, 2, 3)
circuit.rzx(-pi / 2, 0, 1)
circuit.rzz(pi / 2, 2, 3)
fname = "r_gates.png"
self.circuit_drawer(circuit, output="mpl", filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
def test_ctrl_labels(self):
"""Test control labels"""
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
circuit.cy(1, 0, label="Bottom Y label")
circuit.cu(pi / 2, pi / 2, pi / 2, 0, 2, 3, label="Top U label")
circuit.ch(0, 1, label="Top H label")
circuit.append(
HGate(label="H gate label").control(3, label="H control label", ctrl_state="010"),
[qr[1], qr[2], qr[3], qr[0]],
)
fname = "ctrl_labels.png"
self.circuit_drawer(circuit, output="mpl", filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
def test_cswap_rzz(self):
"""Test controlled swap and rzz gates"""
qr = QuantumRegister(5, "q")
circuit = QuantumCircuit(qr)
circuit.cswap(0, 1, 2)
circuit.append(RZZGate(3 * pi / 4).control(3, ctrl_state="010"), [2, 1, 4, 3, 0])
fname = "cswap_rzz.png"
self.circuit_drawer(circuit, output="mpl", filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
def test_ghz_to_gate(self):
"""Test controlled GHZ to_gate circuit"""
qr = QuantumRegister(5, "q")
circuit = QuantumCircuit(qr)
ghz_circuit = QuantumCircuit(3, name="this is a WWWWWWWWWWWide name Ctrl-GHZ Circuit")
ghz_circuit.h(0)
ghz_circuit.cx(0, 1)
ghz_circuit.cx(1, 2)
ghz = ghz_circuit.to_gate()
ccghz = ghz.control(2, ctrl_state="10")
circuit.append(ccghz, [4, 0, 1, 3, 2])
fname = "ghz_to_gate.png"
self.circuit_drawer(circuit, output="mpl", filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
def test_scale(self):
"""Tests scale
See: https://github.com/Qiskit/qiskit-terra/issues/4179"""
circuit = QuantumCircuit(5)
circuit.unitary(random_unitary(2**5), circuit.qubits)
fname = "scale_default.png"
self.circuit_drawer(circuit, output="mpl", filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
fname2 = "scale_half.png"
self.circuit_drawer(circuit, output="mpl", filename=fname2, scale=0.5)
ratio2 = VisualTestUtilities._save_diff(
self._image_path(fname2),
self._reference_path(fname2),
fname2,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
fname3 = "scale_double.png"
self.circuit_drawer(circuit, output="mpl", filename=fname3, scale=2)
ratio3 = VisualTestUtilities._save_diff(
self._image_path(fname3),
self._reference_path(fname3),
fname3,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
self.assertGreaterEqual(ratio2, self.threshold)
self.assertGreaterEqual(ratio3, self.threshold)
def test_pi_param_expr(self):
"""Test pi in circuit with parameter expression."""
x, y = Parameter("x"), Parameter("y")
circuit = QuantumCircuit(1)
circuit.rx((pi - x) * (pi - y), 0)
fname = "pi_in_param_expr.png"
self.circuit_drawer(circuit, output="mpl", filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
def test_partial_layout(self):
"""Tests partial_layout
See: https://github.com/Qiskit/qiskit-terra/issues/4757"""
circuit = QuantumCircuit(3)
circuit.h(1)
transpiled = transpile(
circuit,
backend=GenericBackendV2(5, coupling_map=TENERIFE_CMAP),
basis_gates=["id", "cx", "rz", "sx", "x"],
optimization_level=0,
initial_layout=[1, 2, 0],
seed_transpiler=0,
)
fname = "partial_layout.png"
self.circuit_drawer(transpiled, output="mpl", filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
def test_init_reset(self):
"""Test reset and initialize with 1 and 2 qubits"""
circuit = QuantumCircuit(2)
circuit.initialize([0, 1], 0)
circuit.reset(1)
circuit.initialize([0, 1, 0, 0], [0, 1])
fname = "init_reset.png"
self.circuit_drawer(circuit, output="mpl", filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
def test_with_global_phase(self):
"""Tests with global phase"""
circuit = QuantumCircuit(3, global_phase=1.57079632679)
circuit.h(range(3))
fname = "global_phase.png"
self.circuit_drawer(circuit, output="mpl", filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
def test_alternative_colors(self):
"""Tests alternative color schemes"""
for style in ["iqp", "iqp-dark", "textbook", "clifford"]:
with self.subTest(style=style):
circuit = QuantumCircuit(7)
circuit.h(0)
circuit.x(0)
circuit.cx(0, 1)
circuit.ccx(0, 1, 2)
circuit.swap(0, 1)
circuit.iswap(2, 3)
circuit.cswap(0, 1, 2)
circuit.append(SwapGate().control(2), [0, 1, 2, 3])
circuit.dcx(0, 1)
circuit.append(DCXGate().control(1), [0, 1, 2])
circuit.append(DCXGate().control(2), [0, 1, 2, 3])
circuit.z(4)
circuit.s(4)
circuit.sdg(4)
circuit.t(4)
circuit.tdg(4)
circuit.p(pi / 2, 4)
circuit.cz(5, 6)
circuit.cp(pi / 2, 5, 6)
circuit.mcp(pi / 5, [0, 1, 2, 3], 4)
circuit.y(5)
circuit.rx(pi / 3, 5)
circuit.rz(pi / 6, 6)
circuit.rzx(pi / 2, 5, 6)
circuit.rzz(pi / 4, 5, 6)
circuit.u(pi / 2, pi / 2, pi / 2, 5)
circuit.barrier(5, 6)
circuit.reset(5)
fname = f"{style}_color.png"
self.circuit_drawer(circuit, output="mpl", style={"name": style}, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
def test_reverse_bits(self):
"""Tests reverse_bits parameter"""
circuit = QuantumCircuit(3)
circuit.h(0)
circuit.cx(0, 1)
circuit.ccx(2, 1, 0)
fname = "reverse_bits.png"
self.circuit_drawer(circuit, output="mpl", reverse_bits=True, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
def test_bw(self):
"""Tests black and white style parameter"""
circuit = QuantumCircuit(3, 3)
circuit.h(0)
circuit.x(1)
circuit.sdg(2)
circuit.cx(0, 1)
circuit.ccx(2, 1, 0)
circuit.swap(1, 2)
circuit.measure_all()
fname = "bw.png"
self.circuit_drawer(circuit, output="mpl", style={"name": "bw"}, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
def test_user_style(self):
"""Tests loading a user style"""
circuit = QuantumCircuit(7)
circuit.h(0)
circuit.append(HGate(label="H2"), [1])
circuit.x(0)
circuit.cx(0, 1)
circuit.ccx(0, 1, 2)
circuit.swap(0, 1)
circuit.cswap(0, 1, 2)
circuit.append(SwapGate().control(2), [0, 1, 2, 3])
circuit.dcx(0, 1)
circuit.append(DCXGate().control(1), [0, 1, 2])
circuit.append(DCXGate().control(2), [0, 1, 2, 3])
circuit.z(4)
circuit.append(SGate(label="S1"), [4])
circuit.sdg(4)
circuit.t(4)
circuit.tdg(4)
circuit.p(pi / 2, 4)
circuit.cz(5, 6)
circuit.cp(pi / 2, 5, 6)
circuit.y(5)
circuit.rx(pi / 3, 5)
circuit.rzx(pi / 2, 5, 6)
circuit.u(pi / 2, pi / 2, pi / 2, 5)
circuit.barrier(5, 6)
circuit.reset(5)
style = {
"name": "user_style",
"displaytext": {"H2": "H_2"},
"displaycolor": {"H2": ("#EEDD00", "#FF0000")},
}
fname = "user_style.png"
self.circuit_drawer(
circuit,
output="mpl",
style=style,
filename=fname,
)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
with self.subTest(msg="check image"):
self.assertGreaterEqual(ratio, self.threshold)
with self.subTest(msg="check style dict unchanged"):
self.assertEqual(
style,
{
"name": "user_style",
"displaytext": {"H2": "H_2"},
"displaycolor": {"H2": ("#EEDD00", "#FF0000")},
},
)
def test_subfont_change(self):
"""Tests changing the subfont size"""
circuit = QuantumCircuit(3)
circuit.h(0)
circuit.x(0)
circuit.u(pi / 2, pi / 2, pi / 2, 1)
circuit.p(pi / 2, 2)
style = {"name": "iqp", "subfontsize": 11}
fname = "subfont.png"
self.circuit_drawer(circuit, output="mpl", style=style, filename=fname)
self.assertEqual(style, {"name": "iqp", "subfontsize": 11}) # check does not change style
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
def test_meas_condition(self):
"""Tests measure with a condition"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(2, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(qr[0])
circuit.measure(qr[0], cr[0])
circuit.h(qr[1]).c_if(cr, 1)
fname = "meas_condition.png"
self.circuit_drawer(circuit, output="mpl", filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
def test_reverse_bits_condition(self):
"""Tests reverse_bits with a condition and gate above"""
cr = ClassicalRegister(2, "cr")
cr2 = ClassicalRegister(1, "cr2")
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr, cr, cr2)
circuit.h(0)
circuit.h(1)
circuit.h(2)
circuit.x(0)
circuit.x(0)
circuit.measure(2, 1)
circuit.x(2).c_if(cr, 2)
fname = "reverse_bits_cond_true.png"
self.circuit_drawer(
circuit, output="mpl", cregbundle=False, reverse_bits=True, filename=fname
)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
fname2 = "reverse_bits_cond_false.png"
self.circuit_drawer(
circuit, output="mpl", cregbundle=False, reverse_bits=False, filename=fname2
)
ratio2 = VisualTestUtilities._save_diff(
self._image_path(fname2),
self._reference_path(fname2),
fname2,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
self.assertGreaterEqual(ratio2, self.threshold)
def test_style_custom_gates(self):
"""Tests style for custom gates"""
def cnotnot(gate_label):
gate_circuit = QuantumCircuit(3, name=gate_label)
gate_circuit.cx(0, 1)
gate_circuit.cx(0, 2)
gate = gate_circuit.to_gate()
return gate
q = QuantumRegister(3, name="q")
circuit = QuantumCircuit(q)
circuit.append(cnotnot("CNOTNOT"), [q[0], q[1], q[2]])
circuit.append(cnotnot("CNOTNOT_PRIME"), [q[0], q[1], q[2]])
circuit.h(q[0])
fname = "style_custom_gates.png"
self.circuit_drawer(
circuit,
output="mpl",
style={
"displaycolor": {"CNOTNOT": ("#000000", "#FFFFFF"), "h": ("#A1A1A1", "#043812")},
"displaytext": {"CNOTNOT_PRIME": "$\\mathrm{CNOTNOT}'$"},
},
filename=fname,
)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
def test_6095(self):
"""Tests controlled-phase gate style
See https://github.com/Qiskit/qiskit-terra/issues/6095"""
circuit = QuantumCircuit(2)
circuit.cp(1.0, 0, 1)
circuit.h(1)
fname = "6095.png"
self.circuit_drawer(
circuit,
output="mpl",
style={"displaycolor": {"cp": ("#A27486", "#000000"), "h": ("#A27486", "#000000")}},
filename=fname,
)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
def test_instruction_1q_1c(self):
"""Tests q0-cr0 instruction on a circuit"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(2, "cr")
circuit = QuantumCircuit(qr, cr)
inst = QuantumCircuit(1, 1, name="Inst").to_instruction()
circuit.append(inst, [qr[0]], [cr[0]])
fname = "instruction_1q_1c.png"
self.circuit_drawer(circuit, output="mpl", filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
def test_instruction_3q_3c_circ1(self):
"""Tests q0-q1-q2-cr_20-cr0-cr1 instruction on a circuit"""
qr = QuantumRegister(4, "qr")
cr = ClassicalRegister(2, "cr")
cr2 = ClassicalRegister(2, "cr2")
circuit = QuantumCircuit(qr, cr, cr2)
inst = QuantumCircuit(3, 3, name="Inst").to_instruction()
circuit.append(inst, [qr[0], qr[1], qr[2]], [cr2[0], cr[0], cr[1]])
fname = "instruction_3q_3c_circ1.png"
self.circuit_drawer(circuit, output="mpl", filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
def test_instruction_3q_3c_circ2(self):
"""Tests q3-q0-q2-cr0-cr1-cr_20 instruction on a circuit"""
qr = QuantumRegister(4, "qr")
cr = ClassicalRegister(2, "cr")
cr2 = ClassicalRegister(2, "cr2")
circuit = QuantumCircuit(qr, cr, cr2)
inst = QuantumCircuit(3, 3, name="Inst").to_instruction()
circuit.append(inst, [qr[3], qr[0], qr[2]], [cr[0], cr[1], cr2[0]])
fname = "instruction_3q_3c_circ2.png"
self.circuit_drawer(circuit, output="mpl", filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
def test_instruction_3q_3c_circ3(self):
"""Tests q3-q1-q2-cr_31-cr1-cr_30 instruction on a circuit"""
qr = QuantumRegister(4, "qr")
cr = ClassicalRegister(2, "cr")
cr2 = ClassicalRegister(1, "cr2")
cr3 = ClassicalRegister(2, "cr3")
circuit = QuantumCircuit(qr, cr, cr2, cr3)
inst = QuantumCircuit(3, 3, name="Inst").to_instruction()
circuit.append(inst, [qr[3], qr[1], qr[2]], [cr3[1], cr[1], cr3[0]])
fname = "instruction_3q_3c_circ3.png"
self.circuit_drawer(circuit, output="mpl", filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
def test_overwide_gates(self):
"""Test gates don't exceed width of default fold"""
circuit = QuantumCircuit(5)
initial_state = np.zeros(2**5)
initial_state[5] = 1
circuit.initialize(initial_state)
fname = "wide_params.png"
self.circuit_drawer(circuit, output="mpl", filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
def test_one_bit_regs(self):
"""Test registers with only one bit display without number"""
qr1 = QuantumRegister(1, "qr1")
qr2 = QuantumRegister(2, "qr2")
cr1 = ClassicalRegister(1, "cr1")
cr2 = ClassicalRegister(2, "cr2")
circuit = QuantumCircuit(qr1, qr2, cr1, cr2)
circuit.h(0)
circuit.measure(0, 0)
fname = "one_bit_regs.png"
self.circuit_drawer(circuit, output="mpl", cregbundle=False, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
def test_user_ax_subplot(self):
"""Test for when user supplies ax for a subplot"""
import matplotlib.pyplot as plt
fig = plt.figure(1, figsize=(6, 4))
fig.patch.set_facecolor("white")
ax1 = fig.add_subplot(1, 2, 1)
ax2 = fig.add_subplot(1, 2, 2)
ax1.plot([1, 2, 3])
circuit = QuantumCircuit(4)
circuit.h(0)
circuit.cx(0, 1)
circuit.h(1)
circuit.cx(1, 2)
plt.close(fig)
fname = "user_ax.png"
self.circuit_drawer(circuit, output="mpl", ax=ax2, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
def test_figwidth(self):
"""Test style dict 'figwidth'"""
circuit = QuantumCircuit(3)
circuit.h(0)
circuit.cx(0, 1)
circuit.x(1)
circuit.cx(1, 2)
circuit.x(2)
fname = "figwidth.png"
self.circuit_drawer(circuit, output="mpl", style={"figwidth": 5}, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
def test_registerless_one_bit(self):
"""Test circuit with one-bit registers and registerless bits."""
qrx = QuantumRegister(2, "qrx")
qry = QuantumRegister(1, "qry")
crx = ClassicalRegister(2, "crx")
circuit = QuantumCircuit(qrx, [Qubit(), Qubit()], qry, [Clbit(), Clbit()], crx)
fname = "registerless_one_bit.png"
self.circuit_drawer(circuit, output="mpl", filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
def test_measures_with_conditions(self):
"""Test that a measure containing a condition displays"""
qr = QuantumRegister(2, "qr")
cr1 = ClassicalRegister(2, "cr1")
cr2 = ClassicalRegister(2, "cr2")
circuit = QuantumCircuit(qr, cr1, cr2)
circuit.h(0)
circuit.h(1)
circuit.measure(0, cr1[1])
circuit.measure(1, cr2[0]).c_if(cr1, 1)
circuit.h(0).c_if(cr2, 3)
fname = "measure_cond_false.png"
self.circuit_drawer(circuit, output="mpl", cregbundle=False, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
fname2 = "measure_cond_true.png"
self.circuit_drawer(circuit, output="mpl", cregbundle=True, filename=fname2)
ratio2 = VisualTestUtilities._save_diff(
self._image_path(fname2),
self._reference_path(fname2),
fname2,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
self.assertGreaterEqual(ratio2, self.threshold)
def test_conditions_measures_with_bits(self):
"""Test that gates with conditions and measures work with bits"""
bits = [Qubit(), Qubit(), Clbit(), Clbit()]
cr = ClassicalRegister(2, "cr")
crx = ClassicalRegister(3, "cs")
circuit = QuantumCircuit(bits, cr, [Clbit()], crx)
circuit.x(0).c_if(crx[1], 0)
circuit.measure(0, bits[3])
fname = "measure_cond_bits_false.png"
self.circuit_drawer(circuit, output="mpl", cregbundle=False, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
fname2 = "measure_cond_bits_true.png"
self.circuit_drawer(circuit, output="mpl", cregbundle=True, filename=fname2)
ratio2 = VisualTestUtilities._save_diff(
self._image_path(fname2),
self._reference_path(fname2),
fname2,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
self.assertGreaterEqual(ratio2, self.threshold)
def test_conditional_gates_right_of_measures_with_bits(self):
"""Test that gates with conditions draw to right of measures when same bit"""
qr = QuantumRegister(3, "qr")
cr = ClassicalRegister(2, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(qr[0])
circuit.measure(qr[0], cr[1])
circuit.h(qr[1]).c_if(cr[1], 0)
circuit.h(qr[2]).c_if(cr[0], 0)
fname = "measure_cond_bits_right.png"
self.circuit_drawer(circuit, output="mpl", cregbundle=False, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
def test_conditions_with_bits_reverse(self):
"""Test that gates with conditions work with bits reversed"""
bits = [Qubit(), Qubit(), Clbit(), Clbit()]
cr = ClassicalRegister(2, "cr")
crx = ClassicalRegister(2, "cs")
circuit = QuantumCircuit(bits, cr, [Clbit()], crx)
circuit.x(0).c_if(bits[3], 0)
fname = "cond_bits_reverse.png"
self.circuit_drawer(
circuit, output="mpl", cregbundle=False, reverse_bits=True, filename=fname
)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
def test_sidetext_with_condition(self):
"""Test that sidetext gates align properly with conditions"""
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(2, "c")
circuit = QuantumCircuit(qr, cr)
circuit.append(CPhaseGate(pi / 2), [qr[0], qr[1]]).c_if(cr[1], 1)
fname = "sidetext_condition.png"
self.circuit_drawer(circuit, output="mpl", cregbundle=False, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
def test_fold_with_conditions(self):
"""Test that gates with conditions draw correctly when folding"""
qr = QuantumRegister(3, "qr")
cr = ClassicalRegister(5, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 1)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 3)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 5)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 7)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 9)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 11)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 13)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 15)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 17)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 19)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 21)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 23)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 25)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 27)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 29)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 31)
fname = "fold_with_conditions.png"
self.circuit_drawer(circuit, output="mpl", cregbundle=False, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
def test_idle_wires_barrier(self):
"""Test that idle_wires False works with barrier"""
circuit = QuantumCircuit(4, 4)
circuit.x(2)
circuit.barrier()
fname = "idle_wires_barrier.png"
self.circuit_drawer(circuit, output="mpl", cregbundle=False, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
def test_wire_order(self):
"""Test the wire_order option"""
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(4, "c")
cr2 = ClassicalRegister(2, "cx")
circuit = QuantumCircuit(qr, cr, cr2)
circuit.h(0)
circuit.h(3)
circuit.x(1)
circuit.x(3).c_if(cr, 10)
fname = "wire_order.png"
self.circuit_drawer(
circuit,
output="mpl",
cregbundle=False,
wire_order=[2, 1, 3, 0, 6, 8, 9, 5, 4, 7],
filename=fname,
)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
def test_barrier_label(self):
"""Test the barrier label"""
circuit = QuantumCircuit(2)
circuit.x(0)
circuit.y(1)
circuit.barrier()
circuit.y(0)
circuit.x(1)
circuit.barrier(label="End Y/X")
fname = "barrier_label.png"
self.circuit_drawer(circuit, output="mpl", filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
def test_if_op(self):
"""Test the IfElseOp with if only"""
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(2, "cr")
circuit = QuantumCircuit(qr, cr)
with circuit.if_test((cr[1], 1)):
circuit.h(0)
circuit.cx(0, 1)
fname = "if_op.png"
self.circuit_drawer(circuit, output="mpl", cregbundle=False, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
def test_if_else_op_bundle_false(self):
"""Test the IfElseOp with else with cregbundle False"""
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(2, "cr")
circuit = QuantumCircuit(qr, cr)
with circuit.if_test((cr[1], 1)) as _else:
circuit.h(0)
circuit.cx(0, 1)
with _else:
circuit.cx(0, 1)
fname = "if_else_op_false.png"
self.circuit_drawer(circuit, output="mpl", cregbundle=False, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
def test_if_else_op_bundle_true(self):
"""Test the IfElseOp with else with cregbundle True"""
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(2, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(0)
with circuit.if_test((cr[1], 1)) as _else:
circuit.h(0)
circuit.cx(0, 1)
with _else:
circuit.cx(0, 1)
fname = "if_else_op_true.png"
self.circuit_drawer(circuit, output="mpl", cregbundle=True, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
def test_if_else_op_textbook_style(self):
"""Test the IfElseOp with else in textbook style"""
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(2, "cr")
circuit = QuantumCircuit(qr, cr)
with circuit.if_test((cr[1], 1)) as _else:
circuit.h(0)
circuit.cx(0, 1)
with _else:
circuit.cx(0, 1)
fname = "if_else_op_textbook.png"
self.circuit_drawer(
circuit, output="mpl", style="textbook", cregbundle=False, filename=fname
)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
def test_if_else_with_body(self):
"""Test the IfElseOp with adding a body manually"""
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(3, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(0)
circuit.h(1)
circuit.measure(0, 1)
circuit.measure(1, 2)
circuit.x(2)
circuit.x(2, label="XLabel").c_if(cr, 2)
qr2 = QuantumRegister(3, "qr2")
qc2 = QuantumCircuit(qr2, cr)
qc2.x(1)
qc2.y(1)
qc2.z(0)
qc2.x(0, label="X1i").c_if(cr, 4)
circuit.if_else((cr[1], 1), qc2, None, [0, 1, 2], [0, 1, 2])
circuit.x(0, label="X1i")
fname = "if_else_body.png"
self.circuit_drawer(circuit, output="mpl", cregbundle=False, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
def test_if_else_op_nested(self):
"""Test the IfElseOp with complex nested if/else"""
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(3, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(0)
with circuit.if_test((cr[1], 1)) as _else:
circuit.x(0, label="X c_if").c_if(cr, 4)
with circuit.if_test((cr[2], 1)):
circuit.z(0)
circuit.y(1)
with circuit.if_test((cr[1], 1)):
circuit.y(1)
circuit.z(2)
with circuit.if_test((cr[2], 1)):
circuit.cx(0, 1)
with circuit.if_test((cr[1], 1)):
circuit.h(0)
circuit.x(1)
with _else:
circuit.y(1)
with circuit.if_test((cr[2], 1)):
circuit.x(0)
circuit.x(1)
inst = QuantumCircuit(2, 2, name="Inst").to_instruction()
circuit.append(inst, [qr[0], qr[1]], [cr[0], cr[1]])
circuit.x(0)
fname = "if_else_op_nested.png"
self.circuit_drawer(circuit, output="mpl", cregbundle=True, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
def test_if_else_op_wire_order(self):
"""Test the IfElseOp with complex nested if/else and wire_order"""
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(3, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(0)
with circuit.if_test((cr[1], 1)) as _else:
circuit.x(0, label="X c_if").c_if(cr, 4)
with circuit.if_test((cr[2], 1)):
circuit.z(0)
circuit.y(1)
with circuit.if_test((cr[1], 1)):
circuit.y(1)
circuit.z(2)
with circuit.if_test((cr[2], 1)):
circuit.cx(0, 1)
with circuit.if_test((cr[1], 1)):
circuit.h(0)
circuit.x(1)
with _else:
circuit.y(1)
with circuit.if_test((cr[2], 1)):
circuit.x(0)
circuit.x(1)
inst = QuantumCircuit(2, 2, name="Inst").to_instruction()
circuit.append(inst, [qr[0], qr[1]], [cr[0], cr[1]])
circuit.x(0)
fname = "if_else_op_wire_order.png"
self.circuit_drawer(
circuit,
output="mpl",
cregbundle=False,
wire_order=[2, 0, 3, 1, 4, 5, 6],
filename=fname,
)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
def test_if_else_op_fold(self):
"""Test the IfElseOp with complex nested if/else and fold"""
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(3, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(0)
with circuit.if_test((cr[1], 1)) as _else:
circuit.x(0, label="X c_if").c_if(cr, 4)
with circuit.if_test((cr[2], 1)):
circuit.z(0)
circuit.y(1)
with circuit.if_test((cr[1], 1)):
circuit.y(1)
circuit.z(2)
with circuit.if_test((cr[2], 1)):
circuit.cx(0, 1)
with circuit.if_test((cr[1], 1)):
circuit.h(0)
circuit.x(1)
with _else:
circuit.y(1)
with circuit.if_test((cr[2], 1)):
circuit.x(0)
circuit.x(1)
inst = QuantumCircuit(2, 2, name="Inst").to_instruction()
circuit.append(inst, [qr[0], qr[1]], [cr[0], cr[1]])
circuit.x(0)
fname = "if_else_op_fold.png"
self.circuit_drawer(circuit, output="mpl", fold=7, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
def test_while_loop_op(self):
"""Test the WhileLoopOp"""
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(3, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(0)
circuit.measure(0, 2)
with circuit.while_loop((cr[0], 0)):
circuit.h(0)
circuit.cx(0, 1)
circuit.measure(0, 0)
with circuit.if_test((cr[2], 1)):
circuit.x(0)
fname = "while_loop.png"
self.circuit_drawer(circuit, output="mpl", cregbundle=False, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
def test_for_loop_op(self):
"""Test the ForLoopOp"""
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(3, "cr")
circuit = QuantumCircuit(qr, cr)
a = Parameter("a")
circuit.h(0)
circuit.measure(0, 2)
with circuit.for_loop((2, 4, 8, 16), loop_parameter=a):
circuit.h(0)
circuit.cx(0, 1)
circuit.rx(pi / a, 1)
circuit.measure(0, 0)
with circuit.if_test((cr[2], 1)):
circuit.z(0)
fname = "for_loop.png"
self.circuit_drawer(circuit, output="mpl", cregbundle=False, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
def test_for_loop_op_range(self):
"""Test the ForLoopOp with a range"""
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(3, "cr")
circuit = QuantumCircuit(qr, cr)
a = Parameter("a")
circuit.h(0)
circuit.measure(0, 2)
with circuit.for_loop(range(10, 20), loop_parameter=a):
circuit.h(0)
circuit.cx(0, 1)
circuit.rx(pi / a, 1)
circuit.measure(0, 0)
with circuit.if_test((cr[2], 1)):
circuit.z(0)
fname = "for_loop_range.png"
self.circuit_drawer(circuit, output="mpl", cregbundle=False, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
def test_for_loop_op_1_qarg(self):
"""Test the ForLoopOp with 1 qarg"""
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(3, "cr")
circuit = QuantumCircuit(qr, cr)
a = Parameter("a")
circuit.h(0)
circuit.measure(0, 2)
with circuit.for_loop((2, 4, 8, 16), loop_parameter=a):
circuit.h(0)
circuit.rx(pi / a, 0)
circuit.measure(0, 0)
with circuit.if_test((cr[2], 1)):
circuit.z(0)
fname = "for_loop_1_qarg.png"
self.circuit_drawer(circuit, output="mpl", cregbundle=False, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
def test_switch_case_op(self):
"""Test the SwitchCaseOp"""
qreg = QuantumRegister(3, "q")
creg = ClassicalRegister(3, "cr")
circuit = QuantumCircuit(qreg, creg)
circuit.h([0, 1, 2])
circuit.measure([0, 1, 2], [0, 1, 2])
with circuit.switch(creg) as case:
with case(0, 1, 2):
circuit.x(0)
with case(3, 4, 5):
circuit.y(1)
circuit.y(0)
circuit.y(0)
with case(case.DEFAULT):
circuit.cx(0, 1)
circuit.h(0)
fname = "switch_case.png"
self.circuit_drawer(circuit, output="mpl", cregbundle=False, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
def test_switch_case_op_1_qarg(self):
"""Test the SwitchCaseOp with 1 qarg"""
qreg = QuantumRegister(3, "q")
creg = ClassicalRegister(3, "cr")
circuit = QuantumCircuit(qreg, creg)
circuit.h([0, 1, 2])
circuit.measure([0, 1, 2], [0, 1, 2])
with circuit.switch(creg) as case:
with case(0, 1, 2):
circuit.x(0)
with case(case.DEFAULT):
circuit.y(0)
circuit.h(0)
fname = "switch_case_1_qarg.png"
self.circuit_drawer(circuit, output="mpl", cregbundle=False, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
def test_switch_case_op_empty_default(self):
"""Test the SwitchCaseOp with empty default case"""
qreg = QuantumRegister(3, "q")
creg = ClassicalRegister(3, "cr")
circuit = QuantumCircuit(qreg, creg)
circuit.h([0, 1, 2])
circuit.measure([0, 1, 2], [0, 1, 2])
with circuit.switch(creg) as case:
with case(0, 1, 2):
circuit.x(0)
with case(case.DEFAULT):
pass
circuit.h(0)
fname = "switch_case_empty_default.png"
self.circuit_drawer(circuit, output="mpl", cregbundle=False, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
def test_if_with_expression(self):
"""Test the IfElseOp with an expression"""
qr = QuantumRegister(3, "qr")
cr = ClassicalRegister(3, "cr")
cr1 = ClassicalRegister(3, "cr1")
cr2 = ClassicalRegister(3, "cr2")
cr3 = ClassicalRegister(3, "cr3")
circuit = QuantumCircuit(qr, cr, cr1, cr2, cr3)
circuit.h(0)
with circuit.if_test(expr.equal(expr.bit_and(cr1, expr.bit_and(cr2, cr3)), 3)):
circuit.z(0)
fname = "if_op_expr.png"
self.circuit_drawer(circuit, output="mpl", filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
def test_if_with_expression_nested(self):
"""Test the IfElseOp with an expression for nested"""
qr = QuantumRegister(3, "qr")
cr = ClassicalRegister(3, "cr")
cr1 = ClassicalRegister(3, "cr1")
cr2 = ClassicalRegister(3, "cr2")
cr3 = ClassicalRegister(3, "cr3")
circuit = QuantumCircuit(qr, cr, cr1, cr2, cr3)
circuit.h(0)
with circuit.if_test(expr.equal(expr.bit_and(cr1, expr.bit_and(cr2, cr3)), 3)):
circuit.x(0)
with circuit.if_test(expr.equal(expr.bit_and(cr3, expr.bit_and(cr1, cr2)), 5)):
circuit.z(1)
fname = "if_op_expr_nested.png"
self.circuit_drawer(circuit, output="mpl", filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
def test_switch_with_expression(self):
"""Test the SwitchCaseOp with an expression"""
qr = QuantumRegister(3, "qr")
cr = ClassicalRegister(3, "cr")
cr1 = ClassicalRegister(3, "cr1")
cr2 = ClassicalRegister(3, "cr2")
cr3 = ClassicalRegister(3, "cr3")
circuit = QuantumCircuit(qr, cr, cr1, cr2, cr3)
circuit.h(0)
with circuit.switch(expr.bit_and(cr1, expr.bit_and(cr2, cr3))) as case:
with case(0, 1, 2, 3):
circuit.x(0)
with case(case.DEFAULT):
circuit.cx(0, 1)
fname = "switch_expr.png"
self.circuit_drawer(circuit, output="mpl", filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
def test_control_flow_layout(self):
"""Test control flow with a layout set."""
qreg = QuantumRegister(2, "qr")
creg = ClassicalRegister(2, "cr")
qc = QuantumCircuit(qreg, creg)
qc.h([0, 1])
qc.h([0, 1])
qc.h([0, 1])
qc.measure([0, 1], [0, 1])
with qc.switch(creg) as case:
with case(0):
qc.z(0)
with case(1, 2):
qc.cx(0, 1)
with case(case.DEFAULT):
qc.h(0)
backend = GenericBackendV2(5, coupling_map=YORKTOWN_CMAP, seed=16)
backend.target.add_instruction(SwitchCaseOp, name="switch_case")
tqc = transpile(qc, backend, optimization_level=2, seed_transpiler=671_42)
fname = "layout_control_flow.png"
self.circuit_drawer(tqc, output="mpl", filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
def test_control_flow_nested_layout(self):
"""Test nested control flow with a layout set."""
qreg = QuantumRegister(2, "qr")
creg = ClassicalRegister(2, "cr")
qc = QuantumCircuit(qreg, creg)
qc.h([0, 1])
qc.h([0, 1])
qc.h([0, 1])
qc.measure([0, 1], [0, 1])
with qc.switch(creg) as case:
with case(0):
qc.z(0)
with case(1, 2):
with qc.if_test((creg[0], 0)):
qc.cx(0, 1)
with case(case.DEFAULT):
with qc.if_test((creg[1], 0)):
qc.h(0)
backend = GenericBackendV2(5, coupling_map=YORKTOWN_CMAP, seed=0)
backend.target.add_instruction(SwitchCaseOp, name="switch_case")
backend.target.add_instruction(IfElseOp, name="if_else")
tqc = transpile(qc, backend, optimization_level=2, seed_transpiler=671_42)
fname = "nested_layout_control_flow.png"
self.circuit_drawer(tqc, output="mpl", filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
def test_control_flow_with_fold_minus_one(self):
"""Test control flow works with fold=-1. Qiskit issue #12012"""
qreg = QuantumRegister(2, "qr")
creg = ClassicalRegister(2, "cr")
circuit = QuantumCircuit(qreg, creg)
with circuit.if_test((creg[1], 1)):
circuit.h(0)
circuit.cx(0, 1)
fname = "control_flow_fold_minus_one.png"
self.circuit_drawer(circuit, output="mpl", filename=fname, fold=-1)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
def test_annotated_operation(self):
"""Test AnnotatedOperations and other non-Instructions."""
circuit = QuantumCircuit(3)
cliff = random_clifford(2)
circuit.append(cliff, [0, 1])
circuit.x(0)
circuit.h(1)
circuit.append(SGate().control(2, ctrl_state=1), [0, 2, 1])
circuit.ccx(0, 1, 2)
op1 = AnnotatedOperation(
SGate(), [InverseModifier(), ControlModifier(2, 1), PowerModifier(3.29)]
)
circuit.append(op1, [0, 1, 2])
circuit.append(SXGate(), [1])
fname = "annotated.png"
self.circuit_drawer(circuit, output="mpl", filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
def test_no_qreg_names_after_layout(self):
"""Test that full register names are not shown after transpilation.
See https://github.com/Qiskit/qiskit-terra/issues/11038"""
backend = GenericBackendV2(5, coupling_map=YORKTOWN_CMAP, seed=42)
qc = QuantumCircuit(3)
qc.cx(0, 1)
qc.cx(1, 2)
qc.cx(2, 0)
circuit = transpile(
qc, backend, basis_gates=["rz", "sx", "cx"], layout_method="sabre", seed_transpiler=42
)
fname = "qreg_names_after_layout.png"
self.circuit_drawer(circuit, output="mpl", filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
def test_if_else_standalone_var(self):
"""Test if/else with standalone Var."""
a = expr.Var.new("a", types.Uint(8))
qc = QuantumCircuit(2, 2, inputs=[a])
b = qc.add_var("b", False)
qc.store(a, 128)
with qc.if_test(expr.logic_not(b)):
# Mix old-style and new-style.
with qc.if_test(expr.equal(b, qc.clbits[0])):
qc.cx(0, 1)
c = qc.add_var("c", b)
with qc.if_test(expr.logic_and(c, expr.equal(a, 128))):
qc.h(0)
fname = "if_else_standalone_var.png"
self.circuit_drawer(qc, output="mpl", filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
def test_switch_standalone_var(self):
"""Test switch with standalone Var."""
a = expr.Var.new("a", types.Uint(8))
qc = QuantumCircuit(2, 2, inputs=[a])
b = qc.add_var("b", expr.lift(5, a.type))
with qc.switch(expr.bit_not(a)) as case:
with case(0):
with qc.switch(b) as case2:
with case2(2):
qc.cx(0, 1)
with case2(case2.DEFAULT):
qc.cx(1, 0)
with case(case.DEFAULT):
c = qc.add_var("c", expr.equal(a, b))
with qc.if_test(c):
qc.h(0)
fname = "switch_standalone_var.png"
self.circuit_drawer(qc, output="mpl", filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, self.threshold)
if __name__ == "__main__":
unittest.main(verbosity=1)
| qiskit/test/visual/mpl/circuit/test_circuit_matplotlib_drawer.py/0 | {
"file_path": "qiskit/test/visual/mpl/circuit/test_circuit_matplotlib_drawer.py",
"repo_id": "qiskit",
"token_count": 41081
} | 338 |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020, 2024.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for graph MPL drawer"""
import unittest
import os
from contextlib import contextmanager
from pathlib import Path
from qiskit import QuantumCircuit
from qiskit.utils import optionals
from qiskit.visualization.state_visualization import state_drawer
from qiskit.visualization.counts_visualization import plot_histogram
from qiskit.visualization.gate_map import plot_gate_map, plot_coupling_map
from qiskit.providers.fake_provider import GenericBackendV2
from qiskit.quantum_info import Statevector
from test import QiskitTestCase # pylint: disable=wrong-import-order
from test.visual import VisualTestUtilities # pylint: disable=wrong-import-order
from test.python.legacy_cmaps import ( # pylint: disable=wrong-import-order
YORKTOWN_CMAP,
LAGOS_CMAP,
RUESCHLIKON_CMAP,
MUMBAI_CMAP,
MANHATTAN_CMAP,
)
if optionals.HAS_MATPLOTLIB:
from matplotlib.pyplot import close as mpl_close
else:
raise ImportError('Must have Matplotlib installed. To install, run "pip install matplotlib".')
BASE_DIR = Path(__file__).parent
RESULT_DIR = Path(BASE_DIR) / "graph_results"
TEST_REFERENCE_DIR = Path(BASE_DIR) / "references"
FAILURE_DIFF_DIR = Path(BASE_DIR).parent / "visual_test_failures"
FAILURE_PREFIX = "graph_failure_"
@contextmanager
def cwd(path):
"""A context manager to run in a particular path"""
oldpwd = os.getcwd()
os.chdir(path)
try:
yield
finally:
os.chdir(oldpwd)
class TestGraphMatplotlibDrawer(QiskitTestCase):
"""Graph MPL visualization"""
def setUp(self):
super().setUp()
self.graph_state_drawer = VisualTestUtilities.save_data_wrap(
state_drawer, str(self), RESULT_DIR
)
self.graph_count_drawer = VisualTestUtilities.save_data_wrap(
plot_histogram, str(self), RESULT_DIR
)
self.graph_plot_gate_map = VisualTestUtilities.save_data_wrap(
plot_gate_map, str(self), RESULT_DIR
)
self.graph_plot_coupling_map = VisualTestUtilities.save_data_wrap(
plot_coupling_map, str(self), RESULT_DIR
)
if not os.path.exists(FAILURE_DIFF_DIR):
os.makedirs(FAILURE_DIFF_DIR)
if not os.path.exists(RESULT_DIR):
os.makedirs(RESULT_DIR)
def tearDown(self):
super().tearDown()
mpl_close("all")
@staticmethod
def _image_path(image_name):
return os.path.join(RESULT_DIR, image_name)
@staticmethod
def _reference_path(image_name):
return os.path.join(TEST_REFERENCE_DIR, image_name)
def test_plot_bloch_multivector(self):
"""test bloch sphere
See https://github.com/Qiskit/qiskit-terra/issues/6397.
"""
circuit = QuantumCircuit(1)
circuit.h(0)
# getting the state using quantum_info
state = Statevector(circuit)
fname = "bloch_multivector.png"
self.graph_state_drawer(state=state, output="bloch", filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_plot_state_hinton(self):
"""test plot_state_hinton"""
circuit = QuantumCircuit(1)
circuit.x(0)
# getting the state using quantum_info
state = Statevector(circuit)
fname = "hinton.png"
self.graph_state_drawer(state=state, output="hinton", filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_plot_state_qsphere(self):
"""test for plot_state_qsphere"""
circuit = QuantumCircuit(1)
circuit.x(0)
# getting the state using quantum_info
state = Statevector(circuit)
fname = "qsphere.png"
self.graph_state_drawer(state=state, output="qsphere", filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_plot_state_city(self):
"""test for plot_state_city"""
circuit = QuantumCircuit(1)
circuit.x(0)
# getting the state using quantum_info
state = Statevector(circuit)
fname = "state_city.png"
self.graph_state_drawer(state=state, output="city", filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_plot_state_paulivec(self):
"""test for plot_state_paulivec"""
circuit = QuantumCircuit(1)
circuit.x(0)
# getting the state using quantum_info
state = Statevector(circuit)
fname = "paulivec.png"
self.graph_state_drawer(state=state, output="paulivec", filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_plot_histogram(self):
"""for testing the plot_histogram"""
# specifing counts because we do not want oscillation of
# result until a changes is made to plot_histogram
counts = {"11": 500, "00": 500}
fname = "histogram.png"
self.graph_count_drawer(counts, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_plot_histogram_with_rest(self):
"""test plot_histogram with 2 datasets and number_to_keep"""
data = [{"00": 3, "01": 5, "10": 6, "11": 12}]
fname = "histogram_with_rest.png"
self.graph_count_drawer(data, number_to_keep=2, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_plot_histogram_2_sets_with_rest(self):
"""test plot_histogram with 2 datasets and number_to_keep"""
data = [
{"00": 3, "01": 5, "10": 6, "11": 12},
{"00": 5, "01": 7, "10": 6, "11": 12},
]
fname = "histogram_2_sets_with_rest.png"
self.graph_count_drawer(data, number_to_keep=2, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_plot_histogram_color(self):
"""Test histogram with single color"""
counts = {"00": 500, "11": 500}
fname = "histogram_color.png"
self.graph_count_drawer(data=counts, color="#204940", filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_plot_histogram_multiple_colors(self):
"""Test histogram with multiple custom colors"""
counts = [
{"00": 10, "01": 15, "10": 20, "11": 25},
{"00": 25, "01": 20, "10": 15, "11": 10},
]
fname = "histogram_multiple_colors.png"
self.graph_count_drawer(
data=counts,
color=["#204940", "#c26219"],
filename=fname,
)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_plot_histogram_hamming(self):
"""Test histogram with hamming distance"""
counts = {"101": 500, "010": 500, "001": 500, "100": 500}
fname = "histogram_hamming.png"
self.graph_count_drawer(data=counts, sort="hamming", target_string="101", filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_plot_histogram_value_sort(self):
"""Test histogram with sorting by value"""
counts = {"101": 300, "010": 240, "001": 80, "100": 150, "110": 160, "000": 280, "111": 60}
fname = "histogram_value_sort.png"
self.graph_count_drawer(data=counts, sort="value", target_string="000", filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_plot_histogram_desc_value_sort(self):
"""Test histogram with sorting by descending value"""
counts = {"101": 150, "010": 50, "001": 180, "100": 10, "110": 190, "000": 80, "111": 260}
fname = "histogram_desc_value_sort.png"
self.graph_count_drawer(
data=counts,
sort="value_desc",
target_string="000",
filename=fname,
)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_plot_histogram_legend(self):
"""Test histogram with legend"""
counts = [{"0": 50, "1": 30}, {"0": 30, "1": 40}]
fname = "histogram_legend.png"
self.graph_count_drawer(
data=counts,
legend=["first", "second"],
filename=fname,
figsize=(15, 5),
)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_plot_histogram_title(self):
"""Test histogram with title"""
counts = [{"0": 50, "1": 30}, {"0": 30, "1": 40}]
fname = "histogram_title.png"
self.graph_count_drawer(data=counts, title="My Histogram", filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_plot_1_qubit_gate_map(self):
"""Test plot_gate_map using 1 qubit backend"""
# getting the mock backend from FakeProvider
backend = GenericBackendV2(num_qubits=1, basis_gates=["id", "rz", "sx", "x"])
fname = "1_qubit_gate_map.png"
self.graph_plot_gate_map(backend=backend, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_plot_5_qubit_gate_map(self):
"""Test plot_gate_map using 5 qubit backend"""
# getting the mock backend from FakeProvider
backend = GenericBackendV2(num_qubits=5, coupling_map=YORKTOWN_CMAP)
fname = "5_qubit_gate_map.png"
self.graph_plot_gate_map(backend=backend, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_plot_7_qubit_gate_map(self):
"""Test plot_gate_map using 7 qubit backend"""
# getting the mock backend from FakeProvider
backend = GenericBackendV2(num_qubits=7, coupling_map=LAGOS_CMAP)
fname = "7_qubit_gate_map.png"
self.graph_plot_gate_map(backend=backend, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_plot_16_qubit_gate_map(self):
"""Test plot_gate_map using 16 qubit backend"""
# getting the mock backend from FakeProvider
backend = GenericBackendV2(num_qubits=16, coupling_map=RUESCHLIKON_CMAP)
fname = "16_qubit_gate_map.png"
self.graph_plot_gate_map(backend=backend, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_plot_27_qubit_gate_map(self):
"""Test plot_gate_map using 27 qubit backend"""
# getting the mock backend from FakeProvider
backend = GenericBackendV2(num_qubits=27, coupling_map=MUMBAI_CMAP)
fname = "27_qubit_gate_map.png"
self.graph_plot_gate_map(backend=backend, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_plot_65_qubit_gate_map(self):
"""test for plot_gate_map using 65 qubit backend"""
# getting the mock backend from FakeProvider
backend = GenericBackendV2(num_qubits=65, coupling_map=MANHATTAN_CMAP)
fname = "65_qubit_gate_map.png"
self.graph_plot_gate_map(backend=backend, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_figsize(self):
"""Test figsize parameter of plot_gate_map"""
# getting the mock backend from FakeProvider
backend = GenericBackendV2(num_qubits=5, coupling_map=YORKTOWN_CMAP)
fname = "figsize.png"
self.graph_plot_gate_map(backend=backend, figsize=(10, 10), filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_qubit_size(self):
"""Test qubit_size parameter of plot_gate_map"""
# getting the mock backend from FakeProvider
backend = GenericBackendV2(num_qubits=5, coupling_map=YORKTOWN_CMAP)
fname = "qubit_size.png"
self.graph_plot_gate_map(backend=backend, qubit_size=38, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_qubit_color(self):
"""Test qubit_color parameter of plot_gate_map"""
# getting the mock backend from FakeProvider
backend = GenericBackendV2(num_qubits=7, coupling_map=LAGOS_CMAP)
fname = "qubit_color.png"
self.graph_plot_gate_map(backend=backend, qubit_color=["#ff0000"] * 7, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_qubit_labels(self):
"""Test qubit_labels parameter of plot_gate_map"""
# getting the mock backend from FakeProvider
backend = GenericBackendV2(num_qubits=7, coupling_map=LAGOS_CMAP)
fname = "qubit_labels.png"
self.graph_plot_gate_map(
backend=backend, qubit_labels=list(range(10, 17, 1)), filename=fname
)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_line_color(self):
"""Test line_color parameter of plot_gate_map"""
# getting the mock backend from FakeProvider
backend = GenericBackendV2(num_qubits=65, coupling_map=MANHATTAN_CMAP)
fname = "line_color.png"
self.graph_plot_gate_map(backend=backend, line_color=["#00ff00"] * 144, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_font_color(self):
"""Test font_color parameter of plot_gate_map"""
# getting the mock backend from FakeProvider
backend = GenericBackendV2(num_qubits=65, coupling_map=MANHATTAN_CMAP)
fname = "font_color.png"
self.graph_plot_gate_map(backend=backend, font_color="#ff00ff", filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_plot_coupling_map(self):
"""Test plot_coupling_map"""
num_qubits = 5
qubit_coordinates = [[1, 0], [0, 1], [1, 1], [1, 2], [2, 1]]
coupling_map = [[1, 0], [1, 2], [1, 3], [3, 4]]
fname = "coupling_map.png"
self.graph_plot_coupling_map(
num_qubits=num_qubits,
qubit_coordinates=qubit_coordinates,
coupling_map=coupling_map,
filename=fname,
)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_plot_bloch_multivector_figsize_improvements(self):
"""test bloch sphere figsize, font_size, title_font_size and title_pad
See https://github.com/Qiskit/qiskit-terra/issues/7263
and https://github.com/Qiskit/qiskit-terra/pull/7264.
"""
circuit = QuantumCircuit(3)
circuit.h(1)
circuit.sxdg(2)
# getting the state using quantum_info
state = Statevector(circuit)
fname = "bloch_multivector_figsize_improvements.png"
self.graph_state_drawer(
state=state,
output="bloch",
figsize=(3, 2),
font_size=10,
title="|0+R> state",
title_font_size=14,
title_pad=8,
filename=fname,
)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
if __name__ == "__main__":
unittest.main(verbosity=1)
| qiskit/test/visual/mpl/graph/test_graph_matplotlib_drawer.py/0 | {
"file_path": "qiskit/test/visual/mpl/graph/test_graph_matplotlib_drawer.py",
"repo_id": "qiskit",
"token_count": 10266
} | 339 |
[tox]
minversion = 4.0
envlist = py38, py39, py310, py311, py312, lint-incr
isolated_build = true
[testenv]
# The colons in the substitutions below let us re-use the `install_command` in
# places where `tox` doesn't automatically fill in those values.
install_command = pip install -c{toxinidir}/constraints.txt -U {opts:} {packages:}
setenv =
VIRTUAL_ENV={envdir}
LANGUAGE=en_US
LC_ALL=en_US.utf-8
ARGS="-V"
QISKIT_SUPRESS_PACKAGING_WARNINGS=Y
QISKIT_TEST_CAPTURE_STREAMS=1
QISKIT_PARALLEL=FALSE
passenv =
RUSTUP_TOOLCHAIN
RAYON_NUM_THREADS
OMP_NUM_THREADS
QISKIT_PARALLEL
RUST_BACKTRACE
SETUPTOOLS_ENABLE_FEATURES
QISKIT_TESTS
QISKIT_IN_PARALLEL
QISKIT_DOCS_GITHUB_BRANCH_NAME
deps =
-r{toxinidir}/requirements.txt
-r{toxinidir}/requirements-dev.txt
commands =
stestr run {posargs}
[testenv:lint]
basepython = python3
# `pylint` will examine the source code, not the version that would otherwise be
# installed in `site-packages`, so we use an editable install to make sure the
# compiled modules are built into a valid place for it to find them.
package = editable
allowlist_externals = cargo
commands =
black --check {posargs} qiskit test tools examples setup.py
cargo fmt --check
ruff check qiskit test tools examples setup.py
cargo clippy -- -D warnings
pylint -rn qiskit test tools
# This line is commented out until #6649 merges. We can't run this currently
# via tox because tox doesn't support globbing
# pylint -rn --disable='invalid-name,missing-module-docstring,redefined-outer-name' examples/python/*.py
python {toxinidir}/tools/verify_headers.py qiskit test tools examples crates
python {toxinidir}/tools/find_optional_imports.py
python {toxinidir}/tools/find_stray_release_notes.py
reno -q lint
[testenv:lint-incr]
basepython = python3
allowlist_externals = git
commands =
ruff check qiskit test tools examples setup.py
black --check {posargs} qiskit test tools examples setup.py
-git fetch -q https://github.com/Qiskit/qiskit.git :lint_incr_latest
python {toxinidir}/tools/pylint_incr.py -rn -j4 -sn --paths :/qiskit/*.py :/test/*.py :/tools/*.py
python {toxinidir}/tools/pylint_incr.py -rn -j4 -sn --disable='invalid-name,missing-module-docstring,redefined-outer-name' --paths :(glob,top)examples/python/*.py
python {toxinidir}/tools/verify_headers.py qiskit test tools examples crates
python {toxinidir}/tools/find_optional_imports.py
python {toxinidir}/tools/find_stray_release_notes.py
reno -q lint
[testenv:black]
skip_install = true
deps =
-r requirements-dev.txt
commands = black {posargs} qiskit test tools examples setup.py
[testenv:coverage]
basepython = python3
setenv =
{[testenv]setenv}
PYTHON=coverage3 run --source qiskit --parallel-mode
commands_pre =
{[testenv]install_command} -r{toxinidir}/requirements-optional.txt
commands =
stestr run {posargs}
coverage3 combine
coverage3 report
[testenv:docs]
basepython = python3
setenv =
{[testenv]setenv}
RUST_DEBUG=1 # Faster to compile.
commands_pre =
{[testenv]install_command} -r{toxinidir}/requirements-optional.txt
commands =
sphinx-build -W -j auto -T --keep-going -b html docs/ docs/_build/html {posargs}
[testenv:docs-clean]
skip_install = true
deps =
allowlist_externals =
rm
commands =
rm -rf {toxinidir}/docs/stubs/ {toxinidir}/docs/_build {toxinidir}/docs/locale
| qiskit/tox.ini/0 | {
"file_path": "qiskit/tox.ini",
"repo_id": "qiskit",
"token_count": 1297
} | 340 |
Subsets and Splits