diff --git a/docs/apidoc/extensions.rst b/docs/apidoc/extensions.rst deleted file mode 100644 index 6c58ab806704..000000000000 --- a/docs/apidoc/extensions.rst +++ /dev/null @@ -1,6 +0,0 @@ -.. _qiskit-extensions: - -.. automodule:: qiskit.extensions - :no-members: - :no-inherited-members: - :no-special-members: diff --git a/docs/apidoc/index.rst b/docs/apidoc/index.rst index 9116ccfb4662..a121d0852ba4 100644 --- a/docs/apidoc/index.rst +++ b/docs/apidoc/index.rst @@ -18,7 +18,6 @@ API Reference converters assembler dagcircuit - extensions passmanager providers_basicaer providers diff --git a/qiskit/circuit/library/data_preparation/state_preparation.py b/qiskit/circuit/library/data_preparation/state_preparation.py index d717630d2da6..089f4fbe3f1f 100644 --- a/qiskit/circuit/library/data_preparation/state_preparation.py +++ b/qiskit/circuit/library/data_preparation/state_preparation.py @@ -18,7 +18,7 @@ from qiskit.exceptions import QiskitError from qiskit.circuit.quantumcircuit import QuantumCircuit -from qiskit.circuit.quantumregister import QuantumRegister, Qubit +from qiskit.circuit.quantumregister import QuantumRegister from qiskit.circuit.gate import Gate from qiskit.circuit.library.standard_gates.x import CXGate, XGate from qiskit.circuit.library.standard_gates.h import HGate @@ -413,114 +413,3 @@ def _multiplex(self, target_gate, list_of_angles, last_cnot=True): circuit.append(CXGate(), [msb, lsb]) return circuit - - -def prepare_state(self, state, qubits=None, label=None, normalize=False): - r"""Prepare qubits in a specific state. - - This class implements a state preparing unitary. Unlike - :class:`qiskit.extensions.Initialize` it does not reset the qubits first. - - Args: - state (str or list or int or Statevector): - * Statevector: Statevector to initialize to. - * str: labels of basis states of the Pauli eigenstates Z, X, Y. See - :meth:`.Statevector.from_label`. Notice the order of the labels is reversed with respect - to the qubit index to be applied to. Example label '01' initializes the qubit zero to - :math:`|1\rangle` and the qubit one to :math:`|0\rangle`. - * list: vector of complex amplitudes to initialize to. - * int: an integer that is used as a bitmap indicating which qubits to initialize - to :math:`|1\rangle`. Example: setting params to 5 would initialize qubit 0 and qubit 2 - to :math:`|1\rangle` and qubit 1 to :math:`|0\rangle`. - - qubits (QuantumRegister or Qubit or int): - * QuantumRegister: A list of qubits to be initialized [Default: None]. - * Qubit: Single qubit to be initialized [Default: None]. - * int: Index of qubit to be initialized [Default: None]. - * list: Indexes of qubits to be initialized [Default: None]. - label (str): An optional label for the gate - normalize (bool): Whether to normalize an input array to a unit vector. - - Returns: - qiskit.circuit.Instruction: a handle to the instruction that was just initialized - - Examples: - Prepare a qubit in the state :math:`(|0\rangle - |1\rangle) / \sqrt{2}`. - - .. code-block:: - - import numpy as np - from qiskit import QuantumCircuit - - circuit = QuantumCircuit(1) - circuit.prepare_state([1/np.sqrt(2), -1/np.sqrt(2)], 0) - circuit.draw() - - output: - - .. parsed-literal:: - - ┌─────────────────────────────────────┐ - q_0: ┤ State Preparation(0.70711,-0.70711) ├ - └─────────────────────────────────────┘ - - - Prepare from a string two qubits in the state :math:`|10\rangle`. - The order of the labels is reversed with respect to qubit index. - More information about labels for basis states are in - :meth:`.Statevector.from_label`. - - .. code-block:: - - import numpy as np - from qiskit import QuantumCircuit - - circuit = QuantumCircuit(2) - circuit.prepare_state('01', circuit.qubits) - circuit.draw() - - output: - - .. parsed-literal:: - - ┌─────────────────────────┐ - q_0: ┤0 ├ - │ State Preparation(0,1) │ - q_1: ┤1 ├ - └─────────────────────────┘ - - - Initialize two qubits from an array of complex amplitudes - .. code-block:: - - import numpy as np - from qiskit import QuantumCircuit - - circuit = QuantumCircuit(2) - circuit.prepare_state([0, 1/np.sqrt(2), -1.j/np.sqrt(2), 0], circuit.qubits) - circuit.draw() - - output: - - .. parsed-literal:: - - ┌───────────────────────────────────────────┐ - q_0: ┤0 ├ - │ State Preparation(0,0.70711,-0.70711j,0) │ - q_1: ┤1 ├ - └───────────────────────────────────────────┘ - """ - - if qubits is None: - qubits = self.qubits - elif isinstance(qubits, (int, np.integer, slice, Qubit)): - qubits = [qubits] - - num_qubits = len(qubits) if isinstance(state, int) else None - - return self.append( - StatePreparation(state, num_qubits, label=label, normalize=normalize), qubits - ) - - -QuantumCircuit.prepare_state = prepare_state diff --git a/qiskit/circuit/quantumcircuit.py b/qiskit/circuit/quantumcircuit.py index 08a6a15d2e12..ae6ea839e2a7 100644 --- a/qiskit/circuit/quantumcircuit.py +++ b/qiskit/circuit/quantumcircuit.py @@ -20,7 +20,6 @@ import multiprocessing as mp import warnings import typing -import math from collections import OrderedDict, defaultdict, namedtuple from typing import ( Union, @@ -74,6 +73,7 @@ import qiskit # pylint: disable=cyclic-import from qiskit.transpiler.layout import TranspileLayout # pylint: disable=cyclic-import from qiskit.quantum_info.operators.base_operator import BaseOperator + from qiskit.quantum_info.states.statevector import Statevector # pylint: disable=cyclic-import BitLocations = namedtuple("BitLocations", ("index", "registers")) @@ -3396,23 +3396,6 @@ def ch( CHGate(label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], [] ) - @deprecate_func( - since="0.45.0", - additional_msg="Use QuantumCircuit.id as direct replacement.", - ) - def i(self, qubit: QubitSpecifier) -> InstructionSet: - """Apply :class:`~qiskit.circuit.library.IGate`. - - For the full matrix form of this gate, see the underlying gate documentation. - - Args: - qubit: The qubit(s) to apply the gate to. - - Returns: - A handle to the instructions created. - """ - return self.id(qubit) - def id(self, qubit: QubitSpecifier) -> InstructionSet: # pylint: disable=invalid-name """Apply :class:`~qiskit.circuit.library.IGate`. @@ -3997,33 +3980,6 @@ def cswap( [], ) - @deprecate_func( - since="0.45.0", - additional_msg="Use QuantumCircuit.cswap as direct replacement.", - ) - def fredkin( - self, - control_qubit: QubitSpecifier, - target_qubit1: QubitSpecifier, - target_qubit2: QubitSpecifier, - ) -> InstructionSet: - """Apply :class:`~qiskit.circuit.library.CSwapGate`. - - For the full matrix form of this gate, see the underlying gate documentation. - - Args: - control_qubit: The qubit(s) used as the control. - target_qubit1: The qubit(s) targeted by the gate. - target_qubit2: The qubit(s) targeted by the gate. - - Returns: - A handle to the instructions created. - - See Also: - QuantumCircuit.cswap: the same function with a different name. - """ - return self.cswap(control_qubit, target_qubit1, target_qubit2) - def sx(self, qubit: QubitSpecifier) -> InstructionSet: """Apply :class:`~qiskit.circuit.library.SXGate`. @@ -4221,34 +4177,6 @@ def cx( CXGate(label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], [] ) - @deprecate_func(since="0.45.0", additional_msg="Use QuantumCircuit.cx as direct replacement.") - def cnot( - self, - control_qubit: QubitSpecifier, - target_qubit: QubitSpecifier, - label: str | None = None, - ctrl_state: str | int | None = None, - ) -> InstructionSet: - r"""Apply :class:`~qiskit.circuit.library.CXGate`. - - For the full matrix form of this gate, see the underlying gate documentation. - - Args: - control_qubit: The qubit(s) used as the control. - target_qubit: The qubit(s) targeted by the gate. - label: The string label of the gate in the circuit. - ctrl_state: - The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling - on the '1' state. - - Returns: - A handle to the instructions created. - - See Also: - QuantumCircuit.cx: the same function with a different name. - """ - return self.cx(control_qubit, target_qubit, label, ctrl_state) - def dcx(self, qubit1: QubitSpecifier, qubit2: QubitSpecifier) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.DCXGate`. @@ -4295,30 +4223,6 @@ def ccx( [], ) - @deprecate_func(since="0.45.0", additional_msg="Use QuantumCircuit.ccx as direct replacement.") - def toffoli( - self, - control_qubit1: QubitSpecifier, - control_qubit2: QubitSpecifier, - target_qubit: QubitSpecifier, - ) -> InstructionSet: - r"""Apply :class:`~qiskit.circuit.library.CCXGate`. - - For the full matrix form of this gate, see the underlying gate documentation. - - Args: - control_qubit1: The qubit(s) used as the first control. - control_qubit2: The qubit(s) used as the second control. - target_qubit: The qubit(s) targeted by the gate. - - Returns: - A handle to the instructions created. - - See Also: - QuantumCircuit.ccx: the same gate with a different name. - """ - return self.ccx(control_qubit1, control_qubit2, target_qubit) - def mcx( self, control_qubits: Sequence[QubitSpecifier], @@ -4397,44 +4301,6 @@ def mcx( return self.append(gate, control_qubits[:] + [target_qubit] + ancilla_qubits[:], []) - @deprecate_func(since="0.45.0", additional_msg="Use QuantumCircuit.mcx as direct replacement.") - def mct( - self, - control_qubits: Sequence[QubitSpecifier], - target_qubit: QubitSpecifier, - ancilla_qubits: QubitSpecifier | Sequence[QubitSpecifier] | None = None, - mode: str = "noancilla", - ) -> InstructionSet: - """Apply :class:`~qiskit.circuit.library.MCXGate`. - - The multi-cX gate can be implemented using different techniques, which use different numbers - of ancilla qubits and have varying circuit depth. These modes are: - - - ``'noancilla'``: Requires 0 ancilla qubits. - - ``'recursion'``: Requires 1 ancilla qubit if more than 4 controls are used, otherwise 0. - - ``'v-chain'``: Requires 2 less ancillas than the number of control qubits. - - ``'v-chain-dirty'``: Same as for the clean ancillas (but the circuit will be longer). - - For the full matrix form of this gate, see the underlying gate documentation. - - Args: - control_qubits: The qubits used as the controls. - target_qubit: The qubit(s) targeted by the gate. - ancilla_qubits: The qubits used as the ancillae, if the mode requires them. - mode: The choice of mode, explained further above. - - Returns: - A handle to the instructions created. - - Raises: - ValueError: if the given mode is not known, or if too few ancilla qubits are passed. - AttributeError: if no ancilla qubits are passed, but some are needed. - - See Also: - QuantumCircuit.mcx: the same gate with a different name. - """ - return self.mcx(control_qubits, target_qubit, ancilla_qubits, mode) - def y(self, qubit: QubitSpecifier) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.YGate`. @@ -4571,19 +4437,131 @@ def pauli( return self.append(PauliGate(pauli_string), qubits, []) + def prepare_state( + self, + state: Statevector | Sequence[complex] | str | int, + qubits: Sequence[QubitSpecifier] | None = None, + label: str | None = None, + normalize: bool = False, + ) -> InstructionSet: + r"""Prepare qubits in a specific state. + + This class implements a state preparing unitary. Unlike + :meth:`.initialize` it does not reset the qubits first. + + Args: + state: The state to initialize to, can be either of the following. + + * Statevector or vector of complex amplitudes to initialize to. + * Labels of basis states of the Pauli eigenstates Z, X, Y. See + :meth:`.Statevector.from_label`. Notice the order of the labels is reversed with + respect to the qubit index to be applied to. Example label '01' initializes the + qubit zero to :math:`|1\rangle` and the qubit one to :math:`|0\rangle`. + * An integer that is used as a bitmap indicating which qubits to initialize to + :math:`|1\rangle`. Example: setting params to 5 would initialize qubit 0 and qubit + 2 to :math:`|1\rangle` and qubit 1 to :math:`|0\rangle`. + + qubits: Qubits to initialize. If ``None`` the initialization is applied to all qubits in + the circuit. + label: An optional label for the gate + normalize: Whether to normalize an input array to a unit vector. + + Returns: + A handle to the instruction that was just initialized + + Examples: + Prepare a qubit in the state :math:`(|0\rangle - |1\rangle) / \sqrt{2}`. + + .. code-block:: + + import numpy as np + from qiskit import QuantumCircuit + + circuit = QuantumCircuit(1) + circuit.prepare_state([1/np.sqrt(2), -1/np.sqrt(2)], 0) + circuit.draw() + + output: + + .. parsed-literal:: + + ┌─────────────────────────────────────┐ + q_0: ┤ State Preparation(0.70711,-0.70711) ├ + └─────────────────────────────────────┘ + + + Prepare from a string two qubits in the state :math:`|10\rangle`. + The order of the labels is reversed with respect to qubit index. + More information about labels for basis states are in + :meth:`.Statevector.from_label`. + + .. code-block:: + + import numpy as np + from qiskit import QuantumCircuit + + circuit = QuantumCircuit(2) + circuit.prepare_state('01', circuit.qubits) + circuit.draw() + + output: + + .. parsed-literal:: + + ┌─────────────────────────┐ + q_0: ┤0 ├ + │ State Preparation(0,1) │ + q_1: ┤1 ├ + └─────────────────────────┘ + + + Initialize two qubits from an array of complex amplitudes + .. code-block:: + + import numpy as np + from qiskit import QuantumCircuit + + circuit = QuantumCircuit(2) + circuit.prepare_state([0, 1/np.sqrt(2), -1.j/np.sqrt(2), 0], circuit.qubits) + circuit.draw() + + output: + + .. parsed-literal:: + + ┌───────────────────────────────────────────┐ + q_0: ┤0 ├ + │ State Preparation(0,0.70711,-0.70711j,0) │ + q_1: ┤1 ├ + └───────────────────────────────────────────┘ + """ + # pylint: disable=cyclic-import + from qiskit.circuit.library.data_preparation import StatePreparation + + if qubits is None: + qubits = self.qubits + elif isinstance(qubits, (int, np.integer, slice, Qubit)): + qubits = [qubits] + + num_qubits = len(qubits) if isinstance(state, int) else None + + return self.append( + StatePreparation(state, num_qubits, label=label, normalize=normalize), qubits + ) + def initialize( self, - params: Sequence[complex] | str | int, + params: Statevector | Sequence[complex] | str | int, qubits: Sequence[QubitSpecifier] | None = None, normalize: bool = False, ): r"""Initialize qubits in a specific state. Qubit initialization is done by first resetting the qubits to :math:`|0\rangle` - followed by calling :class:`qiskit.extensions.StatePreparation` + followed by calling :class:`~qiskit.circuit.librar.StatePreparation` class to prepare the qubits in a specified state. Both these steps are included in the - :class:`qiskit.extensions.Initialize` instruction. + :class:`~qiskit.circuit.library.Initialize` instruction. Args: params: The state to initialize to, can be either of the following. @@ -4725,515 +4703,6 @@ def unitary( return self.append(gate, qubits, []) - @deprecate_func( - since="0.45.0", - additional_msg="Instead, compose the circuit with a qiskit.circuit.library.Diagonal circuit.", - pending=True, - ) - def diagonal(self, diag, qubit): - """Attach a diagonal gate to a circuit. - - The decomposition is based on Theorem 7 given in "Synthesis of Quantum Logic Circuits" by - Shende et al. (https://arxiv.org/pdf/quant-ph/0406176.pdf). - - Args: - diag (list): list of the 2^k diagonal entries (for a diagonal gate on k qubits). - Must contain at least two entries - qubit (QuantumRegister | list): list of k qubits the diagonal is - acting on (the order of the qubits specifies the computational basis in which the - diagonal gate is provided: the first element in diag acts on the state where all - the qubits in q are in the state 0, the second entry acts on the state where all - the qubits q[1],...,q[k-1] are in the state zero and q[0] is in the state 1, - and so on) - - Returns: - QuantumCircuit: the diagonal gate which was attached to the circuit. - - Raises: - QiskitError: if the list of the diagonal entries or the qubit list is in bad format; - if the number of diagonal entries is not 2^k, where k denotes the number of qubits - """ - # pylint: disable=cyclic-import - from .library.generalized_gates.diagonal import DiagonalGate - - if isinstance(qubit, QuantumRegister): - qubit = qubit[:] - # Check if q has type "list" - if not isinstance(qubit, list): - raise QiskitError( - "The qubits must be provided as a list (also if there is only one qubit)." - ) - # Check if diag has type "list" - if not isinstance(diag, list): - raise QiskitError("The diagonal entries are not provided in a list.") - num_action_qubits = math.log2(len(diag)) - if not len(qubit) == num_action_qubits: - raise QiskitError( - "The number of diagonal entries does not correspond to the number of qubits." - ) - - return self.append(DiagonalGate(diag), qubit) - - @deprecate_func( - since="0.45.0", - additional_msg="Instead, append a qiskit.circuit.library.Isometry to the circuit.", - pending=True, - ) - def iso( - self, - isometry, - q_input, - q_ancillas_for_output, - q_ancillas_zero=None, - q_ancillas_dirty=None, - epsilon=1e-10, - ): - """ - Attach an arbitrary isometry from m to n qubits to a circuit. In particular, - this allows to attach arbitrary unitaries on n qubits (m=n) or to prepare any state - on n qubits (m=0). - The decomposition used here was introduced by Iten et al. in https://arxiv.org/abs/1501.06911. - - Args: - isometry (ndarray): an isometry from m to n qubits, i.e., a (complex) ndarray of - dimension 2^n×2^m with orthonormal columns (given in the computational basis - specified by the order of the ancillas and the input qubits, where the ancillas - are considered to be more significant than the input qubits.). - q_input (QuantumRegister | list[Qubit]): list of m qubits where the input - to the isometry is fed in (empty list for state preparation). - q_ancillas_for_output (QuantumRegister | list[Qubit]): list of n-m ancilla - qubits that are used for the output of the isometry and which are assumed to start - in the zero state. The qubits are listed with increasing significance. - q_ancillas_zero (QuantumRegister | list[Qubit]): list of ancilla qubits - which are assumed to start in the zero state. Default is q_ancillas_zero = None. - q_ancillas_dirty (QuantumRegister | list[Qubit]): list of ancilla qubits - which can start in an arbitrary state. Default is q_ancillas_dirty = None. - epsilon (float): error tolerance of calculations. - Default is epsilon = _EPS. - - Returns: - QuantumCircuit: the isometry is attached to the quantum circuit. - - Raises: - QiskitError: if the array is not an isometry of the correct size corresponding to - the provided number of qubits. - """ - # pylint: disable=cyclic-import - from .library.generalized_gates.isometry import Isometry - - if q_input is None: - q_input = [] - if q_ancillas_for_output is None: - q_ancillas_for_output = [] - if q_ancillas_zero is None: - q_ancillas_zero = [] - if q_ancillas_dirty is None: - q_ancillas_dirty = [] - - if isinstance(q_input, QuantumRegister): - q_input = q_input[:] - if isinstance(q_ancillas_for_output, QuantumRegister): - q_ancillas_for_output = q_ancillas_for_output[:] - if isinstance(q_ancillas_zero, QuantumRegister): - q_ancillas_zero = q_ancillas_zero[:] - if isinstance(q_ancillas_dirty, QuantumRegister): - q_ancillas_dirty = q_ancillas_dirty[:] - - return self.append( - Isometry(isometry, len(q_ancillas_zero), len(q_ancillas_dirty), epsilon=epsilon), - q_input + q_ancillas_for_output + q_ancillas_zero + q_ancillas_dirty, - ) - - @deprecate_func( - since="0.45.0", - additional_msg="Instead, append a qiskit.circuit.library.HamiltonianGate to the circuit.", - pending=True, - ) - def hamiltonian(self, operator, time, qubits, label=None): - """Apply hamiltonian evolution to qubits. - - This gate resolves to a :class:`~.library.UnitaryGate` as :math:`U(t) = exp(-i t H)`, - which can be decomposed into basis gates if it is 2 qubits or less, or - simulated directly in Aer for more qubits. - - Args: - operator (matrix or Operator): a hermitian operator. - time (float or ParameterExpression): time evolution parameter. - qubits (Union[int, Tuple[int]]): The circuit qubits to apply the - transformation to. - label (str): unitary name for backend [Default: None]. - - Returns: - QuantumCircuit: The quantum circuit. - """ - # pylint: disable=cyclic-import - from .library.hamiltonian_gate import HamiltonianGate - - if not isinstance(qubits, list): - qubits = [qubits] - - return self.append(HamiltonianGate(data=operator, time=time, label=label), qubits, []) - - @deprecate_func( - since="0.45.0", - additional_msg="Instead, append a qiskit.circuit.library.UCGate to the circuit.", - pending=True, - ) - def uc(self, gate_list, q_controls, q_target, up_to_diagonal=False): - """Attach a uniformly controlled gates (also called multiplexed gates) to a circuit. - - The decomposition was introduced by Bergholm et al. in - https://arxiv.org/pdf/quant-ph/0410066.pdf. - - Args: - gate_list (list[ndarray]): list of two qubit unitaries [U_0,...,U_{2^k-1}], - where each single-qubit unitary U_i is a given as a 2*2 array - q_controls (QuantumRegister | list[(QuantumRegister,int)]): list of k control qubits. - The qubits are ordered according to their significance in the computational basis. - For example if q_controls=[q[1],q[2]] (with q = QuantumRegister(2)), - the unitary U_0 is performed if q[1] and q[2] are in the state zero, U_1 is - performed if q[2] is in the state zero and q[1] is in the state one, and so on - q_target (QuantumRegister | tuple(QuantumRegister, int)): target qubit, where we act on with - the single-qubit gates. - up_to_diagonal (bool): If set to True, the uniformly controlled gate is decomposed up - to a diagonal gate, i.e. a unitary u' is implemented such that there exists a - diagonal gate d with u = d.dot(u'), where the unitary u describes the uniformly - controlled gate - - Returns: - QuantumCircuit: the uniformly controlled gate is attached to the circuit. - - Raises: - QiskitError: if the list number of control qubits does not correspond to the provided - number of single-qubit unitaries; if an input is of the wrong type - """ - # pylint: disable=cyclic-import - from .library.generalized_gates.uc import UCGate - - if isinstance(q_controls, QuantumRegister): - q_controls = q_controls[:] - if isinstance(q_target, QuantumRegister): - q_target = q_target[:] - if len(q_target) == 1: - q_target = q_target[0] - else: - raise QiskitError( - "The target qubit is a QuantumRegister containing more than one qubit." - ) - # Check if q_controls has type "list" - if not isinstance(q_controls, list): - raise QiskitError( - "The control qubits must be provided as a list" - " (also if there is only one control qubit)." - ) - # Check if gate_list has type "list" - if not isinstance(gate_list, list): - raise QiskitError("The single-qubit unitaries are not provided in a list.") - # Check if number of gates in gate_list is a positive power of two - num_contr = math.log2(len(gate_list)) - if num_contr < 0 or not num_contr.is_integer(): - raise QiskitError( - "The number of controlled single-qubit gates is not a non negative power of 2." - ) - # Check if number of control qubits does correspond to the number of single-qubit rotations - if num_contr != len(q_controls): - raise QiskitError( - "Number of controlled gates does not correspond to the number of control qubits." - ) - return self.append(UCGate(gate_list, up_to_diagonal), [q_target] + q_controls) - - @deprecate_func( - since="0.45.0", - additional_msg="Instead, append a qiskit.circuit.library.UCRXGate to the circuit.", - pending=True, - ) - def ucrx( - self, - angle_list: list[float], - q_controls: Sequence[QubitSpecifier], - q_target: QubitSpecifier, - ): - r"""Attach a uniformly controlled (also called multiplexed) Rx rotation gate to a circuit. - - The decomposition is base on https://arxiv.org/pdf/quant-ph/0406176.pdf by Shende et al. - - Args: - angle_list (list[float]): list of (real) rotation angles :math:`[a_0,...,a_{2^k-1}]` - q_controls (Sequence[QubitSpecifier]): list of k control qubits - (or empty list if no controls). The control qubits are ordered according to their - significance in increasing order: For example if ``q_controls=[q[0],q[1]]`` - (with ``q = QuantumRegister(2)``), the rotation ``Rx(a_0)`` is performed if ``q[0]`` - and ``q[1]`` are in the state zero, the rotation ``Rx(a_1)`` is performed if ``q[0]`` - is in the state one and ``q[1]`` is in the state zero, and so on - q_target (QubitSpecifier): target qubit, where we act on with - the single-qubit rotation gates - - Returns: - QuantumCircuit: the uniformly controlled rotation gate is attached to the circuit. - - Raises: - QiskitError: if the list number of control qubits does not correspond to the provided - number of single-qubit unitaries; if an input is of the wrong type - """ - # pylint: disable=cyclic-import - from .library.generalized_gates.ucrx import UCRXGate - - if isinstance(q_controls, QuantumRegister): - q_controls = q_controls[:] - if isinstance(q_target, QuantumRegister): - q_target = q_target[:] - if len(q_target) == 1: - q_target = q_target[0] - else: - raise QiskitError( - "The target qubit is a QuantumRegister containing more than one qubit." - ) - # Check if q_controls has type "list" - if not isinstance(angle_list, list): - raise QiskitError("The angles must be provided as a list.") - num_contr = math.log2(len(angle_list)) - if num_contr < 0 or not num_contr.is_integer(): - raise QiskitError( - "The number of controlled rotation gates is not a non-negative power of 2." - ) - # Check if number of control qubits does correspond to the number of rotations - if num_contr != len(q_controls): - raise QiskitError( - "Number of controlled rotations does not correspond to the number of control-qubits." - ) - return self.append(UCRXGate(angle_list), [q_target] + q_controls, []) - - @deprecate_func( - since="0.45.0", - additional_msg="Instead, append a qiskit.circuit.library.UCRYGate to the circuit.", - pending=True, - ) - def ucry( - self, - angle_list: list[float], - q_controls: Sequence[QubitSpecifier], - q_target: QubitSpecifier, - ): - r"""Attach a uniformly controlled (also called multiplexed) Ry rotation gate to a circuit. - - The decomposition is base on https://arxiv.org/pdf/quant-ph/0406176.pdf by Shende et al. - - Args: - angle_list (list[float]): list of (real) rotation angles :math:`[a_0,...,a_{2^k-1}]` - q_controls (Sequence[QubitSpecifier]): list of k control qubits - (or empty list if no controls). The control qubits are ordered according to their - significance in increasing order: For example if ``q_controls=[q[0],q[1]]`` - (with ``q = QuantumRegister(2)``), the rotation ``Ry(a_0)`` is performed if ``q[0]`` - and ``q[1]`` are in the state zero, the rotation ``Ry(a_1)`` is performed if ``q[0]`` - is in the state one and ``q[1]`` is in the state zero, and so on - q_target (QubitSpecifier): target qubit, where we act on with - the single-qubit rotation gates - - Returns: - QuantumCircuit: the uniformly controlled rotation gate is attached to the circuit. - - Raises: - QiskitError: if the list number of control qubits does not correspond to the provided - number of single-qubit unitaries; if an input is of the wrong type - """ - # pylint: disable=cyclic-import - from .library.generalized_gates.ucry import UCRYGate - - if isinstance(q_controls, QuantumRegister): - q_controls = q_controls[:] - if isinstance(q_target, QuantumRegister): - q_target = q_target[:] - if len(q_target) == 1: - q_target = q_target[0] - else: - raise QiskitError( - "The target qubit is a QuantumRegister containing more than one qubit." - ) - # Check if q_controls has type "list" - if not isinstance(angle_list, list): - raise QiskitError("The angles must be provided as a list.") - num_contr = math.log2(len(angle_list)) - if num_contr < 0 or not num_contr.is_integer(): - raise QiskitError( - "The number of controlled rotation gates is not a non-negative power of 2." - ) - # Check if number of control qubits does correspond to the number of rotations - if num_contr != len(q_controls): - raise QiskitError( - "Number of controlled rotations does not correspond to the number of control-qubits." - ) - return self.append(UCRYGate(angle_list), [q_target] + q_controls, []) - - @deprecate_func( - since="0.45.0", - additional_msg="Instead, append a qiskit.circuit.library.UCRZGate to the circuit.", - pending=True, - ) - def ucrz( - self, - angle_list: list[float], - q_controls: Sequence[QubitSpecifier], - q_target: QubitSpecifier, - ): - r"""Attach a uniformly controlled (also called multiplexed) Rz rotation gate to a circuit. - - The decomposition is base on https://arxiv.org/pdf/quant-ph/0406176.pdf by Shende et al. - - Args: - angle_list (list[float]): list of (real) rotation angles :math:`[a_0,...,a_{2^k-1}]` - q_controls (Sequence[QubitSpecifier]): list of k control qubits - (or empty list if no controls). The control qubits are ordered according to their - significance in increasing order: For example if ``q_controls=[q[0],q[1]]`` - (with ``q = QuantumRegister(2)``), the rotation ``Rz(a_0)`` is performed if ``q[0]`` - and ``q[1]`` are in the state zero, the rotation ``Rz(a_1)`` is performed if ``q[0]`` - is in the state one and ``q[1]`` is in the state zero, and so on - q_target (QubitSpecifier): target qubit, where we act on with - the single-qubit rotation gates - - Returns: - QuantumCircuit: the uniformly controlled rotation gate is attached to the circuit. - - Raises: - QiskitError: if the list number of control qubits does not correspond to the provided - number of single-qubit unitaries; if an input is of the wrong type - """ - # pylint: disable=cyclic-import - from .library.generalized_gates.ucrz import UCRZGate - - if isinstance(q_controls, QuantumRegister): - q_controls = q_controls[:] - if isinstance(q_target, QuantumRegister): - q_target = q_target[:] - if len(q_target) == 1: - q_target = q_target[0] - else: - raise QiskitError( - "The target qubit is a QuantumRegister containing more than one qubit." - ) - # Check if q_controls has type "list" - if not isinstance(angle_list, list): - raise QiskitError("The angles must be provided as a list.") - num_contr = math.log2(len(angle_list)) - if num_contr < 0 or not num_contr.is_integer(): - raise QiskitError( - "The number of controlled rotation gates is not a non-negative power of 2." - ) - # Check if number of control qubits does correspond to the number of rotations - if num_contr != len(q_controls): - raise QiskitError( - "Number of controlled rotations does not correspond to the number of control-qubits." - ) - return self.append(UCRZGate(angle_list), [q_target] + q_controls, []) - - @deprecate_func( - since="0.45.0", additional_msg="Instead, use the QuantumCircuit.unitary method." - ) - def squ( - self, - unitary_matrix, - qubit, - mode="ZYZ", - up_to_diagonal=False, - ): - """Decompose an arbitrary 2*2 unitary into three rotation gates. - - Note that the decomposition is up to a global phase shift. - (This is a well known decomposition which can be found for example in Nielsen and Chuang's book - "Quantum computation and quantum information".) - - Args: - unitary_matrix (ndarray): 2*2 unitary (given as a (complex) ndarray). - qubit (QuantumRegister or Qubit): The qubit which the gate is acting on. - mode (string): determines the used decomposition by providing the rotation axes. - The allowed modes are: "ZYZ" (default) - up_to_diagonal (bool): if set to True, the single-qubit unitary is decomposed up to - a diagonal matrix, i.e. a unitary u' is implemented such that there exists a 2*2 - diagonal gate d with u = d.dot(u') - - Returns: - InstructionSet: The single-qubit unitary instruction attached to the circuit. - - Raises: - QiskitError: if the format is wrong; if the array u is not unitary - """ - # pylint: disable=cyclic-import - from qiskit.extensions.quantum_initializer.squ import SingleQubitUnitary - - if isinstance(qubit, QuantumRegister): - qubit = qubit[:] - if len(qubit) == 1: - qubit = qubit[0] - else: - raise QiskitError( - "The target qubit is a QuantumRegister containing more than one qubit." - ) - # Check if there is one target qubit provided - if not isinstance(qubit, Qubit): - raise QiskitError("The target qubit is not a single qubit from a QuantumRegister.") - - with warnings.catch_warnings(): - warnings.simplefilter("ignore", category=DeprecationWarning) - squ = SingleQubitUnitary(unitary_matrix, mode, up_to_diagonal) - - return self.append(squ, [qubit], []) - - @deprecate_func( - since="0.45.0", - additional_msg="The Snapshot instruction has been superseded by Qiskit Aer's save " - "instructions, see " - "https://qiskit.org/ecosystem/aer/apidocs/aer_library.html#saving-simulator-data.", - ) - def snapshot(self, label, snapshot_type="statevector", qubits=None, params=None): - """Take a statevector snapshot of the internal simulator representation. - Works on all qubits, and prevents reordering (like barrier). - - For other types of snapshots use the Snapshot extension directly. - - Args: - label (str): a snapshot label to report the result. - snapshot_type (str): the type of the snapshot. - qubits (list or None): the qubits to apply snapshot to [Default: None]. - params (list or None): the parameters for snapshot_type [Default: None]. - - Returns: - QuantumCircuit: with attached command - - Raises: - ExtensionError: malformed command - """ - # pylint: disable-cyclic-import - from qiskit.extensions.simulator.snapshot import Snapshot - from qiskit.extensions.exceptions import ExtensionError - - # If no qubits are specified we add all qubits so it acts as a barrier - # This is needed for full register snapshots like statevector - if isinstance(qubits, QuantumRegister): - qubits = qubits[:] - if not qubits: - tuples = [] - if isinstance(self, QuantumCircuit): - for register in self.qregs: - tuples.append(register) - if not tuples: - raise ExtensionError("no qubits for snapshot") - qubits = [] - for tuple_element in tuples: - if isinstance(tuple_element, QuantumRegister): - for j in range(tuple_element.size): - qubits.append(tuple_element[j]) - else: - qubits.append(tuple_element) - - # catch deprecation warning from instantiating the Snapshot instruction, - # as a warning is already triggered from this method - with warnings.catch_warnings(): - warnings.simplefilter("ignore", category=DeprecationWarning) - snap = Snapshot( - label, snapshot_type=snapshot_type, num_qubits=len(qubits), params=params - ) - - return self.append(snap, qubits) - def _current_scope(self) -> CircuitScopeInterface: if self._control_flow_scopes: return self._control_flow_scopes[-1] @@ -5973,10 +5442,6 @@ def qubit_stop_time(self, *qubits: Union[Qubit, int]) -> float: return 0 # If there are no instructions over bits -# isometry is an alias for iso -QuantumCircuit.isometry = QuantumCircuit.iso - - class _OuterCircuitScopeInterface(CircuitScopeInterface): # This is an explicit interface-fulfilling object friend of QuantumCircuit that acts as its # implementation of the control-flow builder scope methods. diff --git a/qiskit/circuit/random/utils.py b/qiskit/circuit/random/utils.py index d8c863a81d6f..71809735aa8e 100644 --- a/qiskit/circuit/random/utils.py +++ b/qiskit/circuit/random/utils.py @@ -26,7 +26,7 @@ def random_circuit( """Generate random circuit of arbitrary size and form. This function will generate a random circuit by randomly selecting gates - from the set of standard gates in :mod:`qiskit.extensions`. For example: + from the set of standard gates in :mod:`qiskit.circuit.library.standard_gates`. For example: .. plot:: :include-source: diff --git a/qiskit/extensions/__init__.py b/qiskit/extensions/__init__.py deleted file mode 100644 index d0685f0a0d03..000000000000 --- a/qiskit/extensions/__init__.py +++ /dev/null @@ -1,70 +0,0 @@ -# This code is part of Qiskit. -# -# (C) Copyright IBM 2017. -# -# This code is licensed under the Apache License, Version 2.0. You may -# obtain a copy of this license in the LICENSE.txt file in the root directory -# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. -# -# Any modifications or derivative works of this code must retain this -# copyright notice, and modified files need to carry a notice indicating -# that they have been altered from the originals. - -""" -===================================================== -Quantum Circuit Extensions (:mod:`qiskit.extensions`) -===================================================== - -.. currentmodule:: qiskit.extensions - -Unitary Extensions -================== - -.. autosummary:: - :toctree: ../stubs/ - - SingleQubitUnitary - -Simulator Extensions -==================== - -.. autosummary:: - :toctree: ../stubs/ - - Snapshot - -Exceptions -========== - -The additional gates in this module will tend to raise a custom exception when they encounter -problems. - -.. autoexception:: ExtensionError -""" - -import warnings - -# import all standard gates -from qiskit.circuit.library.standard_gates import * -from qiskit.circuit.library.hamiltonian_gate import HamiltonianGate -from qiskit.circuit.library.generalized_gates import UnitaryGate -from qiskit.circuit.barrier import Barrier - -from .exceptions import ExtensionError -from .quantum_initializer import ( - Initialize, - SingleQubitUnitary, - UCPauliRotGate, - UCRXGate, - UCRYGate, - UCRZGate, -) -from .simulator import Snapshot - - -warnings.warn( - "The qiskit.extensions module is pending deprecation since Qiskit 0.45.0. It will be deprecated " - "in a following release, no sooner than 3 months after the 0.45.0 release.", - stacklevel=2, - category=PendingDeprecationWarning, -) diff --git a/qiskit/extensions/exceptions.py b/qiskit/extensions/exceptions.py deleted file mode 100644 index 7a3f052e19f1..000000000000 --- a/qiskit/extensions/exceptions.py +++ /dev/null @@ -1,31 +0,0 @@ -# This code is part of Qiskit. -# -# (C) Copyright IBM 2017. -# -# This code is licensed under the Apache License, Version 2.0. You may -# obtain a copy of this license in the LICENSE.txt file in the root directory -# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. -# -# Any modifications or derivative works of this code must retain this -# copyright notice, and modified files need to carry a notice indicating -# that they have been altered from the originals. - -""" -Exception for errors raised by extensions module. -""" -from qiskit.exceptions import QiskitError -from qiskit.utils.deprecation import deprecate_func - - -class ExtensionError(QiskitError): - """Base class for errors raised by extensions module.""" - - @deprecate_func(since="0.45.0", pending=True) - def __init__(self, *message): - """Set the error message.""" - super().__init__(*message) - self.message = " ".join(message) - - def __str__(self): - """Return the message.""" - return repr(self.message) diff --git a/qiskit/extensions/quantum_initializer/__init__.py b/qiskit/extensions/quantum_initializer/__init__.py deleted file mode 100644 index 27f24443bd02..000000000000 --- a/qiskit/extensions/quantum_initializer/__init__.py +++ /dev/null @@ -1,26 +0,0 @@ -# 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. - -"""Initialize qubit registers to desired arbitrary state.""" - -from qiskit.circuit.library import ( - UCPauliRotGate, - UCRZGate, - UCRYGate, - UCRXGate, - DiagonalGate, - UCGate, - Isometry, - Initialize, -) - -from .squ import SingleQubitUnitary diff --git a/qiskit/extensions/quantum_initializer/squ.py b/qiskit/extensions/quantum_initializer/squ.py deleted file mode 100644 index 8356dc86fb9f..000000000000 --- a/qiskit/extensions/quantum_initializer/squ.py +++ /dev/null @@ -1,163 +0,0 @@ -# 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. - -"""Decompose an arbitrary 2*2 unitary into three rotation gates: U=R_zR_yR_z. - -Note that the decomposition is up to a global phase shift. -(This is a well known decomposition, which can be found for example in Nielsen and Chuang's book -"Quantum computation and quantum information".) -""" - -import cmath - -import numpy as np - -from qiskit.circuit import QuantumRegister, QuantumCircuit -from qiskit.circuit.gate import Gate -from qiskit.circuit.exceptions import CircuitError -from qiskit.quantum_info.operators.predicates import is_unitary_matrix -from qiskit.exceptions import QiskitError -from qiskit.utils.deprecation import deprecate_func - -_EPS = 1e-10 # global variable used to chop very small numbers to zero - - -class SingleQubitUnitary(Gate): - """Single-qubit unitary. - - Args: - unitary_matrix: :math:`2 \times 2` unitary (given as a (complex) ``numpy.ndarray``). - mode: determines the used decomposition by providing the rotation axes. - up_to_diagonal: the single-qubit unitary is decomposed up to a diagonal matrix, - i.e. a unitary :math:`U'` is implemented such that there exists a diagonal - matrix :math:`D` with :math:`U = D U'`. - """ - - @deprecate_func( - since="0.45.0", - additional_msg="Instead, you can use qiskit.circuit.library.UnitaryGate.", - ) - def __init__(self, unitary_matrix, mode="ZYZ", up_to_diagonal=False): - """Create a new single qubit gate based on the unitary ``u``.""" - if mode not in ["ZYZ"]: - raise QiskitError("The decomposition mode is not known.") - # Check if the matrix u has the right dimensions and if it is a unitary - if unitary_matrix.shape != (2, 2): - raise QiskitError("The dimension of the input matrix is not equal to (2,2).") - if not is_unitary_matrix(unitary_matrix): - raise QiskitError("The 2*2 matrix is not unitary.") - - self.mode = mode - self.up_to_diagonal = up_to_diagonal - self._diag = None - - # Create new gate - super().__init__("squ", 1, [unitary_matrix]) - - def inverse(self): - """Return the inverse. - - Note that the resulting gate has an empty ``params`` property. - """ - inverse_gate = Gate( - name=self.name + "_dg", num_qubits=self.num_qubits, params=[] - ) # removing the params because arrays are deprecated - - definition = QuantumCircuit(*self.definition.qregs) - for inst in reversed(self._definition): - definition._append(inst.replace(operation=inst.operation.inverse())) - inverse_gate.definition = definition - return inverse_gate - - @property - def diag(self): - """Returns the diagonal gate D up to which the single-qubit unitary u is implemented. - - I.e. u=D.u', where u' is the unitary implemented by the found circuit. - """ - if self._diag is None: - self._define() - return self._diag - - def _define(self): - """Define the gate using the decomposition.""" - - if self.mode == "ZYZ": - circuit, diag = self._zyz_circuit() - else: - raise QiskitError("The decomposition mode is not known.") - - self._diag = diag - - self.definition = circuit - - def _zyz_circuit(self): - """Get the circuit for the ZYZ decomposition.""" - q = QuantumRegister(self.num_qubits) - qc = QuantumCircuit(q, name=self.name) - - diag = [1.0, 1.0] - alpha, beta, gamma, _ = self._zyz_dec() - - if abs(alpha) > _EPS: - qc.rz(alpha, q[0]) - if abs(beta) > _EPS: - qc.ry(beta, q[0]) - if abs(gamma) > _EPS: - if self.up_to_diagonal: - diag = [np.exp(-1j * gamma / 2.0), np.exp(1j * gamma / 2.0)] - else: - qc.rz(gamma, q[0]) - - return qc, diag - - def _zyz_dec(self): - """Finds rotation angles (a,b,c,d) in the decomposition u=exp(id)*Rz(c).Ry(b).Rz(a). - - Note that where "." denotes matrix multiplication. - """ - unitary = self.params[0] - u00 = unitary.item(0, 0) - u01 = unitary.item(0, 1) - u10 = unitary.item(1, 0) - u11 = unitary.item(1, 1) - # Handle special case if the entry (0,0) of the unitary is equal to zero - if np.abs(u00) < _EPS: - # Note that u10 can't be zero, since u is unitary (and u00 == 0) - gamma = cmath.phase(-u01 / u10) - delta = cmath.phase(u01 * np.exp(-1j * gamma / 2)) - return 0.0, -np.pi, -gamma, delta - # Handle special case if the entry (0,1) of the unitary is equal to zero - if np.abs(u01) < _EPS: - # Note that u11 can't be zero, since u is unitary (and u01 == 0) - gamma = cmath.phase(u00 / u11) - delta = cmath.phase(u00 * np.exp(-1j * gamma / 2)) - return 0.0, 0.0, -gamma, delta - beta = 2 * np.arccos(np.abs(u00)) - if np.sin(beta / 2) - np.cos(beta / 2) > 0: - gamma = cmath.phase(-u00 / u10) - alpha = cmath.phase(u00 / u01) - else: - gamma = -cmath.phase(-u10 / u00) - alpha = -cmath.phase(u01 / u00) - delta = cmath.phase(u00 * np.exp(-1j * (alpha + gamma) / 2)) - # The decomposition works with another convention for the rotation gates - # (the one using negative angles). - # Therefore, we have to take the inverse of the angles at the end. - return -alpha, -beta, -gamma, delta - - def validate_parameter(self, parameter): - """Single-qubit unitary gate parameter has to be an ndarray.""" - if isinstance(parameter, np.ndarray): - return parameter - else: - raise CircuitError(f"invalid param type {type(parameter)} in gate {self.name}") diff --git a/qiskit/extensions/simulator/__init__.py b/qiskit/extensions/simulator/__init__.py deleted file mode 100644 index 069ec393979e..000000000000 --- a/qiskit/extensions/simulator/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# This code is part of Qiskit. -# -# (C) Copyright IBM 2017. -# -# This code is licensed under the Apache License, Version 2.0. You may -# obtain a copy of this license in the LICENSE.txt file in the root directory -# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. -# -# Any modifications or derivative works of this code must retain this -# copyright notice, and modified files need to carry a notice indicating -# that they have been altered from the originals. - -"""Instructions usable by simulator backends.""" - -from .snapshot import Snapshot diff --git a/qiskit/extensions/simulator/snapshot.py b/qiskit/extensions/simulator/snapshot.py deleted file mode 100644 index ca45e56354ac..000000000000 --- a/qiskit/extensions/simulator/snapshot.py +++ /dev/null @@ -1,70 +0,0 @@ -# This code is part of Qiskit. -# -# (C) Copyright IBM 2017. -# -# This code is licensed under the Apache License, Version 2.0. You may -# obtain a copy of this license in the LICENSE.txt file in the root directory -# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. -# -# Any modifications or derivative works of this code must retain this -# copyright notice, and modified files need to carry a notice indicating -# that they have been altered from the originals. -""" -Simulator command to snapshot internal simulator representation. -""" - -from qiskit.circuit.instruction import Instruction -from qiskit.extensions.exceptions import QiskitError, ExtensionError - -from qiskit.utils.deprecation import deprecate_func - - -class Snapshot(Instruction): - """Simulator snapshot instruction.""" - - _directive = True - - @deprecate_func( - since="0.45.0", - additional_msg="The Snapshot instruction has been superseded by Qiskit Aer's save " - "instructions, see " - "https://qiskit.org/ecosystem/aer/apidocs/aer_library.html#saving-simulator-data.", - ) - def __init__(self, label, snapshot_type="statevector", num_qubits=0, num_clbits=0, params=None): - """Create new snapshot instruction. - - Args: - label (str): the snapshot label for result data. - snapshot_type (str): the type of the snapshot. - num_qubits (int): the number of qubits for the snapshot type [Default: 0]. - num_clbits (int): the number of classical bits for the snapshot type - [Default: 0]. - params (list or None): the parameters for snapshot_type [Default: None]. - - Raises: - ExtensionError: if snapshot label is invalid. - """ - if not isinstance(label, str): - raise ExtensionError("Snapshot label must be a string.") - self._snapshot_type = snapshot_type - if params is None: - params = [] - super().__init__("snapshot", num_qubits, num_clbits, params, label=label) - - def assemble(self): - """Assemble a QasmQobjInstruction""" - instruction = super().assemble() - instruction.snapshot_type = self._snapshot_type - return instruction - - def inverse(self): - """Special case. Return self.""" - return Snapshot(self.num_qubits, self.num_clbits, self.params[0], self.params[1]) - - @property - def snapshot_type(self): - """Return snapshot type""" - return self._snapshot_type - - def c_if(self, classical, val): - raise QiskitError("Snapshots are simulator directives and cannot be conditional.") diff --git a/qiskit/qpy/binary_io/circuits.py b/qiskit/qpy/binary_io/circuits.py index cdf1a27657fe..5d6365ff5241 100644 --- a/qiskit/qpy/binary_io/circuits.py +++ b/qiskit/qpy/binary_io/circuits.py @@ -24,7 +24,6 @@ import numpy as np from qiskit import circuit as circuit_mod -from qiskit import extensions from qiskit.circuit import library, controlflow, CircuitInstruction, ControlFlowOp from qiskit.circuit.classical import expr from qiskit.circuit.classicalregister import ClassicalRegister, Clbit @@ -34,7 +33,6 @@ from qiskit.circuit.instruction import Instruction from qiskit.circuit.quantumcircuit import QuantumCircuit from qiskit.circuit.quantumregister import QuantumRegister, Qubit -from qiskit.extensions import quantum_initializer from qiskit.qpy import common, formats, type_keys from qiskit.qpy.binary_io import value, schedules from qiskit.quantum_info.operators import SparsePauliOp, Clifford @@ -43,7 +41,6 @@ def _read_header_v2(file_obj, version, vectors, metadata_deserializer=None): - data = formats.CIRCUIT_HEADER_V2._make( struct.unpack( formats.CIRCUIT_HEADER_V2_PACK, @@ -284,10 +281,6 @@ def _read_instruction( gate_class = getattr(library, gate_name) elif hasattr(circuit_mod, gate_name): gate_class = getattr(circuit_mod, gate_name) - elif hasattr(extensions, gate_name): - gate_class = getattr(extensions, gate_name) - elif hasattr(quantum_initializer, gate_name): - gate_class = getattr(quantum_initializer, gate_name) elif hasattr(controlflow, gate_name): gate_class = getattr(controlflow, gate_name) elif gate_name == "Clifford": @@ -590,8 +583,6 @@ def _write_instruction(file_obj, instruction, custom_operations, index_map, use_ ( not hasattr(library, gate_class_name) and not hasattr(circuit_mod, gate_class_name) - and not hasattr(extensions, gate_class_name) - and not hasattr(quantum_initializer, gate_class_name) and not hasattr(controlflow, gate_class_name) and gate_class_name != "Clifford" ) diff --git a/qiskit/visualization/circuit/matplotlib.py b/qiskit/visualization/circuit/matplotlib.py index 558e6637da1d..a0d4d0ff8047 100644 --- a/qiskit/visualization/circuit/matplotlib.py +++ b/qiskit/visualization/circuit/matplotlib.py @@ -37,6 +37,7 @@ from qiskit.circuit.controlflow import condition_resources from qiskit.circuit.classical import expr from qiskit.circuit.annotated_operation import _canonicalize_modifiers, ControlModifier +from qiskit.circuit.library import Initialize from qiskit.circuit.library.standard_gates import ( SwapGate, RZZGate, @@ -48,7 +49,6 @@ from qiskit.qasm3.exporter import QASM3Builder from qiskit.qasm3.printer import BasicPrinter -from qiskit.extensions import Initialize from qiskit.circuit.tools.pi_check import pi_check from qiskit.utils import optionals as _optionals diff --git a/releasenotes/notes/remove-extensions-ce520ba419c93c58.yaml b/releasenotes/notes/remove-extensions-ce520ba419c93c58.yaml new file mode 100644 index 000000000000..ae9eb6e8176b --- /dev/null +++ b/releasenotes/notes/remove-extensions-ce520ba419c93c58.yaml @@ -0,0 +1,47 @@ +--- +upgrade: + - | + Removed the ``qiskit.extensions`` module, which has been pending deprecation since the 0.45 release + and has been fully deprecated in the 0.46 release. + The following operations from this module are available in :mod:`qiskit.circuit.library`: + + * :class:`~.library.DiagonalGate`, + * :class:`~.library.HamiltonianGateGate`, + * :class:`~.library.Initialize`, + * :class:`~.library.Isometry`, + * :class:`~.library.generalized_gates.mcg_up_diag.MCGupDiag`, + * :class:`~.library.UCGate`, + * :class:`~.library.UCPauliRotGate`, + * :class:`~.library.UCRXGate`, + * :class:`~.library.UCRYGate`, + * :class:`~.library.UCRZGate`, + * :class:`~.library.UnitaryGate`. + + The following objects have been removed: + + * ``SingleQubitUnitary`` (instead use :class:`.library.UnitaryGate`), + * ``Snapshot`` (superseded by Qiskit Aer's save instructions), + * ``ExtensionError``, + + along with the following circuit methods:: + + * ``QuantumCircuit.snapshot``, + * ``QuantumCircuit.squ``, + * ``QuantumCircuit.diagonal``, + * ``QuantumCircuit.hamiltonian``, + * ``QuantumCircuit.isometry`` and ``QuantumCircuit.iso``, + * ``QuantumCircuit.uc``, + * ``QuantumCircuit.ucrx``, + * ``QuantumCircuit.ucry``, + * ``QuantumCircuit.ucrz``. + + These operations can still be performed by appending the appropriate + instruction to a quantum circuit. + - | + Removed deprecated, duplicated :class:`.QuantumCircuit` methods. These include + + * ``QuantumCircuit.cnot``, instead use :meth:`.QuantumCircuit.cx`, + * ``QuantumCircuit.toffoli``, instead use :meth:`.QuantumCircuit.ccx`, + * ``QuantumCircuit.fredkin``, instead use :meth:`.QuantumCircuit.cswap`, + * ``QuantumCircuit.mct``, instead use :meth:`.QuantumCircuit.mcx`, + * ``QuantumCircuit.i``, instead use :meth:`.QuantumCircuit.id`. diff --git a/test/python/circuit/test_circuit_load_from_qpy.py b/test/python/circuit/test_circuit_load_from_qpy.py index c3d9aed88336..570b695c5922 100644 --- a/test/python/circuit/test_circuit_load_from_qpy.py +++ b/test/python/circuit/test_circuit_load_from_qpy.py @@ -44,6 +44,7 @@ UCRYGate, UCRZGate, UnitaryGate, + DiagonalGate, ) from qiskit.circuit.instruction import Instruction from qiskit.circuit.parameter import Parameter @@ -1456,15 +1457,16 @@ def test_incomplete_owned_bits(self): def test_diagonal_gate(self): """Test that a `DiagonalGate` successfully roundtrips.""" + diag = DiagonalGate([1, -1, -1, 1]) + qc = QuantumCircuit(2) - with self.assertWarns(PendingDeprecationWarning): - qc.diagonal([1, -1, -1, 1], [0, 1]) + qc.append(diag, [0, 1]) with io.BytesIO() as fptr: dump(qc, fptr) fptr.seek(0) new_circuit = load(fptr)[0] - # DiagonalGate (and a bunch of the qiskit.extensions gates) have non-deterministic + # DiagonalGate (and some of the qiskit.circuit.library gates) have non-deterministic # definitions with regard to internal instruction names, so cannot be directly compared for # equality. self.assertIs(type(qc.data[0].operation), type(new_circuit.data[0].operation)) diff --git a/test/python/circuit/test_circuit_operations.py b/test/python/circuit/test_circuit_operations.py index 2dc2ed592634..90ac61197dd2 100644 --- a/test/python/circuit/test_circuit_operations.py +++ b/test/python/circuit/test_circuit_operations.py @@ -1379,28 +1379,6 @@ def instructions(): self.assertEqual(circuit, expected) self.assertEqual(circuit.name, "test") - def test_duplicated_methods_deprecation(self): - """Test the now deprecated, duplicated gate method emit a deprecation warning.""" - - # {duplicate: (use_this_instead, args)} - methods = { - "i": ("id", [0]), - "cnot": ("cx", [0, 1]), - "toffoli": ("ccx", [0, 1, 2]), - "mct": ("mcx", [[0, 1], 2]), - "fredkin": ("cswap", [0, 1, 2]), - } - - for old, (new, args) in methods.items(): - circuit = QuantumCircuit(3) - - with self.subTest(method=old): - - # check (1) the (pending) deprecation is raised - # and (2) the new method is documented there - with self.assertWarnsRegex(DeprecationWarning, new): - getattr(circuit, old)(*args) - class TestCircuitPrivateOperations(QiskitTestCase): """Direct tests of some of the private methods of QuantumCircuit. These do not represent diff --git a/test/python/circuit/test_circuit_properties.py b/test/python/circuit/test_circuit_properties.py index f2531954676e..da9af61367a8 100644 --- a/test/python/circuit/test_circuit_properties.py +++ b/test/python/circuit/test_circuit_properties.py @@ -19,7 +19,6 @@ from qiskit.circuit.library import RXGate, RYGate from qiskit.test import QiskitTestCase from qiskit.circuit.exceptions import CircuitError -from qiskit.extensions.simulator import Snapshot class TestCircuitProperties(QiskitTestCase): @@ -561,80 +560,6 @@ def test_circuit_depth_barriers3(self): circ.cx(2, 3) self.assertEqual(circ.depth(), 4) - def test_circuit_depth_snap1(self): - """Test circuit depth for snapshots #1.""" - - # ┌───┐ ░ - # q_0: ┤ H ├──■───░─────────── - # └───┘┌─┴─┐ ░ - # q_1: ─────┤ X ├─░─────────── - # └───┘ ░ ┌───┐ - # q_2: ───────────░─┤ H ├──■── - # ░ └───┘┌─┴─┐ - # q_3: ───────────░──────┤ X ├ - # ░ └───┘ - q = QuantumRegister(4, "q") - c = ClassicalRegister(4, "c") - circ = QuantumCircuit(q, c) - circ.h(0) - circ.cx(0, 1) - with self.assertWarns(DeprecationWarning): - circ.append(Snapshot("snap", num_qubits=4), [0, 1, 2, 3]) - circ.h(2) - circ.cx(2, 3) - self.assertEqual(circ.depth(), 4) - - def test_circuit_depth_snap2(self): - """Test circuit depth for snapshots #2.""" - - # ┌───┐ ░ ░ ░ - # q_0: ┤ H ├─░───■───░───────░────── - # └───┘ ░ ┌─┴─┐ ░ ░ - # q_1: ──────░─┤ X ├─░───────░────── - # ░ └───┘ ░ ┌───┐ ░ - # q_2: ──────░───────░─┤ H ├─░───■── - # ░ ░ └───┘ ░ ┌─┴─┐ - # q_3: ──────░───────░───────░─┤ X ├ - # ░ ░ ░ └───┘ - q = QuantumRegister(4, "q") - c = ClassicalRegister(4, "c") - circ = QuantumCircuit(q, c) - circ.h(0) - with self.assertWarns(DeprecationWarning): - circ.append(Snapshot("snap0", num_qubits=4), [0, 1, 2, 3]) - circ.cx(0, 1) - with self.assertWarns(DeprecationWarning): - circ.append(Snapshot("snap1", num_qubits=4), [0, 1, 2, 3]) - circ.h(2) - with self.assertWarns(DeprecationWarning): - circ.append(Snapshot("snap2", num_qubits=4), [0, 1, 2, 3]) - circ.cx(2, 3) - self.assertEqual(circ.depth(), 4) - - def test_circuit_depth_snap3(self): - """Test circuit depth for snapshots #3.""" - - # ┌───┐ ░ ░ - # q_0: ┤ H ├──■───░──░─────────── - # └───┘┌─┴─┐ ░ ░ - # q_1: ─────┤ X ├─░──░─────────── - # └───┘ ░ ░ ┌───┐ - # q_2: ───────────░──░─┤ H ├──■── - # ░ ░ └───┘┌─┴─┐ - # q_3: ───────────░──░──────┤ X ├ - # ░ ░ └───┘ - q = QuantumRegister(4, "q") - c = ClassicalRegister(4, "c") - circ = QuantumCircuit(q, c) - circ.h(0) - circ.cx(0, 1) - with self.assertWarns(DeprecationWarning): - circ.append(Snapshot("snap0", num_qubits=4), [0, 1, 2, 3]) - circ.append(Snapshot("snap1", num_qubits=4), [0, 1, 2, 3]) - circ.h(2) - circ.cx(2, 3) - self.assertEqual(circ.depth(), 4) - def test_circuit_depth_2qubit(self): """Test finding depth of two-qubit gates only.""" @@ -745,21 +670,6 @@ def test_circuit_size_2qubit(self): qc.rzz(0.1, q[1], q[2]) self.assertEqual(qc.size(lambda x: x.operation.num_qubits == 2), 2) - def test_circuit_size_ignores_barriers_snapshots(self): - """Circuit.size should not count barriers or snapshots.""" - q = QuantumRegister(4, "q") - c = ClassicalRegister(4, "c") - qc = QuantumCircuit(q, c) - - qc.h(q[0]) - qc.cx(q[0], q[1]) - self.assertEqual(qc.size(), 2) - qc.barrier(q) - self.assertEqual(qc.size(), 2) - with self.assertWarns(DeprecationWarning): - qc.append(Snapshot("snapshot_label", num_qubits=4), [0, 1, 2, 3]) - self.assertEqual(qc.size(), 2) - def test_circuit_count_ops(self): """Test circuit count ops.""" q = QuantumRegister(6, "q") diff --git a/test/python/circuit/test_controlled_gate.py b/test/python/circuit/test_controlled_gate.py index 7f3bcee95f12..34bf21f30e2e 100644 --- a/test/python/circuit/test_controlled_gate.py +++ b/test/python/circuit/test_controlled_gate.py @@ -1016,7 +1016,7 @@ def test_open_control_composite_unrolling(self): @data(*ControlledGate.__subclasses__()) def test_standard_base_gate_setting(self, gate_class): - """Test all gates in standard extensions which are of type ControlledGate + """Test all standard gates which are of type ControlledGate and have a base gate setting. """ if gate_class in {SingletonControlledGate, _SingletonControlledGateOverrides}: @@ -1044,9 +1044,7 @@ def test_standard_base_gate_setting(self, gate_class): ctrl_state=[None, 0, 1], ) def test_all_inverses(self, gate, num_ctrl_qubits, ctrl_state): - """Test all gates in standard extensions except those that cannot be controlled - or are being deprecated. - """ + """Test all standard gates except those that cannot be controlled.""" if not (issubclass(gate, ControlledGate) or issubclass(gate, allGates.IGate)): # only verify basic gates right now, as already controlled ones # will generate differing definitions @@ -1146,7 +1144,7 @@ def test_open_controlled_gate_raises(self): def test_base_gate_params_reference(self): """ - Test all gates in standard extensions which are of type ControlledGate and have a base gate + Test all standard gates which are of type ControlledGate and have a base gate setting have params which reference the one in their base gate. """ num_ctrl_qubits = 1 diff --git a/test/python/circuit/test_diagonal_gate.py b/test/python/circuit/test_diagonal_gate.py index c0379e4fd9c1..550ab2d45567 100644 --- a/test/python/circuit/test_diagonal_gate.py +++ b/test/python/circuit/test_diagonal_gate.py @@ -16,12 +16,12 @@ import unittest import numpy as np -from qiskit import QuantumCircuit, QuantumRegister, BasicAer, execute, assemble +from qiskit import QuantumCircuit, BasicAer, execute, assemble from qiskit import QiskitError from qiskit.test import QiskitTestCase from qiskit.compiler import transpile -from qiskit.extensions.quantum_initializer import DiagonalGate +from qiskit.circuit.library.generalized_gates import DiagonalGate from qiskit.quantum_info.operators.predicates import matrix_equal @@ -44,10 +44,10 @@ def test_diag_gate(self): with self.subTest(phases=phases): diag = [np.exp(1j * ph) for ph in phases] num_qubits = int(np.log2(len(diag))) - q = QuantumRegister(num_qubits) - qc = QuantumCircuit(q) - with self.assertWarns(PendingDeprecationWarning): - qc.diagonal(diag, q[0:num_qubits]) + qc = QuantumCircuit(num_qubits) + gate = DiagonalGate(diag) + qc.append(gate, qc.qubits) + # Decompose the gate qc = transpile(qc, basis_gates=["u1", "u3", "u2", "cx", "id"], optimization_level=0) # Simulate the decomposed gate @@ -62,16 +62,15 @@ def test_mod1_entries(self): from qiskit.quantum_info.operators.predicates import ATOL_DEFAULT, RTOL_DEFAULT with self.assertRaises(QiskitError): - with self.assertWarns(PendingDeprecationWarning): - DiagonalGate([1, 1 - 2 * ATOL_DEFAULT - RTOL_DEFAULT]) + DiagonalGate([1, 1 - 2 * ATOL_DEFAULT - RTOL_DEFAULT]) def test_npcomplex_params_conversion(self): """Verify diagonal gate converts numpy.complex to complex.""" # ref: https://github.com/Qiskit/qiskit-aer/issues/696 diag = np.array([1 + 0j, 1 + 0j]) qc = QuantumCircuit(1) - with self.assertWarns(PendingDeprecationWarning): - qc.diagonal(diag.tolist(), [0]) + gate = DiagonalGate(diag) + qc.append(gate, [0]) params = qc.data[0].operation.params self.assertTrue( diff --git a/test/python/circuit/test_isometry.py b/test/python/circuit/test_isometry.py index 774e2368803f..3ef9a73fb759 100644 --- a/test/python/circuit/test_isometry.py +++ b/test/python/circuit/test_isometry.py @@ -52,11 +52,10 @@ def test_isometry(self, iso): iso = iso.reshape((len(iso), 1)) num_q_output = int(np.log2(iso.shape[0])) num_q_input = int(np.log2(iso.shape[1])) - q = QuantumRegister(num_q_output) - qc = QuantumCircuit(q) + qc = QuantumCircuit(num_q_output) - with self.assertWarns(PendingDeprecationWarning): - qc.iso(iso, q[:num_q_input], q[num_q_input:]) + gate = Isometry(iso, num_ancillas_zero=0, num_ancillas_dirty=0) + qc.append(gate, qc.qubits) # Verify the circuit can be decomposed self.assertIsInstance(qc.decompose(), QuantumCircuit) @@ -93,12 +92,11 @@ def test_isometry_tolerance(self, iso): iso = iso.reshape((len(iso), 1)) num_q_output = int(np.log2(iso.shape[0])) num_q_input = int(np.log2(iso.shape[1])) - q = QuantumRegister(num_q_output) - qc = QuantumCircuit(q) + qc = QuantumCircuit(num_q_output) # Compute isometry with custom tolerance - with self.assertWarns(PendingDeprecationWarning): - qc.isometry(iso, q[:num_q_input], q[num_q_input:], epsilon=1e-3) + gate = Isometry(iso, num_ancillas_zero=0, num_ancillas_dirty=0, epsilon=1e-3) + qc.append(gate, qc.qubits) # Verify the circuit can be decomposed self.assertIsInstance(qc.decompose(), QuantumCircuit) diff --git a/test/python/circuit/test_operation.py b/test/python/circuit/test_operation.py index 7e98142ae612..f8989e644c59 100644 --- a/test/python/circuit/test_operation.py +++ b/test/python/circuit/test_operation.py @@ -102,7 +102,7 @@ def test_pauli_as_operation(self): def test_isometry_as_operation(self): """Test that we can instantiate an object of class - :class:`~qiskit.extensions.quantum_initializer.Isometry` and that + :class:`~qiskit.circuit.library.Isometry` and that it has the expected name, num_qubits and num_clbits. """ op = Isometry(np.eye(4, 4), 3, 2) @@ -113,7 +113,7 @@ def test_isometry_as_operation(self): def test_initialize_as_operation(self): """Test that we can instantiate an object of class - :class:`~qiskit.extensions.quantum_initializer.Initialize` and that + :class:`~qiskit.circuit.library.Initialize` and that it has the expected name, num_qubits and num_clbits. """ desired_vector = [0.5, 0.5, 0.5, 0.5] diff --git a/test/python/circuit/test_squ.py b/test/python/circuit/test_squ.py deleted file mode 100644 index e80a17e20b68..000000000000 --- a/test/python/circuit/test_squ.py +++ /dev/null @@ -1,65 +0,0 @@ -# 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. - -# pylint: disable=invalid-name - -"""Single-qubit unitary tests.""" - -import unittest -from test import combine -import numpy as np -from ddt import ddt -from qiskit.quantum_info.random import random_unitary -from qiskit import BasicAer, QuantumCircuit, QuantumRegister -from qiskit.test import QiskitTestCase -from qiskit.extensions.quantum_initializer.squ import SingleQubitUnitary -from qiskit.compiler import transpile -from qiskit.quantum_info.operators.predicates import matrix_equal - -squs = [ - np.eye(2, 2), - np.array([[0.0, 1.0], [1.0, 0.0]]), - 1 / np.sqrt(2) * np.array([[1.0, 1.0], [-1.0, 1.0]]), - np.array([[np.exp(1j * 5.0 / 2), 0], [0, np.exp(-1j * 5.0 / 2)]]), - random_unitary(2, seed=42).data, -] - -up_to_diagonal_list = [True, False] - - -@ddt -class TestSingleQubitUnitary(QiskitTestCase): - """Qiskit ZYZ-decomposition tests.""" - - @combine(u=squs, up_to_diagonal=up_to_diagonal_list) - def test_squ(self, u, up_to_diagonal): - """Tests for single-qubit unitary decomposition.""" - qr = QuantumRegister(1, "qr") - qc = QuantumCircuit(qr) - with self.assertWarns(DeprecationWarning): - qc.squ(u, qr[0], up_to_diagonal=up_to_diagonal) - # Decompose the gate - qc = transpile(qc, basis_gates=["u1", "u3", "u2", "cx", "id"]) - # Simulate the decomposed gate - simulator = BasicAer.get_backend("unitary_simulator") - result = simulator.run(qc).result() - unitary = result.get_unitary(qc) - if up_to_diagonal: - with self.assertWarns(DeprecationWarning): - squ = SingleQubitUnitary(u, up_to_diagonal=up_to_diagonal) - unitary = np.dot(np.diagflat(squ.diag), unitary) - unitary_desired = u - self.assertTrue(matrix_equal(unitary_desired, unitary, ignore_phase=True)) - - -if __name__ == "__main__": - unittest.main() diff --git a/test/python/circuit/test_uc.py b/test/python/circuit/test_uc.py index 9a7b5757a769..969dfe67f021 100644 --- a/test/python/circuit/test_uc.py +++ b/test/python/circuit/test_uc.py @@ -59,9 +59,8 @@ def test_ucg(self, squs, up_to_diagonal): q = QuantumRegister(num_con + 1) qc = QuantumCircuit(q) - with self.assertWarns(PendingDeprecationWarning): - # TODO: change to directly appending UCGate once deprecation period of the method is over - qc.uc(squs, q[1:], q[0], up_to_diagonal=up_to_diagonal) + uc = UCGate(squs, up_to_diagonal=up_to_diagonal) + qc.append(uc, q) # Decompose the gate qc = transpile(qc, basis_gates=["u1", "u3", "u2", "cx", "id"]) diff --git a/test/python/circuit/test_ucx_y_z.py b/test/python/circuit/test_ucx_y_z.py index 23ea57111fbb..c6dc491f8636 100644 --- a/test/python/circuit/test_ucx_y_z.py +++ b/test/python/circuit/test_ucx_y_z.py @@ -14,7 +14,6 @@ import itertools import unittest -from ddt import ddt, data import numpy as np from scipy.linalg import block_diag @@ -41,14 +40,11 @@ rot_axis_list = ["X", "Y", "Z"] -@ddt class TestUCRXYZ(QiskitTestCase): """Qiskit tests for UCRXGate, UCRYGate and UCRZGate rotations gates.""" - @data(True, False) - def test_ucy(self, use_method): + def test_ucy(self): """Test the decomposition of uniformly controlled rotations.""" - methods = {"X": "ucrx", "Y": "ucry", "Z": "ucrz"} gates = {"X": UCRXGate, "Y": UCRYGate, "Z": UCRZGate} for angles, rot_axis in itertools.product(angles_list, rot_axis_list): @@ -56,12 +52,8 @@ def test_ucy(self, use_method): num_contr = int(np.log2(len(angles))) q = QuantumRegister(num_contr + 1) qc = QuantumCircuit(q) - if use_method: - with self.assertWarns(PendingDeprecationWarning): - getattr(qc, methods[rot_axis])(angles, q[1 : num_contr + 1], q[0]) - else: - gate = gates[rot_axis](angles) - qc.append(gate, q) + gate = gates[rot_axis](angles) + qc.append(gate, q) # Decompose the gate qc = transpile(qc, basis_gates=["u1", "u3", "u2", "cx", "id"]) diff --git a/test/python/transpiler/test_unroller.py b/test/python/transpiler/test_unroller.py index a69d7667ef2b..c43953f221d9 100644 --- a/test/python/transpiler/test_unroller.py +++ b/test/python/transpiler/test_unroller.py @@ -16,7 +16,6 @@ from numpy import pi from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit -from qiskit.extensions.simulator import Snapshot from qiskit.transpiler.passes import Unroller from qiskit.converters import circuit_to_dag, dag_to_circuit from qiskit.quantum_info import Operator @@ -774,15 +773,6 @@ def test_unroll_z(self): self.ref_circuit.append(U3Gate(0, 0, pi), [0]) self.compare_dags() - def test_unroll_snapshot(self): - """test unroll snapshot""" - num_qubits = self.circuit.num_qubits - with self.assertWarns(DeprecationWarning): - instr = Snapshot("0", num_qubits=num_qubits) - self.circuit.append(instr, range(num_qubits)) - self.ref_circuit.append(instr, range(num_qubits)) - self.compare_dags() - def test_unroll_measure(self): """test unroll measure""" self.circuit.measure(self.qr, self.cr) diff --git a/test/python/visualization/references/test_latex_plot_barriers_false.tex b/test/python/visualization/references/test_latex_plot_barriers_false.tex index 06e3519367ad..8c256729101a 100644 --- a/test/python/visualization/references/test_latex_plot_barriers_false.tex +++ b/test/python/visualization/references/test_latex_plot_barriers_false.tex @@ -6,8 +6,8 @@ \begin{document} \scalebox{1.0}{ \Qcircuit @C=1.0em @R=0.2em @!R { \\ - \nghost{{q}_{0} : } & \lstick{{q}_{0} : } & \gate{\mathrm{H}} & \qw & \qw & \qw & \qw & \qw\\ - \nghost{{q}_{1} : } & \lstick{{q}_{1} : } & \qw & \qw & \gate{\mathrm{H}} & \qw & \qw & \qw\\ - \nghost{\mathrm{{c} : }} & \lstick{\mathrm{{c} : }} & \lstick{/_{_{2}}} \cw & \cw & \cw & \cw & \cw & \cw\\ + \nghost{{q}_{0} : } & \lstick{{q}_{0} : } & \gate{\mathrm{H}} & \qw & \qw & \qw & \qw\\ + \nghost{{q}_{1} : } & \lstick{{q}_{1} : } & \qw & \qw & \gate{\mathrm{H}} & \qw & \qw\\ + \nghost{\mathrm{{c} : }} & \lstick{\mathrm{{c} : }} & \lstick{/_{_{2}}} \cw & \cw & \cw & \cw & \cw\\ \\ }} \end{document} \ No newline at end of file diff --git a/test/python/visualization/references/test_latex_plot_barriers_true.tex b/test/python/visualization/references/test_latex_plot_barriers_true.tex index b7679d27cd39..399e2ecd4ece 100644 --- a/test/python/visualization/references/test_latex_plot_barriers_true.tex +++ b/test/python/visualization/references/test_latex_plot_barriers_true.tex @@ -6,8 +6,8 @@ \begin{document} \scalebox{1.0}{ \Qcircuit @C=1.0em @R=0.2em @!R { \\ - \nghost{{q}_{0} : } & \lstick{{q}_{0} : } & \gate{\mathrm{H}} \barrier[0em]{1} & \qw & \qw \barrier[0em]{1} & \cds{0}{^{\mathrm{sn\,1}}} & \qw & \qw\\ - \nghost{{q}_{1} : } & \lstick{{q}_{1} : } & \qw & \qw & \gate{\mathrm{H}} & \qw & \qw & \qw\\ - \nghost{\mathrm{{c} : }} & \lstick{\mathrm{{c} : }} & \lstick{/_{_{2}}} \cw & \cw & \cw & \cw & \cw & \cw\\ + \nghost{{q}_{0} : } & \lstick{{q}_{0} : } & \gate{\mathrm{H}} \barrier[0em]{1} & \qw & \qw & \qw & \qw\\ + \nghost{{q}_{1} : } & \lstick{{q}_{1} : } & \qw & \qw & \gate{\mathrm{H}} & \qw & \qw\\ + \nghost{\mathrm{{c} : }} & \lstick{\mathrm{{c} : }} & \lstick{/_{_{2}}} \cw & \cw & \cw & \cw & \cw\\ \\ }} \end{document} \ No newline at end of file diff --git a/test/python/visualization/test_circuit_latex.py b/test/python/visualization/test_circuit_latex.py index 85f6e0c7c4e6..9f9de616d724 100644 --- a/test/python/visualization/test_circuit_latex.py +++ b/test/python/visualization/test_circuit_latex.py @@ -247,12 +247,6 @@ def test_plot_barriers(self): # check for other barrier like commands circuit.h(q[1]) - # this import appears to be unused, but is actually needed to get snapshot instruction - import qiskit.extensions.simulator # pylint: disable=unused-import - - with self.assertWarns(DeprecationWarning): - circuit.snapshot("sn 1") - # check the barriers plot properly when plot_barriers= True circuit_drawer(circuit, filename=filename1, output="latex_source", plot_barriers=True) diff --git a/test/visual/mpl/circuit/references/plot_barriers_true.png b/test/visual/mpl/circuit/references/plot_barriers_true.png index a3369938138c..cc37c63261c5 100644 Binary files a/test/visual/mpl/circuit/references/plot_barriers_true.png and b/test/visual/mpl/circuit/references/plot_barriers_true.png differ diff --git a/test/visual/mpl/circuit/test_circuit_matplotlib_drawer.py b/test/visual/mpl/circuit/test_circuit_matplotlib_drawer.py index 87798d23707c..f060f2aa8904 100644 --- a/test/visual/mpl/circuit/test_circuit_matplotlib_drawer.py +++ b/test/visual/mpl/circuit/test_circuit_matplotlib_drawer.py @@ -438,12 +438,6 @@ def test_plot_barriers(self): # check for other barrier like commands circuit.h(q[1]) - # this import appears to be unused, but is actually needed to get snapshot instruction - import qiskit.extensions.simulator # pylint: disable=unused-import - - with self.assertWarns(DeprecationWarning): - circuit.snapshot("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)