|
| 1 | +# This code is part of Qiskit. |
| 2 | +# |
| 3 | +# (C) Copyright IBM 2021. |
| 4 | +# |
| 5 | +# This code is licensed under the Apache License, Version 2.0. You may |
| 6 | +# obtain a copy of this license in the LICENSE.txt file in the root directory |
| 7 | +# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. |
| 8 | +# |
| 9 | +# Any modifications or derivative works of this code must retain this |
| 10 | +# copyright notice, and modified files need to carry a notice indicating |
| 11 | +# that they have been altered from the originals. |
| 12 | +""" |
| 13 | +Functions for preparing circuits for execution |
| 14 | +""" |
| 15 | + |
| 16 | +from __future__ import annotations |
| 17 | + |
| 18 | +import importlib.metadata |
| 19 | +import logging |
| 20 | +from collections.abc import Sequence |
| 21 | + |
| 22 | +from qiskit import QuantumCircuit, QuantumRegister, transpile |
| 23 | +from qiskit.exceptions import QiskitError |
| 24 | +from qiskit.providers import Backend |
| 25 | +from qiskit.providers.options import Options |
| 26 | +from qiskit.pulse.calibration_entries import CalibrationPublisher |
| 27 | +from qiskit.transpiler import Target |
| 28 | + |
| 29 | + |
| 30 | +LOGGER = logging.getLogger(__file__) |
| 31 | + |
| 32 | +DEFAULT_TRANSPILE_OPTIONS = Options(optimization_level=0, full_transpile=False) |
| 33 | +if importlib.metadata.version("qiskit").partition(".")[0] != "0": |
| 34 | + DEFAULT_TRANSPILE_OPTIONS["num_processes"] = 1 |
| 35 | + |
| 36 | + |
| 37 | +def map_qubits( |
| 38 | + circuit: QuantumCircuit, |
| 39 | + physical_qubits: Sequence[int], |
| 40 | + n_qubits: int | None = None, |
| 41 | +) -> QuantumCircuit: |
| 42 | + """Generate a new version of a circuit with new qubit indices |
| 43 | +
|
| 44 | + This function iterates through the instructions of ``circuit`` and copies |
| 45 | + them into a new circuit with qubit indices replaced according to the |
| 46 | + entries in ``physical_qubits``. So qubit 0's instructions are applied to |
| 47 | + ``physical_qubits[0]`` and qubit 1's to ``physical_qubits[1]``, etc. |
| 48 | +
|
| 49 | + This function behaves similarly to passing ``initial_layout`` to |
| 50 | + :func:`qiskit.transpile` but does not use a Qiskit |
| 51 | + :class:`~qiskit.transpiler.PassManager` and does not fill the circuit with |
| 52 | + ancillas. |
| 53 | +
|
| 54 | + Args: |
| 55 | + circuit: The :class:`~qiskit.QuantumCircuit` to re-index. |
| 56 | + physical_qubits: The list of new indices for ``circuit``'s qubit indices. |
| 57 | + n_qubits: Optional qubit size to use for the output circuit. If |
| 58 | + ``None``, then the maximum of ``physical_qubits`` will be used. |
| 59 | +
|
| 60 | + Returns: |
| 61 | + The quantum circuit with new qubit indices |
| 62 | + """ |
| 63 | + if len(physical_qubits) != circuit.num_qubits: |
| 64 | + raise QiskitError( |
| 65 | + f"Circuit to map has {circuit.num_qubits} qubits, but " |
| 66 | + f"{len(physical_qubits)} physical qubits specified for mapping." |
| 67 | + ) |
| 68 | + |
| 69 | + # if all(p == r for p, r in zip(physical_qubits, range(circuit.num_qubits))): |
| 70 | + # # No mapping necessary |
| 71 | + # return circuit |
| 72 | + |
| 73 | + circ_size = n_qubits if n_qubits is not None else (max(physical_qubits) + 1) |
| 74 | + p_qregs = QuantumRegister(circ_size) |
| 75 | + p_circ = QuantumCircuit( |
| 76 | + p_qregs, |
| 77 | + *circuit.cregs, |
| 78 | + name=circuit.name, |
| 79 | + metadata=circuit.metadata, |
| 80 | + global_phase=circuit.global_phase, |
| 81 | + ) |
| 82 | + p_circ.compose( |
| 83 | + circuit, |
| 84 | + qubits=physical_qubits, |
| 85 | + inplace=True, |
| 86 | + copy=False, |
| 87 | + ) |
| 88 | + return p_circ |
| 89 | + |
| 90 | + |
| 91 | +def _has_calibration(target: Target, name: str, qubits: tuple[int, ...]) -> bool: |
| 92 | + """Wrapper to work around bug in Target.has_calibration""" |
| 93 | + try: |
| 94 | + has_cal = target.has_calibration(name, qubits) |
| 95 | + except AttributeError: |
| 96 | + has_cal = False |
| 97 | + |
| 98 | + return has_cal |
| 99 | + |
| 100 | + |
| 101 | +def check_transpilation_needed( |
| 102 | + circuits: Sequence[QuantumCircuit], |
| 103 | + backend: Backend, |
| 104 | +) -> bool: |
| 105 | + """Test if circuits are already compatible with backend |
| 106 | +
|
| 107 | + This function checks if circuits are able to be executed on ``backend`` |
| 108 | + without transpilation. It loops through the circuits to check if any gate |
| 109 | + instructions are not included in the backend's |
| 110 | + :class:`~qiskit.transpiler.Target`. The :class:`~qiskit.transpiler.Target` |
| 111 | + is also checked for custom pulse gate calibrations for circuit's |
| 112 | + instructions. If all gates are included in the target and there are no |
| 113 | + custom calibrations, the function returns ``False`` indicating that |
| 114 | + transpilation is not needed. |
| 115 | +
|
| 116 | + This function returns ``True`` if the version of ``backend`` is less than |
| 117 | + 2. |
| 118 | +
|
| 119 | + The motivation for this function is that when no transpilation is necessary |
| 120 | + it is faster to check the circuits in this way than to run |
| 121 | + :func:`~qiskit.transpile` and have it do nothing. |
| 122 | +
|
| 123 | + Args: |
| 124 | + circuits: The circuits to prepare for the backend. |
| 125 | + backend: The backend for which the circuits should be prepared. |
| 126 | +
|
| 127 | + Returns: |
| 128 | + ``True`` if transpilation is needed. Otherwise, ``False``. |
| 129 | + """ |
| 130 | + transpilation_needed = False |
| 131 | + |
| 132 | + if getattr(backend, "version", 0) <= 1: |
| 133 | + # Fall back to transpilation for BackendV1 |
| 134 | + return True |
| 135 | + |
| 136 | + target = backend.target |
| 137 | + |
| 138 | + for circ in circuits: |
| 139 | + for inst in circ.data: |
| 140 | + if inst.operation.name == "barrier" or circ.has_calibration_for(inst): |
| 141 | + continue |
| 142 | + qubits = tuple(circ.find_bit(q).index for q in inst.qubits) |
| 143 | + if not target.instruction_supported(inst.operation.name, qubits): |
| 144 | + transpilation_needed = True |
| 145 | + break |
| 146 | + if _has_calibration(target, inst.operation.name, qubits): |
| 147 | + cal = target.get_calibration(inst.operation.name, qubits, *inst.operation.params) |
| 148 | + if ( |
| 149 | + cal.metadata.get("publisher", CalibrationPublisher.QISKIT) |
| 150 | + != CalibrationPublisher.BACKEND_PROVIDER |
| 151 | + ): |
| 152 | + transpilation_needed = True |
| 153 | + break |
| 154 | + if transpilation_needed: |
| 155 | + break |
| 156 | + |
| 157 | + return transpilation_needed |
| 158 | + |
| 159 | + |
| 160 | +def minimal_transpile( |
| 161 | + circuits: Sequence[QuantumCircuit], |
| 162 | + backend: Backend, |
| 163 | + options: Options, |
| 164 | +) -> list[QuantumCircuit]: |
| 165 | + """Prepare circuits for execution on a backend |
| 166 | +
|
| 167 | + This function is a wrapper around :func:`~qiskit.transpile` to prepare |
| 168 | + circuits for execution ``backend`` that tries to do less work in the case |
| 169 | + in which the ``circuits`` can already be executed on the backend without |
| 170 | + modification. |
| 171 | +
|
| 172 | + The instructions in ``circuits`` are checked to see if they can be executed |
| 173 | + by the ``backend`` using :func:`check_transpilation_needed`. If the |
| 174 | + circuits can not be executed, :func:`~qiskit.transpile` is called on them. |
| 175 | + ``options`` is a set of options to pass to the :func:`~qiskit.transpile` |
| 176 | + (see detailed description of ``options``). The special ``full_transpile`` |
| 177 | + option can also be set to ``True`` to force calling |
| 178 | + :func:`~qiskit.transpile`. |
| 179 | +
|
| 180 | + Args: |
| 181 | + circuits: The circuits to prepare for the backend. |
| 182 | + backend: The backend for which the circuits should be prepared. |
| 183 | + options: Options for the transpilation. ``full_transpile`` can be set |
| 184 | + to ``True`` to force this function to pass the circuits to |
| 185 | + :func:`~qiskit.transpile`. Other options are passed as arguments to |
| 186 | + :func:`qiskit.transpile` if it is called. |
| 187 | +
|
| 188 | + Returns: |
| 189 | + The prepared circuits |
| 190 | + """ |
| 191 | + options = dict(options.items()) |
| 192 | + |
| 193 | + if "full_transpile" not in options: |
| 194 | + LOGGER.debug( |
| 195 | + "Performing full transpile because base transpile options " |
| 196 | + "were overwritten and full_transpile was not specified." |
| 197 | + ) |
| 198 | + full_transpile = True |
| 199 | + else: |
| 200 | + full_transpile = options.pop("full_transpile", False) |
| 201 | + if not full_transpile and set(options) - set(DEFAULT_TRANSPILE_OPTIONS): |
| 202 | + # If an experiment specifies transpile options, it needs to go |
| 203 | + # through transpile() |
| 204 | + full_transpile = True |
| 205 | + LOGGER.debug( |
| 206 | + "Performing full transpile because non-default transpile options are specified." |
| 207 | + ) |
| 208 | + |
| 209 | + if not full_transpile: |
| 210 | + full_transpile = check_transpilation_needed(circuits, backend) |
| 211 | + |
| 212 | + if full_transpile: |
| 213 | + transpiled = transpile(circuits, backend, **options) |
| 214 | + else: |
| 215 | + transpiled = circuits |
| 216 | + |
| 217 | + return transpiled |
0 commit comments