repo
stringclasses
900 values
file
stringclasses
754 values
content
stringlengths
4
215k
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# 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. """Helper function for converting a dag to a circuit.""" import copy from qiskit.circuit import QuantumCircuit, CircuitInstruction def dag_to_circuit(dag, copy_operations=True): """Build a ``QuantumCircuit`` object from a ``DAGCircuit``. Args: dag (DAGCircuit): the input dag. copy_operations (bool): Deep copy the operation objects in the :class:`~.DAGCircuit` for the output :class:`~.QuantumCircuit`. This should only be set to ``False`` if the input :class:`~.DAGCircuit` will not be used anymore as the operations in the output :class:`~.QuantumCircuit` will be shared instances and modifications to operations in the :class:`~.DAGCircuit` will be reflected in the :class:`~.QuantumCircuit` (and vice versa). Return: QuantumCircuit: the circuit representing the input dag. Example: .. plot:: :include-source: from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.dagcircuit import DAGCircuit from qiskit.converters import circuit_to_dag from qiskit.circuit.library.standard_gates import CHGate, U2Gate, CXGate from qiskit.converters import dag_to_circuit q = QuantumRegister(3, 'q') c = ClassicalRegister(3, 'c') circ = QuantumCircuit(q, c) circ.h(q[0]) circ.cx(q[0], q[1]) circ.measure(q[0], c[0]) circ.rz(0.5, q[1]).c_if(c, 2) dag = circuit_to_dag(circ) circuit = dag_to_circuit(dag) circuit.draw('mpl') """ name = dag.name or None circuit = QuantumCircuit( dag.qubits, dag.clbits, *dag.qregs.values(), *dag.cregs.values(), name=name, global_phase=dag.global_phase, ) circuit.metadata = dag.metadata circuit.calibrations = dag.calibrations for node in dag.topological_op_nodes(): op = node.op if copy_operations: op = copy.deepcopy(op) circuit._append(CircuitInstruction(op, node.qargs, node.cargs)) circuit.duration = dag.duration circuit.unit = dag.unit return circuit
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# 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. """ Arbitrary unitary circuit instruction. """ import numpy from qiskit.circuit import Gate, ControlledGate from qiskit.circuit import QuantumCircuit from qiskit.circuit import QuantumRegister, Qubit from qiskit.circuit.exceptions import CircuitError from qiskit.circuit._utils import _compute_control_matrix from qiskit.circuit.library.standard_gates import UGate from qiskit.extensions.quantum_initializer import isometry from qiskit.quantum_info.operators.predicates import matrix_equal from qiskit.quantum_info.operators.predicates import is_unitary_matrix from qiskit.quantum_info.synthesis.one_qubit_decompose import OneQubitEulerDecomposer from qiskit.quantum_info.synthesis.two_qubit_decompose import two_qubit_cnot_decompose from qiskit.extensions.exceptions import ExtensionError _DECOMPOSER1Q = OneQubitEulerDecomposer("U") class UnitaryGate(Gate): """Class quantum gates specified by a unitary matrix. Example: We can create a unitary gate from a unitary matrix then add it to a quantum circuit. The matrix can also be directly applied to the quantum circuit, see :meth:`.QuantumCircuit.unitary`. .. code-block:: python from qiskit import QuantumCircuit from qiskit.extensions import UnitaryGate matrix = [[0, 0, 0, 1], [0, 0, 1, 0], [1, 0, 0, 0], [0, 1, 0, 0]] gate = UnitaryGate(matrix) circuit = QuantumCircuit(2) circuit.append(gate, [0, 1]) """ def __init__(self, data, label=None): """Create a gate from a numeric unitary matrix. Args: data (matrix or Operator): unitary operator. label (str): unitary name for backend [Default: None]. Raises: ExtensionError: if input data is not an N-qubit unitary operator. """ if hasattr(data, "to_matrix"): # If input is Gate subclass or some other class object that has # a to_matrix method this will call that method. data = data.to_matrix() elif hasattr(data, "to_operator"): # If input is a BaseOperator subclass this attempts to convert # the object to an Operator so that we can extract the underlying # numpy matrix from `Operator.data`. data = data.to_operator().data # Convert to numpy array in case not already an array data = numpy.array(data, dtype=complex) # Check input is unitary if not is_unitary_matrix(data): raise ExtensionError("Input matrix is not unitary.") # Check input is N-qubit matrix input_dim, output_dim = data.shape num_qubits = int(numpy.log2(input_dim)) if input_dim != output_dim or 2**num_qubits != input_dim: raise ExtensionError("Input matrix is not an N-qubit operator.") # Store instruction params super().__init__("unitary", num_qubits, [data], label=label) def __eq__(self, other): if not isinstance(other, UnitaryGate): return False if self.label != other.label: return False # Should we match unitaries as equal if they are equal # up to global phase? return matrix_equal(self.params[0], other.params[0], ignore_phase=True) def __array__(self, dtype=None): """Return matrix for the unitary.""" # pylint: disable=unused-argument return self.params[0] def inverse(self): """Return the adjoint of the unitary.""" return self.adjoint() def conjugate(self): """Return the conjugate of the unitary.""" return UnitaryGate(numpy.conj(self.to_matrix())) def adjoint(self): """Return the adjoint of the unitary.""" return self.transpose().conjugate() def transpose(self): """Return the transpose of the unitary.""" return UnitaryGate(numpy.transpose(self.to_matrix())) def _define(self): """Calculate a subcircuit that implements this unitary.""" if self.num_qubits == 1: q = QuantumRegister(1, "q") qc = QuantumCircuit(q, name=self.name) theta, phi, lam, global_phase = _DECOMPOSER1Q.angles_and_phase(self.to_matrix()) qc._append(UGate(theta, phi, lam), [q[0]], []) qc.global_phase = global_phase self.definition = qc elif self.num_qubits == 2: self.definition = two_qubit_cnot_decompose(self.to_matrix()) else: from qiskit.quantum_info.synthesis.qsd import ( # pylint: disable=cyclic-import qs_decomposition, ) self.definition = qs_decomposition(self.to_matrix()) def control(self, num_ctrl_qubits=1, label=None, ctrl_state=None): """Return controlled version of gate Args: num_ctrl_qubits (int): number of controls to add to gate (default=1) label (str): optional gate label ctrl_state (int or str or None): The control state in decimal or as a bit string (e.g. '1011'). If None, use 2**num_ctrl_qubits-1. Returns: UnitaryGate: controlled version of gate. Raises: QiskitError: Invalid ctrl_state. ExtensionError: Non-unitary controlled unitary. """ mat = self.to_matrix() cmat = _compute_control_matrix(mat, num_ctrl_qubits, ctrl_state=None) iso = isometry.Isometry(cmat, 0, 0) return ControlledGate( "c-unitary", num_qubits=self.num_qubits + num_ctrl_qubits, params=[mat], label=label, num_ctrl_qubits=num_ctrl_qubits, definition=iso.definition, ctrl_state=ctrl_state, base_gate=self.copy(), ) def _qasm2_decomposition(self): """Return an unparameterized version of ourselves, so the OQ2 exporter doesn't choke on the non-standard things in our `params` field.""" out = self.definition.to_gate() out.name = self.name return out def validate_parameter(self, parameter): """Unitary gate parameter has to be an ndarray.""" if isinstance(parameter, numpy.ndarray): return parameter else: raise CircuitError(f"invalid param type {type(parameter)} in gate {self.name}") def unitary(self, obj, qubits, label=None): """Apply unitary gate specified by ``obj`` to ``qubits``. Args: obj (matrix or Operator): unitary operator. 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. Raises: ExtensionError: if input data is not an N-qubit unitary operator. Example: Apply a gate specified by a unitary matrix to a quantum circuit .. code-block:: python from qiskit import QuantumCircuit matrix = [[0, 0, 0, 1], [0, 0, 1, 0], [1, 0, 0, 0], [0, 1, 0, 0]] circuit = QuantumCircuit(2) circuit.unitary(matrix, [0, 1]) """ gate = UnitaryGate(obj, label=label) if isinstance(qubits, QuantumRegister): qubits = qubits[:] # for single qubit unitary gate, allow an 'int' or a 'list of ints' as qubits. if gate.num_qubits == 1: if isinstance(qubits, (int, Qubit)) or len(qubits) > 1: qubits = [qubits] return self.append(gate, qubits, []) QuantumCircuit.unitary = unitary
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# 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. """ Initialize qubit registers to desired arbitrary state. """ import numpy as np from qiskit.circuit import QuantumCircuit from qiskit.circuit import QuantumRegister from qiskit.circuit import Instruction from qiskit.circuit import Qubit from qiskit.circuit.library.data_preparation import StatePreparation _EPS = 1e-10 # global variable used to chop very small numbers to zero class Initialize(Instruction): """Complex amplitude initialization. Class that initializes some flexible collection of qubit registers, implemented by calling the :class:`qiskit.extensions.StatePreparation` Class. Note that Initialize is an Instruction and not a Gate since it contains a reset instruction, which is not unitary. """ def __init__(self, params, num_qubits=None, normalize=False): r"""Create new initialize composite. Args: params (str, list, int or Statevector): * Statevector: Statevector to initialize to. * list: vector of complex amplitudes to initialize to. * string: 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`. * 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`. num_qubits (int): This parameter is only used if params is an int. Indicates the total number of qubits in the `initialize` call. Example: `initialize` covers 5 qubits and params is 3. This allows qubits 0 and 1 to be initialized to :math:`|1\rangle` and the remaining 3 qubits to be initialized to :math:`|0\rangle`. normalize (bool): Whether to normalize an input array to a unit vector. """ self._stateprep = StatePreparation(params, num_qubits, normalize=normalize) super().__init__("initialize", self._stateprep.num_qubits, 0, self._stateprep.params) def _define(self): q = QuantumRegister(self.num_qubits, "q") initialize_circuit = QuantumCircuit(q, name="init_def") initialize_circuit.reset(q) initialize_circuit.append(self._stateprep, q) self.definition = initialize_circuit def gates_to_uncompute(self): """Call to create a circuit with gates that take the desired vector to zero. Returns: QuantumCircuit: circuit to take self.params vector to :math:`|{00\\ldots0}\\rangle` """ return self._stateprep._gates_to_uncompute() @property def params(self): """Return initialize params.""" return self._stateprep.params @params.setter def params(self, parameters): """Set initialize params.""" self._stateprep.params = parameters def broadcast_arguments(self, qargs, cargs): return self._stateprep.broadcast_arguments(qargs, cargs) def initialize(self, params, qubits=None, normalize=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` class to prepare the qubits in a specified state. Both these steps are included in the :class:`qiskit.extensions.Initialize` instruction. Args: params (str or list or int): * 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]. 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.initialize([1/np.sqrt(2), -1/np.sqrt(2)], 0) circuit.draw() output: .. parsed-literal:: ┌──────────────────────────────┐ q_0: ┤ Initialize(0.70711,-0.70711) ├ └──────────────────────────────┘ Initialize 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.initialize('01', circuit.qubits) circuit.draw() output: .. parsed-literal:: ┌──────────────────┐ q_0: ┤0 ├ │ Initialize(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.initialize([0, 1/np.sqrt(2), -1.j/np.sqrt(2), 0], circuit.qubits) circuit.draw() output: .. parsed-literal:: ┌────────────────────────────────────┐ q_0: ┤0 ├ │ Initialize(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(params, int) else None return self.append(Initialize(params, num_qubits, normalize), qubits) QuantumCircuit.initialize = initialize
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2020, 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. """CircuitSampler Class""" import logging from functools import partial from time import time from typing import Any, Dict, List, Optional, Tuple, Union, cast import numpy as np from qiskit import QiskitError from qiskit.circuit import Parameter, ParameterExpression, QuantumCircuit from qiskit.opflow.converters.converter_base import ConverterBase from qiskit.opflow.exceptions import OpflowError from qiskit.opflow.list_ops.list_op import ListOp from qiskit.opflow.operator_base import OperatorBase from qiskit.opflow.state_fns.circuit_state_fn import CircuitStateFn from qiskit.opflow.state_fns.dict_state_fn import DictStateFn from qiskit.opflow.state_fns.state_fn import StateFn from qiskit.providers import Backend from qiskit.utils.backend_utils import is_aer_provider, is_statevector_backend from qiskit.utils.quantum_instance import QuantumInstance from qiskit.utils.deprecation import deprecate_func logger = logging.getLogger(__name__) class CircuitSampler(ConverterBase): """ Deprecated: The CircuitSampler traverses an Operator and converts any CircuitStateFns into approximations of the state function by a DictStateFn or VectorStateFn using a quantum backend. Note that in order to approximate the value of the CircuitStateFn, it must 1) send state function through a depolarizing channel, which will destroy all phase information and 2) replace the sampled frequencies with **square roots** of the frequency, rather than the raw probability of sampling (which would be the equivalent of sampling the **square** of the state function, per the Born rule. The CircuitSampler aggressively caches transpiled circuits to handle re-parameterization of the same circuit efficiently. If you are converting multiple different Operators, you are better off using a different CircuitSampler for each Operator to avoid cache thrashing. """ @deprecate_func( since="0.24.0", additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__( self, backend: Union[Backend, QuantumInstance], statevector: Optional[bool] = None, param_qobj: bool = False, attach_results: bool = False, caching: str = "last", ) -> None: """ Args: backend: The quantum backend or QuantumInstance to use to sample the circuits. statevector: If backend is a statevector backend, whether to replace the CircuitStateFns with DictStateFns (from the counts) or VectorStateFns (from the statevector). ``None`` will set this argument automatically based on the backend. attach_results: Whether to attach the data from the backend ``Results`` object for a given ``CircuitStateFn``` to an ``execution_results`` field added the converted ``DictStateFn`` or ``VectorStateFn``. param_qobj: Whether to use Aer's parameterized Qobj capability to avoid re-assembling the circuits. caching: The caching strategy. Can be `'last'` (default) to store the last operator that was converted, set to `'all'` to cache all processed operators. Raises: ValueError: Set statevector or param_qobj True when not supported by backend. """ super().__init__() self._quantum_instance = ( backend if isinstance(backend, QuantumInstance) else QuantumInstance(backend=backend) ) self._statevector = ( statevector if statevector is not None else self.quantum_instance.is_statevector ) self._param_qobj = param_qobj self._attach_results = attach_results self._check_quantum_instance_and_modes_consistent() # Object state variables self._caching = caching self._cached_ops: Dict[int, OperatorCache] = {} self._last_op: Optional[OperatorBase] = None self._reduced_op_cache = None self._circuit_ops_cache: Dict[int, CircuitStateFn] = {} self._transpiled_circ_cache: Optional[List[Any]] = None self._transpiled_circ_templates: Optional[List[Any]] = None self._transpile_before_bind = True def _check_quantum_instance_and_modes_consistent(self) -> None: """Checks whether the statevector and param_qobj settings are compatible with the backend Raises: ValueError: statevector or param_qobj are True when not supported by backend. """ if self._statevector and not is_statevector_backend(self.quantum_instance.backend): raise ValueError( "Statevector mode for circuit sampling requires statevector " "backend, not {}.".format(self.quantum_instance.backend) ) if self._param_qobj and not is_aer_provider(self.quantum_instance.backend): raise ValueError( "Parameterized Qobj mode requires Aer " "backend, not {}.".format(self.quantum_instance.backend) ) @property def quantum_instance(self) -> QuantumInstance: """Returns the quantum instance. Returns: The QuantumInstance used by the CircuitSampler """ return self._quantum_instance @quantum_instance.setter def quantum_instance(self, quantum_instance: Union[QuantumInstance, Backend]) -> None: """Sets the QuantumInstance. Raises: ValueError: statevector or param_qobj are True when not supported by backend. """ if isinstance(quantum_instance, Backend): quantum_instance = QuantumInstance(quantum_instance) self._quantum_instance = quantum_instance self._check_quantum_instance_and_modes_consistent() def convert( self, operator: OperatorBase, params: Optional[Dict[Parameter, Union[float, List[float], List[List[float]]]]] = None, ) -> OperatorBase: r""" Converts the Operator to one in which the CircuitStateFns are replaced by DictStateFns or VectorStateFns. Extracts the CircuitStateFns out of the Operator, caches them, calls ``sample_circuits`` below to get their converted replacements, and replaces the CircuitStateFns in operator with the replacement StateFns. Args: operator: The Operator to convert params: A dictionary mapping parameters to either single binding values or lists of binding values. Returns: The converted Operator with CircuitStateFns replaced by DictStateFns or VectorStateFns. Raises: OpflowError: if extracted circuits are empty. """ # check if the operator should be cached op_id = operator.instance_id # op_id = id(operator) if op_id not in self._cached_ops.keys(): # delete cache if we only want to cache one operator if self._caching == "last": self.clear_cache() # convert to circuit and reduce operator_dicts_replaced = operator.to_circuit_op() self._reduced_op_cache = operator_dicts_replaced.reduce() # extract circuits self._circuit_ops_cache = {} self._extract_circuitstatefns(self._reduced_op_cache) if not self._circuit_ops_cache: raise OpflowError( "Circuits are empty. " "Check that the operator is an instance of CircuitStateFn or its ListOp." ) self._transpiled_circ_cache = None self._transpile_before_bind = True else: # load the cached circuits self._reduced_op_cache = self._cached_ops[op_id].reduced_op_cache self._circuit_ops_cache = self._cached_ops[op_id].circuit_ops_cache self._transpiled_circ_cache = self._cached_ops[op_id].transpiled_circ_cache self._transpile_before_bind = self._cached_ops[op_id].transpile_before_bind self._transpiled_circ_templates = self._cached_ops[op_id].transpiled_circ_templates return_as_list = False if params is not None and len(params.keys()) > 0: p_0 = list(params.values())[0] if isinstance(p_0, (list, np.ndarray)): num_parameterizations = len(p_0) param_bindings = [ {param: value_list[i] for param, value_list in params.items()} # type: ignore for i in range(num_parameterizations) ] return_as_list = True else: num_parameterizations = 1 param_bindings = [params] else: param_bindings = None num_parameterizations = 1 # Don't pass circuits if we have in the cache, the sampling function knows to use the cache circs = list(self._circuit_ops_cache.values()) if not self._transpiled_circ_cache else None p_b = cast(List[Dict[Parameter, float]], param_bindings) sampled_statefn_dicts = self.sample_circuits(circuit_sfns=circs, param_bindings=p_b) def replace_circuits_with_dicts(operator, param_index=0): if isinstance(operator, CircuitStateFn): return sampled_statefn_dicts[id(operator)][param_index] elif isinstance(operator, ListOp): return operator.traverse( partial(replace_circuits_with_dicts, param_index=param_index) ) else: return operator # store the operator we constructed, if it isn't stored already if op_id not in self._cached_ops.keys(): op_cache = OperatorCache() op_cache.reduced_op_cache = self._reduced_op_cache op_cache.circuit_ops_cache = self._circuit_ops_cache op_cache.transpiled_circ_cache = self._transpiled_circ_cache op_cache.transpile_before_bind = self._transpile_before_bind op_cache.transpiled_circ_templates = self._transpiled_circ_templates self._cached_ops[op_id] = op_cache if return_as_list: return ListOp( [ replace_circuits_with_dicts(self._reduced_op_cache, param_index=i) for i in range(num_parameterizations) ] ) else: return replace_circuits_with_dicts(self._reduced_op_cache, param_index=0) def clear_cache(self) -> None: """Clear the cache of sampled operator expressions.""" self._cached_ops = {} def _extract_circuitstatefns(self, operator: OperatorBase) -> None: r""" Recursively extract the ``CircuitStateFns`` contained in operator into the ``_circuit_ops_cache`` field. """ if isinstance(operator, CircuitStateFn): self._circuit_ops_cache[id(operator)] = operator elif isinstance(operator, ListOp): for op in operator.oplist: self._extract_circuitstatefns(op) def sample_circuits( self, circuit_sfns: Optional[List[CircuitStateFn]] = None, param_bindings: Optional[List[Dict[Parameter, float]]] = None, ) -> Dict[int, List[StateFn]]: r""" Samples the CircuitStateFns and returns a dict associating their ``id()`` values to their replacement DictStateFn or VectorStateFn. If param_bindings is provided, the CircuitStateFns are broken into their parameterizations, and a list of StateFns is returned in the dict for each circuit ``id()``. Note that param_bindings is provided here in a different format than in ``convert``, and lists of parameters within the dict is not supported, and only binding dicts which are valid to be passed into Terra can be included in this list. Args: circuit_sfns: The list of CircuitStateFns to sample. param_bindings: The parameterizations to bind to each CircuitStateFn. Returns: The dictionary mapping ids of the CircuitStateFns to their replacement StateFns. Raises: OpflowError: if extracted circuits are empty. """ if not circuit_sfns and not self._transpiled_circ_cache: raise OpflowError("CircuitStateFn is empty and there is no cache.") if circuit_sfns: self._transpiled_circ_templates = None if self._statevector or circuit_sfns[0].from_operator: circuits = [op_c.to_circuit(meas=False) for op_c in circuit_sfns] else: circuits = [op_c.to_circuit(meas=True) for op_c in circuit_sfns] try: self._transpiled_circ_cache = self.quantum_instance.transpile( circuits, pass_manager=self.quantum_instance.unbound_pass_manager ) except QiskitError: logger.debug( r"CircuitSampler failed to transpile circuits with unbound " r"parameters. Attempting to transpile only when circuits are bound " r"now, but this can hurt performance due to repeated transpilation." ) self._transpile_before_bind = False self._transpiled_circ_cache = circuits else: circuit_sfns = list(self._circuit_ops_cache.values()) if param_bindings is not None: if self._param_qobj: start_time = time() ready_circs = self._prepare_parameterized_run_config(param_bindings) end_time = time() logger.debug("Parameter conversion %.5f (ms)", (end_time - start_time) * 1000) else: start_time = time() ready_circs = [ circ.assign_parameters(_filter_params(circ, binding)) for circ in self._transpiled_circ_cache for binding in param_bindings ] end_time = time() logger.debug("Parameter binding %.5f (ms)", (end_time - start_time) * 1000) else: ready_circs = self._transpiled_circ_cache # run transpiler passes on bound circuits if self._transpile_before_bind and self.quantum_instance.bound_pass_manager is not None: ready_circs = self.quantum_instance.transpile( ready_circs, pass_manager=self.quantum_instance.bound_pass_manager ) results = self.quantum_instance.execute( ready_circs, had_transpiled=self._transpile_before_bind ) if param_bindings is not None and self._param_qobj: self._clean_parameterized_run_config() # Wipe parameterizations, if any # self.quantum_instance._run_config.parameterizations = None sampled_statefn_dicts = {} for i, op_c in enumerate(circuit_sfns): # Taking square root because we're replacing a statevector # representation of probabilities. reps = len(param_bindings) if param_bindings is not None else 1 c_statefns = [] for j in range(reps): circ_index = (i * reps) + j circ_results = results.data(circ_index) if "expval_measurement" in circ_results: avg = circ_results["expval_measurement"] # Will be replaced with just avg when eval is called later num_qubits = circuit_sfns[0].num_qubits result_sfn = DictStateFn( "0" * num_qubits, coeff=avg * op_c.coeff, is_measurement=op_c.is_measurement, from_operator=op_c.from_operator, ) elif self._statevector: result_sfn = StateFn( op_c.coeff * results.get_statevector(circ_index), is_measurement=op_c.is_measurement, ) else: shots = self.quantum_instance._run_config.shots result_sfn = DictStateFn( { b: (v / shots) ** 0.5 * op_c.coeff for (b, v) in results.get_counts(circ_index).items() }, is_measurement=op_c.is_measurement, from_operator=op_c.from_operator, ) if self._attach_results: result_sfn.execution_results = circ_results c_statefns.append(result_sfn) sampled_statefn_dicts[id(op_c)] = c_statefns return sampled_statefn_dicts def _build_aer_params( self, circuit: QuantumCircuit, building_param_tables: Dict[Tuple[int, int], List[float]], input_params: Dict[Parameter, float], ) -> None: def resolve_param(inst_param): if not isinstance(inst_param, ParameterExpression): return None param_mappings = {} for param in inst_param._parameter_symbols.keys(): if param not in input_params: raise ValueError(f"unexpected parameter: {param}") param_mappings[param] = input_params[param] return float(inst_param.bind(param_mappings)) gate_index = 0 for instruction in circuit.data: param_index = 0 for inst_param in instruction.operation.params: val = resolve_param(inst_param) if val is not None: param_key = (gate_index, param_index) if param_key in building_param_tables: building_param_tables[param_key].append(val) else: building_param_tables[param_key] = [val] param_index += 1 gate_index += 1 def _prepare_parameterized_run_config( self, param_bindings: List[Dict[Parameter, float]] ) -> List[Any]: self.quantum_instance._run_config.parameterizations = [] if self._transpiled_circ_templates is None or len(self._transpiled_circ_templates) != len( self._transpiled_circ_cache ): # temporally resolve parameters of self._transpiled_circ_cache # They will be overridden in Aer from the next iterations self._transpiled_circ_templates = [ circ.assign_parameters(_filter_params(circ, param_bindings[0])) for circ in self._transpiled_circ_cache ] for circ in self._transpiled_circ_cache: building_param_tables: Dict[Tuple[int, int], List[float]] = {} for param_binding in param_bindings: self._build_aer_params(circ, building_param_tables, param_binding) param_tables = [] for gate_and_param_indices in building_param_tables: gate_index = gate_and_param_indices[0] param_index = gate_and_param_indices[1] param_tables.append( [[gate_index, param_index], building_param_tables[(gate_index, param_index)]] ) self.quantum_instance._run_config.parameterizations.append(param_tables) return self._transpiled_circ_templates def _clean_parameterized_run_config(self) -> None: self.quantum_instance._run_config.parameterizations = [] def _filter_params(circuit, param_dict): """Remove all parameters from ``param_dict`` that are not in ``circuit``.""" return {param: value for param, value in param_dict.items() if param in circuit.parameters} class OperatorCache: """A struct to cache an operator along with the circuits in contains.""" reduced_op_cache = None # the reduced operator circuit_ops_cache: Optional[Dict[int, CircuitStateFn]] = None # the extracted circuits transpiled_circ_cache = None # the transpiled circuits transpile_before_bind = True # whether to transpile before binding parameters in the operator transpiled_circ_templates: Optional[List[Any]] = None # transpiled circuit templates for Aer
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2020, 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. """PauliBasisChange Class""" from functools import partial, reduce from typing import Callable, List, Optional, Tuple, Union, cast import numpy as np from qiskit import QuantumCircuit from qiskit.opflow.converters.converter_base import ConverterBase from qiskit.opflow.list_ops.composed_op import ComposedOp from qiskit.opflow.list_ops.list_op import ListOp from qiskit.opflow.list_ops.summed_op import SummedOp from qiskit.opflow.operator_base import OperatorBase from qiskit.opflow.operator_globals import H, I, S from qiskit.opflow.primitive_ops.pauli_op import PauliOp from qiskit.opflow.primitive_ops.pauli_sum_op import PauliSumOp from qiskit.opflow.primitive_ops.primitive_op import PrimitiveOp from qiskit.opflow.state_fns.operator_state_fn import OperatorStateFn from qiskit.opflow.state_fns.state_fn import StateFn from qiskit.quantum_info import Pauli from qiskit.utils.deprecation import deprecate_func class PauliBasisChange(ConverterBase): r""" Deprecated: Converter for changing Paulis into other bases. By default, the diagonal basis composed only of Pauli {Z, I}^n is used as the destination basis to which to convert. Meaning, if a Pauli containing X or Y terms is passed in, which cannot be sampled or evolved natively on some Quantum hardware, the Pauli can be replaced by a composition of a change of basis circuit and a Pauli composed of only Z and I terms (diagonal), which can be evolved or sampled natively on the Quantum hardware. The replacement function determines how the ``PauliOps`` should be replaced by their computed change-of-basis ``CircuitOps`` and destination ``PauliOps``. Several convenient out-of-the-box replacement functions have been added as static methods, such as ``measurement_replacement_fn``. This class uses the typical basis change method found in most Quantum Computing textbooks (such as on page 210 of Nielsen and Chuang's, "Quantum Computation and Quantum Information", ISBN: 978-1-107-00217-3), which involves diagonalizing the single-qubit Paulis with H and S† gates, mapping the eigenvectors of the diagonalized origin Pauli to the diagonalized destination Pauli using CNOTS, and then de-diagonalizing any single qubit Paulis to their non-diagonal destination values. Many other methods are possible, as well as variations on this method, such as the placement of the CNOT chains. """ @deprecate_func( since="0.24.0", additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__( self, destination_basis: Optional[Union[Pauli, PauliOp]] = None, traverse: bool = True, replacement_fn: Optional[Callable] = None, ) -> None: """ Args: destination_basis: The Pauli into the basis of which the operators will be converted. If None is specified, the destination basis will be the diagonal ({I, Z}^n) basis requiring only single qubit rotations. traverse: If true and the operator passed into convert contains sub-Operators, such as ListOp, traverse the Operator and apply the conversion to every applicable sub-operator within it. replacement_fn: A function specifying what to do with the basis-change ``CircuitOp`` and destination ``PauliOp`` when converting an Operator and replacing converted values. By default, this will be 1) For StateFns (or Measurements): replacing the StateFn with ComposedOp(StateFn(d), c) where c is the conversion circuit and d is the destination Pauli, so the overall beginning and ending operators are equivalent. 2) For non-StateFn Operators: replacing the origin p with c·d·c†, where c is the conversion circuit and d is the destination, so the overall beginning and ending operators are equivalent. """ super().__init__() if destination_basis is not None: self.destination = destination_basis # type: ignore else: self._destination = None # type: Optional[PauliOp] self._traverse = traverse self._replacement_fn = replacement_fn or PauliBasisChange.operator_replacement_fn @property def destination(self) -> Optional[PauliOp]: r""" The destination ``PauliOp``, or ``None`` if using the default destination, the diagonal basis. """ return self._destination @destination.setter def destination(self, dest: Union[Pauli, PauliOp]) -> None: r""" The destination ``PauliOp``, or ``None`` if using the default destination, the diagonal basis. """ if isinstance(dest, Pauli): dest = PauliOp(dest) if not isinstance(dest, PauliOp): raise TypeError( f"PauliBasisChange can only convert into Pauli bases, not {type(dest)}." ) self._destination = dest # TODO see whether we should make this performant by handling ListOps of Paulis later. # pylint: disable=too-many-return-statements def convert(self, operator: OperatorBase) -> OperatorBase: r""" Given a ``PauliOp``, or an Operator containing ``PauliOps`` if ``_traverse`` is True, converts each Pauli into the basis specified by self._destination and a basis-change-circuit, calls ``replacement_fn`` with these two Operators, and replaces the ``PauliOps`` with the output of ``replacement_fn``. For example, for the built-in ``operator_replacement_fn`` below, each PauliOp p will be replaced by the composition of the basis-change Clifford ``CircuitOp`` c with the destination PauliOp d and c†, such that p = c·d·c†, up to global phase. Args: operator: The Operator to convert. Returns: The converted Operator. """ if ( isinstance(operator, OperatorStateFn) and isinstance(operator.primitive, PauliSumOp) and operator.primitive.grouping_type == "TPB" ): primitive = operator.primitive.primitive.copy() origin_x = reduce(np.logical_or, primitive.paulis.x) origin_z = reduce(np.logical_or, primitive.paulis.z) origin_pauli = Pauli((origin_z, origin_x)) cob_instr_op, _ = self.get_cob_circuit(origin_pauli) primitive.paulis.z = np.logical_or(primitive.paulis.x, primitive.paulis.z) primitive.paulis.x = False # The following line is because the deprecated PauliTable did not have a phase # and did not track it, so phase=0 was always guaranteed. # But the new PauliList may change phase. primitive.paulis.phase = 0 dest_pauli_sum_op = PauliSumOp(primitive, coeff=operator.coeff, grouping_type="TPB") return self._replacement_fn(cob_instr_op, dest_pauli_sum_op) if ( isinstance(operator, OperatorStateFn) and isinstance(operator.primitive, SummedOp) and all( isinstance(op, PauliSumOp) and op.grouping_type == "TPB" for op in operator.primitive.oplist ) ): sf_list: List[OperatorBase] = [ StateFn(op, is_measurement=operator.is_measurement) for op in operator.primitive.oplist ] listop_of_statefns = SummedOp(oplist=sf_list, coeff=operator.coeff) return listop_of_statefns.traverse(self.convert) if isinstance(operator, OperatorStateFn) and isinstance(operator.primitive, PauliSumOp): operator = OperatorStateFn( operator.primitive.to_pauli_op(), coeff=operator.coeff, is_measurement=operator.is_measurement, ) if isinstance(operator, PauliSumOp): operator = operator.to_pauli_op() if isinstance(operator, (Pauli, PauliOp)): cob_instr_op, dest_pauli_op = self.get_cob_circuit(operator) return self._replacement_fn(cob_instr_op, dest_pauli_op) if isinstance(operator, StateFn) and "Pauli" in operator.primitive_strings(): # If the StateFn/Meas only contains a Pauli, use it directly. if isinstance(operator.primitive, PauliOp): cob_instr_op, dest_pauli_op = self.get_cob_circuit(operator.primitive) return self._replacement_fn(cob_instr_op, dest_pauli_op * operator.coeff) # TODO make a canonical "distribute" or graph swap as method in ListOp? elif operator.primitive.distributive: if operator.primitive.abelian: origin_pauli = self.get_tpb_pauli(operator.primitive) cob_instr_op, _ = self.get_cob_circuit(origin_pauli) diag_ops: List[OperatorBase] = [ self.get_diagonal_pauli_op(op) for op in operator.primitive.oplist ] dest_pauli_op = operator.primitive.__class__( diag_ops, coeff=operator.coeff, abelian=True ) return self._replacement_fn(cob_instr_op, dest_pauli_op) else: sf_list = [ StateFn(op, is_measurement=operator.is_measurement) for op in operator.primitive.oplist ] listop_of_statefns = operator.primitive.__class__( oplist=sf_list, coeff=operator.coeff ) return listop_of_statefns.traverse(self.convert) elif ( isinstance(operator, ListOp) and self._traverse and "Pauli" in operator.primitive_strings() ): # If ListOp is abelian we can find a single post-rotation circuit # for the whole set. For now, # assume operator can only be abelian if all elements are # Paulis (enforced in AbelianGrouper). if operator.abelian: origin_pauli = self.get_tpb_pauli(operator) cob_instr_op, _ = self.get_cob_circuit(origin_pauli) oplist = cast(List[PauliOp], operator.oplist) diag_ops = [self.get_diagonal_pauli_op(op) for op in oplist] dest_list_op = operator.__class__(diag_ops, coeff=operator.coeff, abelian=True) return self._replacement_fn(cob_instr_op, dest_list_op) else: return operator.traverse(self.convert) return operator @staticmethod def measurement_replacement_fn( cob_instr_op: PrimitiveOp, dest_pauli_op: Union[PauliOp, PauliSumOp, ListOp] ) -> OperatorBase: r""" A built-in convenience replacement function which produces measurements isomorphic to an ``OperatorStateFn`` measurement holding the origin ``PauliOp``. Args: cob_instr_op: The basis-change ``CircuitOp``. dest_pauli_op: The destination Pauli type operator. Returns: The ``~StateFn @ CircuitOp`` composition equivalent to a measurement by the original ``PauliOp``. """ return ComposedOp([StateFn(dest_pauli_op, is_measurement=True), cob_instr_op]) @staticmethod def statefn_replacement_fn( cob_instr_op: PrimitiveOp, dest_pauli_op: Union[PauliOp, PauliSumOp, ListOp] ) -> OperatorBase: r""" A built-in convenience replacement function which produces state functions isomorphic to an ``OperatorStateFn`` state function holding the origin ``PauliOp``. Args: cob_instr_op: The basis-change ``CircuitOp``. dest_pauli_op: The destination Pauli type operator. Returns: The ``~CircuitOp @ StateFn`` composition equivalent to a state function defined by the original ``PauliOp``. """ return ComposedOp([cob_instr_op.adjoint(), StateFn(dest_pauli_op)]) @staticmethod def operator_replacement_fn( cob_instr_op: PrimitiveOp, dest_pauli_op: Union[PauliOp, PauliSumOp, ListOp] ) -> OperatorBase: r""" A built-in convenience replacement function which produces Operators isomorphic to the origin ``PauliOp``. Args: cob_instr_op: The basis-change ``CircuitOp``. dest_pauli_op: The destination ``PauliOp``. Returns: The ``~CircuitOp @ PauliOp @ CircuitOp`` composition isomorphic to the original ``PauliOp``. """ return ComposedOp([cob_instr_op.adjoint(), dest_pauli_op, cob_instr_op]) def get_tpb_pauli(self, list_op: ListOp) -> Pauli: r""" Gets the Pauli (not ``PauliOp``!) whose diagonalizing single-qubit rotations is a superset of the diagonalizing single-qubit rotations for each of the Paulis in ``list_op``. TPB stands for `Tensor Product Basis`. Args: list_op: the :class:`ListOp` whose TPB Pauli to return. Returns: The TBP Pauli. """ oplist = cast(List[PauliOp], list_op.oplist) origin_z = reduce(np.logical_or, [p_op.primitive.z for p_op in oplist]) origin_x = reduce(np.logical_or, [p_op.primitive.x for p_op in oplist]) return Pauli((origin_z, origin_x)) def get_diagonal_pauli_op(self, pauli_op: PauliOp) -> PauliOp: """Get the diagonal ``PualiOp`` to which ``pauli_op`` could be rotated with only single-qubit operations. Args: pauli_op: The ``PauliOp`` whose diagonal to compute. Returns: The diagonal ``PauliOp``. """ return PauliOp( Pauli( ( np.logical_or(pauli_op.primitive.z, pauli_op.primitive.x), [False] * pauli_op.num_qubits, ) ), coeff=pauli_op.coeff, ) def get_diagonalizing_clifford(self, pauli: Union[Pauli, PauliOp]) -> OperatorBase: r""" Construct a ``CircuitOp`` with only single-qubit gates which takes the eigenvectors of ``pauli`` to eigenvectors composed only of \|0⟩ and \|1⟩ tensor products. Equivalently, finds the basis-change circuit to take ``pauli`` to a diagonal ``PauliOp`` composed only of Z and I tensor products. Note, underlying Pauli bits are in Qiskit endianness, so we need to reverse before we begin composing with Operator flow. Args: pauli: the ``Pauli`` or ``PauliOp`` to whose diagonalizing circuit to compute. Returns: The diagonalizing ``CircuitOp``. """ if isinstance(pauli, PauliOp): pauli = pauli.primitive tensorall = cast( Callable[[List[PrimitiveOp]], PrimitiveOp], partial(reduce, lambda x, y: x.tensor(y)) ) y_to_x_origin = tensorall( [S if has_y else I for has_y in reversed(np.logical_and(pauli.x, pauli.z))] ).adjoint() x_to_z_origin = tensorall( # pylint: disable=assignment-from-no-return [H if has_x else I for has_x in reversed(pauli.x)] ) return x_to_z_origin.compose(y_to_x_origin) def pad_paulis_to_equal_length( self, pauli_op1: PauliOp, pauli_op2: PauliOp ) -> Tuple[PauliOp, PauliOp]: r""" If ``pauli_op1`` and ``pauli_op2`` do not act over the same number of qubits, pad identities to the end of the shorter of the two so they are of equal length. Padding is applied to the end of the Paulis. Note that the Terra represents Paulis in big-endian order, so this will appear as padding to the beginning of the Pauli x and z bit arrays. Args: pauli_op1: A pauli_op to possibly pad. pauli_op2: A pauli_op to possibly pad. Returns: A tuple containing the padded PauliOps. """ num_qubits = max(pauli_op1.num_qubits, pauli_op2.num_qubits) pauli_1, pauli_2 = pauli_op1.primitive, pauli_op2.primitive # Padding to the end of the Pauli, but remember that Paulis are in reverse endianness. if not len(pauli_1.z) == num_qubits: missing_qubits = num_qubits - len(pauli_1.z) pauli_1 = Pauli( ( ([False] * missing_qubits) + pauli_1.z.tolist(), ([False] * missing_qubits) + pauli_1.x.tolist(), ) ) if not len(pauli_2.z) == num_qubits: missing_qubits = num_qubits - len(pauli_2.z) pauli_2 = Pauli( ( ([False] * missing_qubits) + pauli_2.z.tolist(), ([False] * missing_qubits) + pauli_2.x.tolist(), ) ) return PauliOp(pauli_1, coeff=pauli_op1.coeff), PauliOp(pauli_2, coeff=pauli_op2.coeff) def construct_cnot_chain(self, diag_pauli_op1: PauliOp, diag_pauli_op2: PauliOp) -> PrimitiveOp: r""" Construct a ``CircuitOp`` (or ``PauliOp`` if equal to the identity) which takes the eigenvectors of ``diag_pauli_op1`` to the eigenvectors of ``diag_pauli_op2``, assuming both are diagonal (or performing this operation on their diagonalized Paulis implicitly if not). This works by the insight that the eigenvalue of a diagonal Pauli's eigenvector is equal to or -1 if the parity is 1 and 1 if the parity is 0, or 1 - (2 * parity). Therefore, using CNOTs, we can write the parity of diag_pauli_op1's significant bits onto some qubit, and then write out that parity onto diag_pauli_op2's significant bits. Args: diag_pauli_op1: The origin ``PauliOp``. diag_pauli_op2: The destination ``PauliOp``. Return: The ``PrimitiveOp`` performs the mapping. """ # TODO be smarter about connectivity and actual distance between pauli and destination # TODO be smarter in general pauli_1 = ( diag_pauli_op1.primitive if isinstance(diag_pauli_op1, PauliOp) else diag_pauli_op1 ) pauli_2 = ( diag_pauli_op2.primitive if isinstance(diag_pauli_op2, PauliOp) else diag_pauli_op2 ) origin_sig_bits = np.logical_or(pauli_1.z, pauli_1.x) destination_sig_bits = np.logical_or(pauli_2.z, pauli_2.x) num_qubits = max(len(pauli_1.z), len(pauli_2.z)) sig_equal_sig_bits = np.logical_and(origin_sig_bits, destination_sig_bits) non_equal_sig_bits = np.logical_not(origin_sig_bits == destination_sig_bits) # Equivalent to np.logical_xor(origin_sig_bits, destination_sig_bits) if not any(non_equal_sig_bits): return I ^ num_qubits # I am deeply sorry for this code, but I don't know another way to do it. sig_in_origin_only_indices = np.extract( np.logical_and(non_equal_sig_bits, origin_sig_bits), np.arange(num_qubits) ) sig_in_dest_only_indices = np.extract( np.logical_and(non_equal_sig_bits, destination_sig_bits), np.arange(num_qubits) ) if len(sig_in_origin_only_indices) > 0 and len(sig_in_dest_only_indices) > 0: origin_anchor_bit = min(sig_in_origin_only_indices) dest_anchor_bit = min(sig_in_dest_only_indices) else: # Set to lowest equal bit origin_anchor_bit = min(np.extract(sig_equal_sig_bits, np.arange(num_qubits))) dest_anchor_bit = origin_anchor_bit cnots = QuantumCircuit(num_qubits) # Step 3) Take the indices of bits which are sig_bits in # pauli but but not in dest, and cnot them to the pauli anchor. for i in sig_in_origin_only_indices: if not i == origin_anchor_bit: cnots.cx(i, origin_anchor_bit) # Step 4) if not origin_anchor_bit == dest_anchor_bit: cnots.swap(origin_anchor_bit, dest_anchor_bit) # Need to do this or a Terra bug sometimes flips cnots. No time to investigate. cnots.i(0) # Step 6) for i in sig_in_dest_only_indices: if not i == dest_anchor_bit: cnots.cx(i, dest_anchor_bit) return PrimitiveOp(cnots) def get_cob_circuit(self, origin: Union[Pauli, PauliOp]) -> Tuple[PrimitiveOp, PauliOp]: r""" Construct an Operator which maps the +1 and -1 eigenvectors of the origin Pauli to the +1 and -1 eigenvectors of the destination Pauli. It does so by 1) converting any \|i+⟩ or \|i+⟩ eigenvector bits in the origin to \|+⟩ and \|-⟩ with S†s, then 2) converting any \|+⟩ or \|+⟩ eigenvector bits in the converted origin to \|0⟩ and \|1⟩ with Hs, then 3) writing the parity of the significant (Z-measured, rather than I) bits in the origin to a single "origin anchor bit," using cnots, which will hold the parity of these bits, 4) swapping the parity of the pauli anchor bit into a destination anchor bit using a swap gate (only if they are different, if there are any bits which are significant in both origin and dest, we set both anchors to one of these bits to avoid a swap). 5) writing the parity of the destination anchor bit into the other significant bits of the destination, 6) converting the \|0⟩ and \|1⟩ significant eigenvector bits to \|+⟩ and \|-⟩ eigenvector bits in the destination where the destination demands it (e.g. pauli.x == true for a bit), using Hs 8) converting the \|+⟩ and \|-⟩ significant eigenvector bits to \|i+⟩ and \|i-⟩ eigenvector bits in the destination where the destination demands it (e.g. pauli.x == true and pauli.z == true for a bit), using Ss Args: origin: The ``Pauli`` or ``PauliOp`` to map. Returns: A tuple of a ``PrimitiveOp`` which equals the basis change mapping and a ``PauliOp`` which equals the destination basis. Raises: TypeError: Attempting to convert from non-Pauli origin. ValueError: Attempting to change a non-identity Pauli to an identity Pauli, or vice versa. """ # If pauli is an PrimitiveOp, extract the Pauli if isinstance(origin, Pauli): origin = PauliOp(origin) if not isinstance(origin, PauliOp): raise TypeError( f"PauliBasisChange can only convert Pauli-based OpPrimitives, not {type(origin)}" ) # If no destination specified, assume nearest Pauli in {Z,I}^n basis, # the standard basis change for expectations. destination = self.destination or self.get_diagonal_pauli_op(origin) # Pad origin or destination if either are not as long as the other origin, destination = self.pad_paulis_to_equal_length(origin, destination) origin_sig_bits = np.logical_or(origin.primitive.x, origin.primitive.z) destination_sig_bits = np.logical_or(destination.primitive.x, destination.primitive.z) if not any(origin_sig_bits) or not any(destination_sig_bits): if not (any(origin_sig_bits) or any(destination_sig_bits)): # Both all Identity, just return Identities return I ^ origin.num_qubits, destination else: # One is Identity, one is not raise ValueError("Cannot change to or from a fully Identity Pauli.") # Steps 1 and 2 cob_instruction = self.get_diagonalizing_clifford(origin) # Construct CNOT chain, assuming full connectivity... - Steps 3)-5) cob_instruction = self.construct_cnot_chain(origin, destination).compose(cob_instruction) # Step 6 and 7 dest_diagonlizing_clifford = self.get_diagonalizing_clifford(destination).adjoint() cob_instruction = dest_diagonlizing_clifford.compose(cob_instruction) return cast(PrimitiveOp, cob_instruction), destination
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2020, 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. """ExpectationFactory Class""" import logging from typing import Optional, Union from qiskit import BasicAer from qiskit.opflow.expectations.aer_pauli_expectation import AerPauliExpectation from qiskit.opflow.expectations.expectation_base import ExpectationBase from qiskit.opflow.expectations.matrix_expectation import MatrixExpectation from qiskit.opflow.expectations.pauli_expectation import PauliExpectation from qiskit.opflow.operator_base import OperatorBase from qiskit.providers import Backend from qiskit.utils.backend_utils import is_aer_qasm, is_statevector_backend from qiskit.utils import QuantumInstance, optionals from qiskit.utils.deprecation import deprecate_func logger = logging.getLogger(__name__) class ExpectationFactory: """Deprecated: factory class for convenient automatic selection of an Expectation based on the Operator to be converted and backend used to sample the expectation value. """ @staticmethod @deprecate_func( since="0.24.0", additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def build( operator: OperatorBase, backend: Optional[Union[Backend, QuantumInstance]] = None, include_custom: bool = True, ) -> ExpectationBase: """ A factory method for convenient automatic selection of an Expectation based on the Operator to be converted and backend used to sample the expectation value. Args: operator: The Operator whose expectation value will be taken. backend: The backend which will be used to sample the expectation value. include_custom: Whether the factory will include the (Aer) specific custom expectations if their behavior against the backend might not be as expected. For instance when using Aer qasm_simulator with paulis the Aer snapshot can be used but the outcome lacks shot noise and hence does not intuitively behave overall as people might expect when choosing a qasm_simulator. It is however fast as long as the more state vector like behavior is acceptable. Returns: The expectation algorithm which best fits the Operator and backend. Raises: ValueError: If operator is not of a composition for which we know the best Expectation method. """ backend_to_check = backend.backend if isinstance(backend, QuantumInstance) else backend # pylint: disable=cyclic-import primitives = operator.primitive_strings() if primitives in ({"Pauli"}, {"SparsePauliOp"}): if backend_to_check is None: # If user has Aer but didn't specify a backend, use the Aer fast expectation if optionals.HAS_AER: from qiskit_aer import AerSimulator backend_to_check = AerSimulator() # If user doesn't have Aer, use statevector_simulator # for < 16 qubits, and qasm with warning for more. else: if operator.num_qubits <= 16: backend_to_check = BasicAer.get_backend("statevector_simulator") else: logger.warning( "%d qubits is a very large expectation value. " "Consider installing Aer to use " "Aer's fast expectation, which will perform better here. We'll use " "the BasicAer qasm backend for this expectation to avoid having to " "construct the %dx%d operator matrix.", operator.num_qubits, 2**operator.num_qubits, 2**operator.num_qubits, ) backend_to_check = BasicAer.get_backend("qasm_simulator") # If the user specified Aer qasm backend and is using a # Pauli operator, use the Aer fast expectation if we are including such # custom behaviors. if is_aer_qasm(backend_to_check) and include_custom: return AerPauliExpectation() # If the user specified a statevector backend (either Aer or BasicAer), # use a converter to produce a # Matrix operator and compute using matmul elif is_statevector_backend(backend_to_check): if operator.num_qubits >= 16: logger.warning( "Note: Using a statevector_simulator with %d qubits can be very expensive. " "Consider using the Aer qasm_simulator instead to take advantage of Aer's " "built-in fast Pauli Expectation", operator.num_qubits, ) return MatrixExpectation() # All other backends, including IBMQ, BasicAer QASM, go here. else: return PauliExpectation() elif primitives == {"Matrix"}: return MatrixExpectation() else: raise ValueError("Expectations of Mixed Operators not yet supported.")
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2020, 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. """CircuitGradient Class""" from abc import abstractmethod from typing import List, Union, Optional, Tuple, Set from qiskit import QuantumCircuit, QiskitError, transpile from qiskit.circuit import ParameterExpression, ParameterVector from qiskit.utils.deprecation import deprecate_func from ...converters.converter_base import ConverterBase from ...operator_base import OperatorBase class CircuitGradient(ConverterBase): r"""Deprecated: Circuit to gradient operator converter. Converter for changing parameterized circuits into operators whose evaluation yields the gradient with respect to the circuit parameters. This is distinct from DerivativeBase converters which take gradients of composite operators and handle things like differentiating combo_fn's and enforcing product rules when operator coefficients are parameterized. CircuitGradient - uses quantum techniques to get derivatives of circuits DerivativeBase - uses classical techniques to differentiate operator flow data structures """ @deprecate_func( since="0.24.0", additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__(self) -> None: super().__init__() # pylint: disable=arguments-differ @abstractmethod def convert( self, operator: OperatorBase, params: Optional[ Union[ ParameterExpression, ParameterVector, List[ParameterExpression], Tuple[ParameterExpression, ParameterExpression], List[Tuple[ParameterExpression, ParameterExpression]], ] ] = None, ) -> OperatorBase: r""" Args: operator: The operator we are taking the gradient of params: The parameters we are taking the gradient wrt: ω If a ParameterExpression, ParameterVector or List[ParameterExpression] is given, then the 1st order derivative of the operator is calculated. If a Tuple[ParameterExpression, ParameterExpression] or List[Tuple[ParameterExpression, ParameterExpression]] is given, then the 2nd order derivative of the operator is calculated. Returns: An operator whose evaluation yields the Gradient. Raises: ValueError: If ``params`` contains a parameter not present in ``operator``. """ raise NotImplementedError @staticmethod def _transpile_to_supported_operations( circuit: QuantumCircuit, supported_gates: Set[str] ) -> QuantumCircuit: """Transpile the given circuit into a gate set for which the gradients may be computed. Args: circuit: Quantum circuit to be transpiled into supported operations. supported_gates: Set of quantum operations supported by a gradient method intended to be used on the quantum circuit. Returns: Quantum circuit which is transpiled into supported operations. Raises: QiskitError: when circuit transpiling fails. """ unique_ops = set(circuit.count_ops()) if not unique_ops.issubset(supported_gates): try: circuit = transpile( circuit, basis_gates=list(supported_gates), optimization_level=0 ) except Exception as exc: raise QiskitError( f"Could not transpile the circuit provided {circuit} into supported gates " f"{supported_gates}." ) from exc return circuit
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2020, 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. """The module to compute the state gradient with the parameter shift rule.""" from collections.abc import Iterable from copy import deepcopy from functools import partial from typing import List, Union, Tuple, Dict import scipy import numpy as np from qiskit import QuantumCircuit from qiskit.circuit import Parameter, ParameterExpression, ParameterVector from qiskit.utils.deprecation import deprecate_func from .circuit_gradient import CircuitGradient from ...operator_base import OperatorBase from ...state_fns.state_fn import StateFn from ...operator_globals import Zero, One from ...state_fns.circuit_state_fn import CircuitStateFn from ...primitive_ops.circuit_op import CircuitOp from ...list_ops.summed_op import SummedOp from ...list_ops.list_op import ListOp from ...list_ops.composed_op import ComposedOp from ...state_fns.dict_state_fn import DictStateFn from ...state_fns.vector_state_fn import VectorStateFn from ...state_fns.sparse_vector_state_fn import SparseVectorStateFn from ...exceptions import OpflowError from ..derivative_base import _coeff_derivative class ParamShift(CircuitGradient): """Deprecated: Compute the gradient d⟨ψ(ω)|O(θ)|ψ(ω)〉/ dω respectively the gradients of the sampling probabilities of the basis states of a state |ψ(ω)〉w.r.t. ω with the parameter shift method. """ SUPPORTED_GATES = {"x", "y", "z", "h", "rx", "ry", "rz", "p", "u", "cx", "cy", "cz"} @deprecate_func( since="0.24.0", additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__(self, analytic: bool = True, epsilon: float = 1e-6): r""" Args: analytic: If True use the parameter shift rule to compute analytic gradients, else use a finite difference approach epsilon: The offset size to use when computing finite difference gradients. Ignored if analytic == True Raises: ValueError: If method != ``fin_diff`` and ``epsilon`` is not None. """ super().__init__() self._analytic = analytic self._epsilon = epsilon @property def analytic(self) -> bool: """Returns ``analytic`` flag. Returns: ``analytic`` flag. """ return self._analytic @property def epsilon(self) -> float: """Returns ``epsilon``. Returns: ``epsilon``. """ return self._epsilon # pylint: disable=signature-differs def convert( self, operator: OperatorBase, params: Union[ ParameterExpression, ParameterVector, List[ParameterExpression], Tuple[ParameterExpression, ParameterExpression], List[Tuple[ParameterExpression, ParameterExpression]], ], ) -> OperatorBase: """ Args: operator: The operator corresponding to our quantum state we are taking the gradient of: |ψ(ω)〉 params: The parameters we are taking the gradient wrt: ω If a ParameterExpression, ParameterVector or List[ParameterExpression] is given, then the 1st order derivative of the operator is calculated. If a Tuple[ParameterExpression, ParameterExpression] or List[Tuple[ParameterExpression, ParameterExpression]] is given, then the 2nd order derivative of the operator is calculated. Returns: An operator corresponding to the gradient resp. Hessian. The order is in accordance with the order of the given parameters. Raises: OpflowError: If the parameters are given in an invalid format. """ if isinstance(params, (ParameterExpression, ParameterVector)): return self._parameter_shift(operator, params) elif isinstance(params, tuple): return self._parameter_shift(self._parameter_shift(operator, params[0]), params[1]) elif isinstance(params, Iterable): if all(isinstance(param, ParameterExpression) for param in params): return self._parameter_shift(operator, params) elif all(isinstance(param, tuple) for param in params): return ListOp( [ self._parameter_shift(self._parameter_shift(operator, pair[0]), pair[1]) for pair in params ] ) else: raise OpflowError( "The linear combination gradient does only support " "the computation " "of 1st gradients and 2nd order gradients." ) else: raise OpflowError( "The linear combination gradient does only support the computation " "of 1st gradients and 2nd order gradients." ) # pylint: disable=too-many-return-statements def _parameter_shift( self, operator: OperatorBase, params: Union[ParameterExpression, ParameterVector, List] ) -> OperatorBase: r""" Args: operator: The operator containing circuits we are taking the derivative of. params: The parameters (ω) we are taking the derivative with respect to. If a ParameterVector is provided, each parameter will be shifted. Returns: param_shifted_op: An operator object which evaluates to the respective gradients. Raises: ValueError: If the given parameters do not occur in the provided operator TypeError: If the operator has more than one circuit representing the quantum state """ if isinstance(params, (ParameterVector, list)): param_grads = [self._parameter_shift(operator, param) for param in params] absent_params = [ params[i] for i, grad_ops in enumerate(param_grads) if grad_ops is None ] if len(absent_params) > 0: raise ValueError( "The following parameters do not appear in the provided operator: ", absent_params, ) return ListOp(absent_params) # By this point, it's only one parameter param = params if isinstance(operator, ListOp) and not isinstance(operator, ComposedOp): return_op = operator.traverse(partial(self._parameter_shift, params=param)) # Remove any branch of the tree where the relevant parameter does not occur trimmed_oplist = [op for op in return_op.oplist if op is not None] # If all branches are None, remove the parent too if len(trimmed_oplist) == 0: return None # Rebuild the operator with the trimmed down oplist properties = {"coeff": return_op._coeff, "abelian": return_op._abelian} if return_op.__class__ == ListOp: properties["combo_fn"] = return_op.combo_fn return return_op.__class__(oplist=trimmed_oplist, **properties) else: circs = self.get_unique_circuits(operator) if len(circs) > 1: raise TypeError( "Please define an operator with a single circuit representing " "the quantum state." ) if len(circs) == 0: return operator circ = circs[0] if self.analytic: # Unroll the circuit into a gate set for which the gradient may be computed # using pi/2 shifts. circ = ParamShift._transpile_to_supported_operations(circ, self.SUPPORTED_GATES) operator = ParamShift._replace_operator_circuit(operator, circ) if param not in circ._parameter_table: return ~Zero @ One shifted_ops = [] summed_shifted_op = None iref_to_data_index = {id(inst.operation): idx for idx, inst in enumerate(circ.data)} for param_reference in circ._parameter_table[param]: original_gate, param_index = param_reference m = iref_to_data_index[id(original_gate)] pshift_op = deepcopy(operator) mshift_op = deepcopy(operator) # We need the circuit objects of the newly instantiated operators pshift_circ = self.get_unique_circuits(pshift_op)[0] mshift_circ = self.get_unique_circuits(mshift_op)[0] pshift_gate = pshift_circ.data[m].operation mshift_gate = mshift_circ.data[m].operation p_param = pshift_gate.params[param_index] m_param = mshift_gate.params[param_index] # For analytic gradients the circuit parameters are shifted once by +pi/2 and # once by -pi/2. if self.analytic: shift_constant = 0.5 pshift_gate.params[param_index] = p_param + (np.pi / (4 * shift_constant)) mshift_gate.params[param_index] = m_param - (np.pi / (4 * shift_constant)) # For finite difference gradients the circuit parameters are shifted once by # +epsilon and once by -epsilon. else: shift_constant = 1.0 / (2 * self._epsilon) pshift_gate.params[param_index] = p_param + self._epsilon mshift_gate.params[param_index] = m_param - self._epsilon # The results of the shifted operators are now evaluated according the parameter # shift / finite difference formula. if isinstance(operator, ComposedOp): shifted_op = shift_constant * (pshift_op - mshift_op) # If the operator represents a quantum state then we apply a special combo # function to evaluate probability gradients. elif isinstance(operator, StateFn): shifted_op = ListOp( [pshift_op, mshift_op], combo_fn=partial(self._prob_combo_fn, shift_constant=shift_constant), ) else: raise TypeError( "Probability gradients are not supported for the given operator type" ) if isinstance(p_param, ParameterExpression) and not isinstance(p_param, Parameter): expr_grad = _coeff_derivative(p_param, param) shifted_op *= expr_grad if not summed_shifted_op: summed_shifted_op = shifted_op else: summed_shifted_op += shifted_op shifted_ops.append(summed_shifted_op) if not SummedOp(shifted_ops).reduce(): return ~StateFn(Zero) @ One else: return SummedOp(shifted_ops).reduce() @staticmethod def _prob_combo_fn( x: Union[ DictStateFn, VectorStateFn, SparseVectorStateFn, List[Union[DictStateFn, VectorStateFn, SparseVectorStateFn]], ], shift_constant: float, ) -> Union[Dict, np.ndarray]: """Implement the combo_fn used to evaluate probability gradients Args: x: Output of an operator evaluation shift_constant: Shifting constant factor needed for proper rescaling Returns: Array representing the probability gradients w.r.t. the given operator and parameters Raises: TypeError: if ``x`` is not DictStateFn, VectorStateFn or their list. """ # Note: In the probability gradient case, the amplitudes still need to be converted # into sampling probabilities. def get_primitives(item): if isinstance(item, (DictStateFn, SparseVectorStateFn)): item = item.primitive if isinstance(item, VectorStateFn): item = item.primitive.data return item is_statefn = False if isinstance(x, list): # Check if all items in x are a StateFn items if all(isinstance(item, StateFn) for item in x): is_statefn = True items = [get_primitives(item) for item in x] else: # Check if x is a StateFn item if isinstance(x, StateFn): is_statefn = True items = [get_primitives(x)] if isinstance(items[0], dict): prob_dict: Dict[str, float] = {} for i, item in enumerate(items): for key, prob_counts in item.items(): prob_dict[key] = ( prob_dict.get(key, 0) + shift_constant * ((-1) ** i) * prob_counts ) return prob_dict elif isinstance(items[0], scipy.sparse.spmatrix): # If x was given as StateFn the state amplitudes need to be multiplied in order to # evaluate the sampling probabilities which are then subtracted according to the # parameter shift rule. if is_statefn: return shift_constant * np.subtract( items[0].multiply(np.conj(items[0])), items[1].multiply(np.conj(items[1])) ) # If x was not given as a StateFn the state amplitudes were already converted into # sampling probabilities which are then only subtracted according to the # parameter shift rule. else: return shift_constant * np.subtract(items[0], items[1]) elif isinstance(items[0], Iterable): # If x was given as StateFn the state amplitudes need to be multiplied in order to # evaluate the sampling probabilities which are then subtracted according to the # parameter shift rule. if is_statefn: return shift_constant * np.subtract( np.multiply(items[0], np.conj(items[0])), np.multiply(items[1], np.conj(items[1])), ) # If x was not given as a StateFn the state amplitudes were already converted into # sampling probabilities which are then only subtracted according to the # parameter shift rule. else: return shift_constant * np.subtract(items[0], items[1]) raise TypeError( "Probability gradients can only be evaluated from VectorStateFs or DictStateFns." ) @staticmethod def _replace_operator_circuit(operator: OperatorBase, circuit: QuantumCircuit) -> OperatorBase: """Replace a circuit element in an operator with a single element given as circuit Args: operator: Operator for which the circuit representing the quantum state shall be replaced circuit: Circuit which shall replace the circuit in the given operator Returns: Operator with replaced circuit quantum state function """ if isinstance(operator, CircuitStateFn): return CircuitStateFn(circuit, coeff=operator.coeff) elif isinstance(operator, CircuitOp): return CircuitOp(circuit, coeff=operator.coeff) elif isinstance(operator, (ComposedOp, ListOp)): return operator.traverse(partial(ParamShift._replace_operator_circuit, circuit=circuit)) else: return operator @classmethod def get_unique_circuits(cls, operator: OperatorBase) -> List[QuantumCircuit]: """Traverse the operator and return all unique circuits Args: operator: An operator that potentially includes QuantumCircuits Returns: A list of all unique quantum circuits that appear in the operator """ if isinstance(operator, CircuitStateFn): return [operator.primitive] def get_circuit(op): return op.primitive if isinstance(op, (CircuitStateFn, CircuitOp)) else None unrolled_op = cls.unroll_operator(operator) circuits = [] for ops in unrolled_op: if not isinstance(ops, list): ops = [ops] for op in ops: if isinstance(op, (CircuitStateFn, CircuitOp, QuantumCircuit)): c = get_circuit(op) if c and c not in circuits: circuits.append(c) return circuits @classmethod def unroll_operator(cls, operator: OperatorBase) -> Union[OperatorBase, List[OperatorBase]]: """Traverse the operator and return all OperatorBase objects flattened into a single list. This is used as a subroutine to extract all circuits within a large composite operator. Args: operator: An OperatorBase type object Returns: A single flattened list of all OperatorBase objects within the input operator """ if isinstance(operator, ListOp): return [cls.unroll_operator(op) for op in operator] if hasattr(operator, "primitive") and isinstance(operator.primitive, ListOp): return [operator.__class__(op) for op in operator.primitive] return operator
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2020, 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. """ComposedOp Class""" from functools import partial, reduce from typing import List, Optional, Union, cast, Dict from numbers import Number import numpy as np from qiskit import QuantumCircuit from qiskit.circuit import ParameterExpression from qiskit.opflow.exceptions import OpflowError from qiskit.opflow.list_ops.list_op import ListOp from qiskit.opflow.operator_base import OperatorBase from qiskit.quantum_info import Statevector from qiskit.utils.deprecation import deprecate_func class ComposedOp(ListOp): """Deprecated: A class for lazily representing compositions of Operators. Often Operators cannot be efficiently composed with one another, but may be manipulated further so that they can be composed later. This class holds logic to indicate that the Operators in ``oplist`` are meant to be composed, and therefore if they reach a point in which they can be, such as after conversion to QuantumCircuits or matrices, they can be reduced by composition.""" @deprecate_func( since="0.24.0", additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__( self, oplist: List[OperatorBase], coeff: Union[complex, ParameterExpression] = 1.0, abelian: bool = False, ) -> None: """ Args: oplist: The Operators being composed. coeff: A coefficient multiplying the operator abelian: Indicates whether the Operators in ``oplist`` are known to mutually commute. """ super().__init__(oplist, combo_fn=partial(reduce, np.dot), coeff=coeff, abelian=abelian) @property def num_qubits(self) -> int: return self.oplist[0].num_qubits @property def distributive(self) -> bool: return False @property def settings(self) -> Dict: """Return settings.""" return {"oplist": self._oplist, "coeff": self._coeff, "abelian": self._abelian} # TODO take advantage of the mixed product property, tensorpower each element in the composition # def tensorpower(self, other): # """ Tensor product with Self Multiple Times """ # raise NotImplementedError def to_matrix(self, massive: bool = False) -> np.ndarray: OperatorBase._check_massive("to_matrix", True, self.num_qubits, massive) mat = self.coeff * reduce( np.dot, [np.asarray(op.to_matrix(massive=massive)) for op in self.oplist] ) # Note: As ComposedOp has a combo function of inner product we can end up here not with # a matrix (array) but a scalar. In which case we make a single element array of it. if isinstance(mat, Number): mat = [mat] return np.asarray(mat, dtype=complex) def to_circuit(self) -> QuantumCircuit: """Returns the quantum circuit, representing the composed operator. Returns: The circuit representation of the composed operator. Raises: OpflowError: for operators where a single underlying circuit can not be obtained. """ # pylint: disable=cyclic-import from ..state_fns.circuit_state_fn import CircuitStateFn from ..primitive_ops.primitive_op import PrimitiveOp circuit_op = self.to_circuit_op() if isinstance(circuit_op, (PrimitiveOp, CircuitStateFn)): return circuit_op.to_circuit() raise OpflowError( "Conversion to_circuit supported only for operators, where a single " "underlying circuit can be produced." ) def adjoint(self) -> "ComposedOp": return ComposedOp([op.adjoint() for op in reversed(self.oplist)], coeff=self.coeff) def compose( self, other: OperatorBase, permutation: Optional[List[int]] = None, front: bool = False ) -> OperatorBase: new_self, other = self._expand_shorter_operator_and_permute(other, permutation) new_self = cast(ComposedOp, new_self) if front: return other.compose(new_self) # Try composing with last element in list if isinstance(other, ComposedOp): return ComposedOp(new_self.oplist + other.oplist, coeff=new_self.coeff * other.coeff) # Try composing with last element of oplist. We only try # this if that last element isn't itself an # ComposedOp, so we can tell whether composing the # two elements directly worked. If it doesn't, # continue to the final return statement below, appending other to the oplist. if not isinstance(new_self.oplist[-1], ComposedOp): comp_with_last = new_self.oplist[-1].compose(other) # Attempt successful if not isinstance(comp_with_last, ComposedOp): new_oplist = new_self.oplist[0:-1] + [comp_with_last] return ComposedOp(new_oplist, coeff=new_self.coeff) return ComposedOp(new_self.oplist + [other], coeff=new_self.coeff) def eval( self, front: Optional[Union[str, dict, np.ndarray, OperatorBase, Statevector]] = None ) -> Union[OperatorBase, complex]: if self._is_empty(): return 0.0 # pylint: disable=cyclic-import from ..state_fns.state_fn import StateFn def tree_recursive_eval(r, l_arg): if isinstance(r, list): return [tree_recursive_eval(r_op, l_arg) for r_op in r] else: return l_arg.eval(r) eval_list = self.oplist.copy() # Only one op needs to be multiplied, so just multiply the first. eval_list[0] = eval_list[0] * self.coeff # type: ignore if front and isinstance(front, OperatorBase): eval_list = eval_list + [front] elif front: eval_list = [StateFn(front, is_measurement=True)] + eval_list # type: ignore return reduce(tree_recursive_eval, reversed(eval_list)) # Try collapsing list or trees of compositions into a single <Measurement | Op | State>. def non_distributive_reduce(self) -> OperatorBase: """Reduce without attempting to expand all distributive compositions. Returns: The reduced Operator. """ reduced_ops = [op.reduce() for op in self.oplist] reduced_ops = reduce(lambda x, y: x.compose(y), reduced_ops) * self.coeff if isinstance(reduced_ops, ComposedOp) and len(reduced_ops.oplist) > 1: return reduced_ops else: return reduced_ops[0] def reduce(self) -> OperatorBase: reduced_ops = [op.reduce() for op in self.oplist] if len(reduced_ops) == 0: return self.__class__([], coeff=self.coeff, abelian=self.abelian) def distribute_compose(l_arg, r): if isinstance(l_arg, ListOp) and l_arg.distributive: # Either ListOp or SummedOp, returns correct type return l_arg.__class__( [distribute_compose(l_op * l_arg.coeff, r) for l_op in l_arg.oplist] ) if isinstance(r, ListOp) and r.distributive: return r.__class__([distribute_compose(l_arg, r_op * r.coeff) for r_op in r.oplist]) else: return l_arg.compose(r) reduced_ops = reduce(distribute_compose, reduced_ops) * self.coeff if isinstance(reduced_ops, ListOp) and len(reduced_ops.oplist) == 1: return reduced_ops.oplist[0] else: return cast(OperatorBase, reduced_ops)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2020, 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. """SummedOp Class""" from typing import List, Union, cast, Dict import numpy as np from qiskit import QuantumCircuit from qiskit.circuit import ParameterExpression from qiskit.opflow.exceptions import OpflowError from qiskit.opflow.list_ops.list_op import ListOp from qiskit.opflow.operator_base import OperatorBase from qiskit.utils.deprecation import deprecate_func class SummedOp(ListOp): """Deprecated: A class for lazily representing sums of Operators. Often Operators cannot be efficiently added to one another, but may be manipulated further so that they can be later. This class holds logic to indicate that the Operators in ``oplist`` are meant to be added together, and therefore if they reach a point in which they can be, such as after evaluation or conversion to matrices, they can be reduced by addition.""" @deprecate_func( since="0.24.0", additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__( self, oplist: List[OperatorBase], coeff: Union[complex, ParameterExpression] = 1.0, abelian: bool = False, ) -> None: """ Args: oplist: The Operators being summed. coeff: A coefficient multiplying the operator abelian: Indicates whether the Operators in ``oplist`` are known to mutually commute. """ super().__init__(oplist, combo_fn=lambda x: np.sum(x, axis=0), coeff=coeff, abelian=abelian) @property def num_qubits(self) -> int: return self.oplist[0].num_qubits @property def distributive(self) -> bool: return True @property def settings(self) -> Dict: """Return settings.""" return {"oplist": self._oplist, "coeff": self._coeff, "abelian": self._abelian} def add(self, other: OperatorBase) -> "SummedOp": """Return Operator addition of ``self`` and ``other``, overloaded by ``+``. Note: This appends ``other`` to ``self.oplist`` without checking ``other`` is already included or not. If you want to simplify them, please use :meth:`simplify`. Args: other: An ``OperatorBase`` with the same number of qubits as self, and in the same 'Operator', 'State function', or 'Measurement' category as self (i.e. the same type of underlying function). Returns: A ``SummedOp`` equivalent to the sum of self and other. """ self_new_ops = ( self.oplist if self.coeff == 1 else [op.mul(self.coeff) for op in self.oplist] ) if isinstance(other, SummedOp): other_new_ops = ( other.oplist if other.coeff == 1 else [op.mul(other.coeff) for op in other.oplist] ) else: other_new_ops = [other] return SummedOp(self_new_ops + other_new_ops) def collapse_summands(self) -> "SummedOp": """Return Operator by simplifying duplicate operators. E.g., ``SummedOp([2 * X ^ Y, X ^ Y]).collapse_summands() -> SummedOp([3 * X ^ Y])``. Returns: A simplified ``SummedOp`` equivalent to self. """ # pylint: disable=cyclic-import from ..primitive_ops.primitive_op import PrimitiveOp oplist = [] # type: List[OperatorBase] coeffs = [] # type: List[Union[int, float, complex, ParameterExpression]] for op in self.oplist: if isinstance(op, PrimitiveOp): new_op = PrimitiveOp(op.primitive) new_coeff = op.coeff * self.coeff if new_op in oplist: index = oplist.index(new_op) coeffs[index] += new_coeff else: oplist.append(new_op) coeffs.append(new_coeff) else: if op in oplist: index = oplist.index(op) coeffs[index] += self.coeff else: oplist.append(op) coeffs.append(self.coeff) return SummedOp([op * coeff for op, coeff in zip(oplist, coeffs)]) # TODO be smarter about the fact that any two ops in oplist could be evaluated for sum. def reduce(self) -> OperatorBase: """Try collapsing list or trees of sums. Tries to sum up duplicate operators and reduces the operators in the sum. Returns: A collapsed version of self, if possible. """ if len(self.oplist) == 0: return SummedOp([], coeff=self.coeff, abelian=self.abelian) # reduce constituents reduced_ops = sum(op.reduce() for op in self.oplist) * self.coeff # group duplicate operators if isinstance(reduced_ops, SummedOp): reduced_ops = reduced_ops.collapse_summands() # pylint: disable=cyclic-import from ..primitive_ops.pauli_sum_op import PauliSumOp if isinstance(reduced_ops, PauliSumOp): reduced_ops = reduced_ops.reduce() if isinstance(reduced_ops, SummedOp) and len(reduced_ops.oplist) == 1: return reduced_ops.oplist[0] else: return cast(OperatorBase, reduced_ops) def to_circuit(self) -> QuantumCircuit: """Returns the quantum circuit, representing the SummedOp. In the first step, the SummedOp is converted to MatrixOp. This is straightforward for most operators, but it is not supported for operators containing parameterized PrimitiveOps (in that case, OpflowError is raised). In the next step, the MatrixOp representation of SummedOp is converted to circuit. In most cases, if the summands themselves are unitary operators, the SummedOp itself is non-unitary and can not be converted to circuit. In that case, ExtensionError is raised in the underlying modules. Returns: The circuit representation of the summed operator. Raises: OpflowError: if SummedOp can not be converted to MatrixOp (e.g. SummedOp is composed of parameterized PrimitiveOps). """ # pylint: disable=cyclic-import from ..primitive_ops.matrix_op import MatrixOp matrix_op = self.to_matrix_op() if isinstance(matrix_op, MatrixOp): return matrix_op.to_circuit() raise OpflowError( "The SummedOp can not be converted to circuit, because to_matrix_op did " "not return a MatrixOp." ) def to_matrix_op(self, massive: bool = False) -> "SummedOp": """Returns an equivalent Operator composed of only NumPy-based primitives, such as ``MatrixOp`` and ``VectorStateFn``.""" accum = self.oplist[0].to_matrix_op(massive=massive) for i in range(1, len(self.oplist)): accum += self.oplist[i].to_matrix_op(massive=massive) return cast(SummedOp, accum * self.coeff) def to_pauli_op(self, massive: bool = False) -> "SummedOp": # pylint: disable=cyclic-import from ..state_fns.state_fn import StateFn pauli_sum = SummedOp( [ op.to_pauli_op(massive=massive) # type: ignore if not isinstance(op, StateFn) else op for op in self.oplist ], coeff=self.coeff, abelian=self.abelian, ).reduce() if isinstance(pauli_sum, SummedOp): return pauli_sum return pauli_sum.to_pauli_op() # type: ignore def equals(self, other: OperatorBase) -> bool: """Check if other is equal to self. Note: This is not a mathematical check for equality. If ``self`` and ``other`` implement the same operation but differ in the representation (e.g. different type of summands) ``equals`` will evaluate to ``False``. Args: other: The other operator to check for equality. Returns: True, if other and self are equal, otherwise False. Examples: >>> from qiskit.opflow import X, Z >>> 2 * X == X + X True >>> X + Z == Z + X True """ self_reduced, other_reduced = self.reduce(), other.reduce() if not isinstance(other_reduced, type(self_reduced)): return False # check if reduced op is still a SummedOp if not isinstance(self_reduced, SummedOp): return self_reduced == other_reduced self_reduced = cast(SummedOp, self_reduced) other_reduced = cast(SummedOp, other_reduced) if len(self_reduced.oplist) != len(other_reduced.oplist): return False # absorb coeffs into the operators if self_reduced.coeff != 1: self_reduced = SummedOp([op * self_reduced.coeff for op in self_reduced.oplist]) if other_reduced.coeff != 1: other_reduced = SummedOp([op * other_reduced.coeff for op in other_reduced.oplist]) # compare independent of order return all(any(i == j for j in other_reduced) for i in self_reduced)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2020, 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. """CircuitOp Class""" from typing import Dict, List, Optional, Set, Union, cast import numpy as np import qiskit from qiskit import QuantumCircuit from qiskit.circuit import Instruction, ParameterExpression from qiskit.circuit.library import IGate from qiskit.opflow.list_ops.tensored_op import TensoredOp from qiskit.opflow.operator_base import OperatorBase from qiskit.opflow.primitive_ops.primitive_op import PrimitiveOp from qiskit.quantum_info import Statevector from qiskit.utils.deprecation import deprecate_func class CircuitOp(PrimitiveOp): """Deprecated: Class for Operators backed by Terra's ``QuantumCircuit`` module.""" primitive: QuantumCircuit @deprecate_func( since="0.24.0", additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__( self, primitive: Union[Instruction, QuantumCircuit], coeff: Union[complex, ParameterExpression] = 1.0, ) -> None: """ Args: primitive: The QuantumCircuit which defines the behavior of the underlying function. coeff: A coefficient multiplying the primitive Raises: TypeError: Unsupported primitive, or primitive has ClassicalRegisters. """ if isinstance(primitive, Instruction): qc = QuantumCircuit(primitive.num_qubits) qc.append(primitive, qargs=range(primitive.num_qubits)) primitive = qc if not isinstance(primitive, QuantumCircuit): raise TypeError( "CircuitOp can only be instantiated with " "QuantumCircuit, not {}".format(type(primitive)) ) if len(primitive.clbits) != 0: raise TypeError("CircuitOp does not support QuantumCircuits with ClassicalRegisters.") super().__init__(primitive, coeff) self._coeff = coeff def primitive_strings(self) -> Set[str]: return {"QuantumCircuit"} @property def num_qubits(self) -> int: return self.primitive.num_qubits def add(self, other: OperatorBase) -> OperatorBase: if not self.num_qubits == other.num_qubits: raise ValueError( "Sum over operators with different numbers of qubits, {} and {}, is not well " "defined".format(self.num_qubits, other.num_qubits) ) if isinstance(other, CircuitOp) and self.primitive == other.primitive: return CircuitOp(self.primitive, coeff=self.coeff + other.coeff) # Covers all else. # pylint: disable=cyclic-import from ..list_ops.summed_op import SummedOp return SummedOp([self, other]) def adjoint(self) -> "CircuitOp": return CircuitOp(self.primitive.inverse(), coeff=self.coeff.conjugate()) def equals(self, other: OperatorBase) -> bool: if not isinstance(other, CircuitOp) or not self.coeff == other.coeff: return False return self.primitive == other.primitive def tensor(self, other: OperatorBase) -> Union["CircuitOp", TensoredOp]: # pylint: disable=cyclic-import from .pauli_op import PauliOp from .matrix_op import MatrixOp if isinstance(other, (PauliOp, CircuitOp, MatrixOp)): other = other.to_circuit_op() if isinstance(other, CircuitOp): new_qc = QuantumCircuit(self.num_qubits + other.num_qubits) # NOTE!!! REVERSING QISKIT ENDIANNESS HERE new_qc.append( other.to_instruction(), qargs=new_qc.qubits[0 : other.primitive.num_qubits] ) new_qc.append(self.to_instruction(), qargs=new_qc.qubits[other.primitive.num_qubits :]) new_qc = new_qc.decompose() return CircuitOp(new_qc, coeff=self.coeff * other.coeff) return TensoredOp([self, other]) def compose( self, other: OperatorBase, permutation: Optional[List[int]] = None, front: bool = False ) -> OperatorBase: new_self, other = self._expand_shorter_operator_and_permute(other, permutation) new_self = cast(CircuitOp, new_self) if front: return other.compose(new_self) # pylint: disable=cyclic-import from ..operator_globals import Zero from ..state_fns import CircuitStateFn from .pauli_op import PauliOp from .matrix_op import MatrixOp if other == Zero ^ new_self.num_qubits: return CircuitStateFn(new_self.primitive, coeff=new_self.coeff) if isinstance(other, (PauliOp, CircuitOp, MatrixOp)): other = other.to_circuit_op() if isinstance(other, (CircuitOp, CircuitStateFn)): new_qc = other.primitive.compose(new_self.primitive) if isinstance(other, CircuitStateFn): return CircuitStateFn( new_qc, is_measurement=other.is_measurement, coeff=new_self.coeff * other.coeff ) else: return CircuitOp(new_qc, coeff=new_self.coeff * other.coeff) return super(CircuitOp, new_self).compose(other) def to_matrix(self, massive: bool = False) -> np.ndarray: OperatorBase._check_massive("to_matrix", True, self.num_qubits, massive) unitary = qiskit.quantum_info.Operator(self.to_circuit()).data return unitary * self.coeff def __str__(self) -> str: qc = self.to_circuit() prim_str = str(qc.draw(output="text")) if self.coeff == 1.0: return prim_str else: return f"{self.coeff} * {prim_str}" def assign_parameters(self, param_dict: dict) -> OperatorBase: param_value = self.coeff qc = self.primitive if isinstance(self.coeff, ParameterExpression) or self.primitive.parameters: unrolled_dict = self._unroll_param_dict(param_dict) if isinstance(unrolled_dict, list): from ..list_ops.list_op import ListOp return ListOp([self.assign_parameters(param_dict) for param_dict in unrolled_dict]) if isinstance(self.coeff, ParameterExpression) and self.coeff.parameters <= set( unrolled_dict.keys() ): param_instersection = set(unrolled_dict.keys()) & self.coeff.parameters binds = {param: unrolled_dict[param] for param in param_instersection} param_value = float(self.coeff.bind(binds)) # & is set intersection, check if any parameters in unrolled are present in circuit # This is different from bind_parameters in Terra because they check for set equality if set(unrolled_dict.keys()) & self.primitive.parameters: # Only bind the params found in the circuit param_instersection = set(unrolled_dict.keys()) & self.primitive.parameters binds = {param: unrolled_dict[param] for param in param_instersection} qc = self.to_circuit().assign_parameters(binds) return self.__class__(qc, coeff=param_value) def eval( self, front: Optional[ Union[str, Dict[str, complex], np.ndarray, OperatorBase, Statevector] ] = None, ) -> Union[OperatorBase, complex]: from ..state_fns import CircuitStateFn from ..list_ops import ListOp from .pauli_op import PauliOp from .matrix_op import MatrixOp if isinstance(front, ListOp) and front.distributive: return front.combo_fn( [self.eval(front.coeff * front_elem) for front_elem in front.oplist] ) # Composable with circuit if isinstance(front, (PauliOp, CircuitOp, MatrixOp, CircuitStateFn)): return self.compose(front) return self.to_matrix_op().eval(front) def to_circuit(self) -> QuantumCircuit: return self.primitive def to_circuit_op(self) -> "CircuitOp": return self def to_instruction(self) -> Instruction: return self.primitive.to_instruction() # Warning - modifying immutable object!! def reduce(self) -> OperatorBase: if self.primitive.data is not None: # Need to do this from the end because we're deleting items! for i in reversed(range(len(self.primitive.data))): gate = self.primitive.data[i].operation # Check if Identity or empty instruction (need to check that type is exactly # Instruction because some gates have lazy gate.definition population) # pylint: disable=unidiomatic-typecheck if isinstance(gate, IGate) or ( type(gate) == Instruction and gate.definition.data == [] ): del self.primitive.data[i] return self def _expand_dim(self, num_qubits: int) -> "CircuitOp": return self.permute(list(range(num_qubits, num_qubits + self.num_qubits))) def permute(self, permutation: List[int]) -> "CircuitOp": r""" Permute the qubits of the circuit. Args: permutation: A list defining where each qubit should be permuted. The qubit at index j of the circuit should be permuted to position permutation[j]. Returns: A new CircuitOp containing the permuted circuit. """ new_qc = QuantumCircuit(max(permutation) + 1).compose(self.primitive, qubits=permutation) return CircuitOp(new_qc, coeff=self.coeff)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2020, 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. """MatrixOp Class""" from typing import Dict, List, Optional, Set, Union, cast, get_type_hints import numpy as np from scipy.sparse import spmatrix from qiskit import QuantumCircuit from qiskit.circuit import Instruction, ParameterExpression from qiskit.extensions.hamiltonian_gate import HamiltonianGate from qiskit.opflow.exceptions import OpflowError from qiskit.opflow.list_ops.summed_op import SummedOp from qiskit.opflow.list_ops.tensored_op import TensoredOp from qiskit.opflow.operator_base import OperatorBase from qiskit.opflow.primitive_ops.circuit_op import CircuitOp from qiskit.opflow.primitive_ops.primitive_op import PrimitiveOp from qiskit.quantum_info import Operator, Statevector from qiskit.utils import arithmetic from qiskit.utils.deprecation import deprecate_func class MatrixOp(PrimitiveOp): """Deprecated: Class for Operators represented by matrices, backed by Terra's ``Operator`` module.""" primitive: Operator @deprecate_func( since="0.24.0", additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__( self, primitive: Union[list, np.ndarray, spmatrix, Operator], coeff: Union[complex, ParameterExpression] = 1.0, ) -> None: """ Args: primitive: The matrix-like object which defines the behavior of the underlying function. coeff: A coefficient multiplying the primitive Raises: TypeError: invalid parameters. ValueError: invalid parameters. """ primitive_orig = primitive if isinstance(primitive, spmatrix): primitive = primitive.toarray() if isinstance(primitive, (list, np.ndarray)): primitive = Operator(primitive) if not isinstance(primitive, Operator): type_hints = get_type_hints(MatrixOp.__init__).get("primitive") valid_cls = [cls.__name__ for cls in type_hints.__args__] raise TypeError( f"MatrixOp can only be instantiated with {valid_cls}, " f"not '{primitive_orig.__class__.__name__}'" ) if primitive.input_dims() != primitive.output_dims(): raise ValueError("Cannot handle non-square matrices yet.") super().__init__(primitive, coeff=coeff) def primitive_strings(self) -> Set[str]: return {"Matrix"} @property def num_qubits(self) -> int: return len(self.primitive.input_dims()) def add(self, other: OperatorBase) -> Union["MatrixOp", SummedOp]: if not self.num_qubits == other.num_qubits: raise ValueError( "Sum over operators with different numbers of qubits, {} and {}, is not well " "defined".format(self.num_qubits, other.num_qubits) ) if isinstance(other, MatrixOp) and self.primitive == other.primitive: return MatrixOp(self.primitive, coeff=self.coeff + other.coeff) # Terra's Operator cannot handle ParameterExpressions if ( isinstance(other, MatrixOp) and not isinstance(self.coeff, ParameterExpression) and not isinstance(other.coeff, ParameterExpression) ): return MatrixOp((self.coeff * self.primitive) + (other.coeff * other.primitive)) # Covers Paulis, Circuits, and all else. return SummedOp([self, other]) def adjoint(self) -> "MatrixOp": return MatrixOp(self.primitive.adjoint(), coeff=self.coeff.conjugate()) def equals(self, other: OperatorBase) -> bool: if not isinstance(other, MatrixOp): return False if isinstance(self.coeff, ParameterExpression) ^ isinstance( other.coeff, ParameterExpression ): return False if isinstance(self.coeff, ParameterExpression) and isinstance( other.coeff, ParameterExpression ): return self.coeff == other.coeff and self.primitive == other.primitive return self.coeff * self.primitive == other.coeff * other.primitive def _expand_dim(self, num_qubits: int) -> "MatrixOp": identity = np.identity(2**num_qubits, dtype=complex) return MatrixOp(self.primitive.tensor(Operator(identity)), coeff=self.coeff) def tensor(self, other: OperatorBase) -> Union["MatrixOp", TensoredOp]: if isinstance(other, MatrixOp): return MatrixOp(self.primitive.tensor(other.primitive), coeff=self.coeff * other.coeff) return TensoredOp([self, other]) def compose( self, other: OperatorBase, permutation: Optional[List[int]] = None, front: bool = False ) -> OperatorBase: new_self, other = self._expand_shorter_operator_and_permute(other, permutation) new_self = cast(MatrixOp, new_self) if front: return other.compose(new_self) if isinstance(other, MatrixOp): return MatrixOp( new_self.primitive.compose(other.primitive, front=True), coeff=new_self.coeff * other.coeff, ) return super(MatrixOp, new_self).compose(other) def permute(self, permutation: Optional[List[int]] = None) -> OperatorBase: """Creates a new MatrixOp that acts on the permuted qubits. Args: permutation: A list defining where each qubit should be permuted. The qubit at index j should be permuted to position permutation[j]. Returns: A new MatrixOp representing the permuted operator. Raises: OpflowError: if indices do not define a new index for each qubit. """ new_self = self new_matrix_size = max(permutation) + 1 if self.num_qubits != len(permutation): raise OpflowError("New index must be defined for each qubit of the operator.") if self.num_qubits < new_matrix_size: # pad the operator with identities new_self = self._expand_dim(new_matrix_size - self.num_qubits) qc = QuantumCircuit(new_matrix_size) # extend the indices to match the size of the new matrix permutation = ( list(filter(lambda x: x not in permutation, range(new_matrix_size))) + permutation ) # decompose permutation into sequence of transpositions transpositions = arithmetic.transpositions(permutation) for trans in transpositions: qc.swap(trans[0], trans[1]) matrix = CircuitOp(qc).to_matrix() return MatrixOp(matrix.transpose()) @ new_self @ MatrixOp(matrix) def to_matrix(self, massive: bool = False) -> np.ndarray: return self.primitive.data * self.coeff def __str__(self) -> str: prim_str = str(self.primitive) if self.coeff == 1.0: return prim_str else: return f"{self.coeff} * {prim_str}" def eval( self, front: Optional[ Union[str, Dict[str, complex], np.ndarray, OperatorBase, Statevector] ] = None, ) -> Union[OperatorBase, complex]: # For other ops' eval we return self.to_matrix_op() here, but that's unnecessary here. if front is None: return self # pylint: disable=cyclic-import from ..list_ops import ListOp from ..state_fns import StateFn, VectorStateFn, OperatorStateFn new_front = None # For now, always do this. If it's not performant, we can be more granular. if not isinstance(front, OperatorBase): front = StateFn(front, is_measurement=False) if isinstance(front, ListOp) and front.distributive: new_front = front.combo_fn( [self.eval(front.coeff * front_elem) for front_elem in front.oplist] ) elif isinstance(front, OperatorStateFn): new_front = OperatorStateFn(self.adjoint().compose(front.to_matrix_op()).compose(self)) elif isinstance(front, OperatorBase): new_front = VectorStateFn(self.to_matrix() @ front.to_matrix()) return new_front def exp_i(self) -> OperatorBase: """Return a ``CircuitOp`` equivalent to e^-iH for this operator H""" return CircuitOp(HamiltonianGate(self.primitive, time=self.coeff)) # Op Conversions def to_matrix_op(self, massive: bool = False) -> "MatrixOp": return self def to_instruction(self) -> Instruction: return (self.coeff * self.primitive).to_instruction()
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2020, 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. """PauliOp Class""" from math import pi from typing import Dict, List, Optional, Set, Union, cast import numpy as np from scipy.sparse import spmatrix from qiskit import QuantumCircuit from qiskit.circuit import Instruction, ParameterExpression from qiskit.circuit.library import RXGate, RYGate, RZGate, XGate, YGate, ZGate from qiskit.circuit.library.generalized_gates import PauliGate from qiskit.opflow.exceptions import OpflowError from qiskit.opflow.list_ops.summed_op import SummedOp from qiskit.opflow.list_ops.tensored_op import TensoredOp from qiskit.opflow.operator_base import OperatorBase from qiskit.opflow.primitive_ops.primitive_op import PrimitiveOp from qiskit.quantum_info import Pauli, SparsePauliOp, Statevector from qiskit.utils.deprecation import deprecate_func class PauliOp(PrimitiveOp): """Deprecated: Class for Operators backed by Terra's ``Pauli`` module.""" primitive: Pauli @deprecate_func( since="0.24.0", additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__(self, primitive: Pauli, coeff: Union[complex, ParameterExpression] = 1.0) -> None: """ Args: primitive: The Pauli which defines the behavior of the underlying function. coeff: A coefficient multiplying the primitive. Raises: TypeError: invalid parameters. """ if not isinstance(primitive, Pauli): raise TypeError(f"PauliOp can only be instantiated with Paulis, not {type(primitive)}") super().__init__(primitive, coeff=coeff) def primitive_strings(self) -> Set[str]: return {"Pauli"} @property def num_qubits(self) -> int: return len(self.primitive) def add(self, other: OperatorBase) -> OperatorBase: if not self.num_qubits == other.num_qubits: raise ValueError( "Sum over operators with different numbers of qubits, {} and {}, is not well " "defined".format(self.num_qubits, other.num_qubits) ) if isinstance(other, PauliOp) and self.primitive == other.primitive: return PauliOp(self.primitive, coeff=self.coeff + other.coeff) # pylint: disable=cyclic-import from .pauli_sum_op import PauliSumOp if ( isinstance(other, PauliOp) and isinstance(self.coeff, (int, float, complex)) and isinstance(other.coeff, (int, float, complex)) ): return PauliSumOp( SparsePauliOp(self.primitive, coeffs=[self.coeff]) + SparsePauliOp(other.primitive, coeffs=[other.coeff]) ) if isinstance(other, PauliSumOp) and isinstance(self.coeff, (int, float, complex)): return PauliSumOp(SparsePauliOp(self.primitive, coeffs=[self.coeff])) + other return SummedOp([self, other]) def adjoint(self) -> "PauliOp": return PauliOp(self.primitive.adjoint(), coeff=self.coeff.conjugate()) def equals(self, other: OperatorBase) -> bool: if isinstance(other, PauliOp) and self.coeff == other.coeff: return self.primitive == other.primitive # pylint: disable=cyclic-import from .pauli_sum_op import PauliSumOp if isinstance(other, PauliSumOp): return other == self return False def _expand_dim(self, num_qubits: int) -> "PauliOp": return PauliOp(Pauli("I" * num_qubits).expand(self.primitive), coeff=self.coeff) def tensor(self, other: OperatorBase) -> OperatorBase: # Both Paulis if isinstance(other, PauliOp): return PauliOp(self.primitive.tensor(other.primitive), coeff=self.coeff * other.coeff) # pylint: disable=cyclic-import from .pauli_sum_op import PauliSumOp if isinstance(other, PauliSumOp): new_primitive = SparsePauliOp(self.primitive).tensor(other.primitive) return PauliSumOp(new_primitive, coeff=self.coeff * other.coeff) from .circuit_op import CircuitOp if isinstance(other, CircuitOp): return self.to_circuit_op().tensor(other) return TensoredOp([self, other]) def permute(self, permutation: List[int]) -> "PauliOp": """Permutes the sequence of Pauli matrices. Args: permutation: A list defining where each Pauli should be permuted. The Pauli at index j of the primitive should be permuted to position permutation[j]. Returns: A new PauliOp representing the permuted operator. For operator (X ^ Y ^ Z) and indices=[1,2,4], it returns (X ^ I ^ Y ^ Z ^ I). Raises: OpflowError: if indices do not define a new index for each qubit. """ pauli_string = self.primitive.__str__() length = max(permutation) + 1 # size of list must be +1 larger then its max index new_pauli_list = ["I"] * length if len(permutation) != self.num_qubits: raise OpflowError( "List of indices to permute must have the same size as Pauli Operator" ) for i, index in enumerate(permutation): new_pauli_list[-index - 1] = pauli_string[-i - 1] return PauliOp(Pauli("".join(new_pauli_list)), self.coeff) def compose( self, other: OperatorBase, permutation: Optional[List[int]] = None, front: bool = False ) -> OperatorBase: new_self, other = self._expand_shorter_operator_and_permute(other, permutation) new_self = cast(PauliOp, new_self) if front: return other.compose(new_self) # Both Paulis if isinstance(other, PauliOp): product = new_self.primitive.dot(other.primitive) return PrimitiveOp(product, coeff=new_self.coeff * other.coeff) # pylint: disable=cyclic-import from .pauli_sum_op import PauliSumOp if isinstance(other, PauliSumOp): return PauliSumOp( SparsePauliOp(new_self.primitive).dot(other.primitive), coeff=new_self.coeff * other.coeff, ) # pylint: disable=cyclic-import from ..state_fns.circuit_state_fn import CircuitStateFn from .circuit_op import CircuitOp if isinstance(other, (CircuitOp, CircuitStateFn)): return new_self.to_circuit_op().compose(other) return super(PauliOp, new_self).compose(other) def to_matrix(self, massive: bool = False) -> np.ndarray: OperatorBase._check_massive("to_matrix", True, self.num_qubits, massive) return self.primitive.to_matrix() * self.coeff def to_spmatrix(self) -> spmatrix: """Returns SciPy sparse matrix representation of the Operator. Returns: CSR sparse matrix representation of the Operator. Raises: ValueError: invalid parameters. """ return self.primitive.to_matrix(sparse=True) * self.coeff def __str__(self) -> str: prim_str = str(self.primitive) if self.coeff == 1.0: return prim_str else: return f"{self.coeff} * {prim_str}" def eval( self, front: Optional[ Union[str, Dict[str, complex], np.ndarray, OperatorBase, Statevector] ] = None, ) -> Union[OperatorBase, complex]: if front is None: return self.to_matrix_op() # pylint: disable=cyclic-import from ..list_ops.list_op import ListOp from ..state_fns.circuit_state_fn import CircuitStateFn from ..state_fns.dict_state_fn import DictStateFn from ..state_fns.state_fn import StateFn from .circuit_op import CircuitOp new_front = None # For now, always do this. If it's not performant, we can be more granular. if not isinstance(front, OperatorBase): front = StateFn(front, is_measurement=False) if isinstance(front, ListOp) and front.distributive: new_front = front.combo_fn( [self.eval(front.coeff * front_elem) for front_elem in front.oplist] ) else: if self.num_qubits != front.num_qubits: raise ValueError( "eval does not support operands with differing numbers of qubits, " "{} and {}, respectively.".format(self.num_qubits, front.num_qubits) ) if isinstance(front, DictStateFn): new_dict: Dict[str, complex] = {} corrected_x_bits = self.primitive.x[::-1] corrected_z_bits = self.primitive.z[::-1] for bstr, v in front.primitive.items(): bitstr = np.fromiter(bstr, dtype=int).astype(bool) new_b_str = np.logical_xor(bitstr, corrected_x_bits) new_str = "".join(map(str, 1 * new_b_str)) z_factor = np.prod(1 - 2 * np.logical_and(bitstr, corrected_z_bits)) y_factor = np.prod( np.sqrt(1 - 2 * np.logical_and(corrected_x_bits, corrected_z_bits) + 0j) ) new_dict[new_str] = (v * z_factor * y_factor) + new_dict.get(new_str, 0) # The coefficient consists of: # 1. the coefficient of *this* PauliOp (self) # 2. the coefficient of the evaluated DictStateFn (front) # 3. AND acquires the phase of the internal primitive. This is necessary to # ensure that (X @ Z) and (-iY) return the same result. new_front = StateFn( new_dict, coeff=self.coeff * front.coeff * (-1j) ** self.primitive.phase ) elif isinstance(front, StateFn) and front.is_measurement: raise ValueError("Operator composed with a measurement is undefined.") # Composable types with PauliOp elif isinstance(front, (PauliOp, CircuitOp, CircuitStateFn)): new_front = self.compose(front) # Covers VectorStateFn and OperatorStateFn elif isinstance(front, StateFn): new_front = self.to_matrix_op().eval(front.to_matrix_op()) return new_front def exp_i(self) -> OperatorBase: """Return a ``CircuitOp`` equivalent to e^-iH for this operator H.""" # if only one qubit is significant, we can perform the evolution corrected_x = self.primitive.x[::-1] corrected_z = self.primitive.z[::-1] sig_qubits = np.logical_or(corrected_x, corrected_z) if np.sum(sig_qubits) == 0: # e^I is just a global phase, but we can keep track of it! Should we? # For now, just return identity return PauliOp(self.primitive) if np.sum(sig_qubits) == 1: sig_qubit_index = sig_qubits.tolist().index(True) coeff = ( np.real(self.coeff) if not isinstance(self.coeff, ParameterExpression) else self.coeff ) from .circuit_op import CircuitOp # Y rotation if corrected_x[sig_qubit_index] and corrected_z[sig_qubit_index]: rot_op = CircuitOp(RYGate(2 * coeff)) # Z rotation elif corrected_z[sig_qubit_index]: rot_op = CircuitOp(RZGate(2 * coeff)) # X rotation elif corrected_x[sig_qubit_index]: rot_op = CircuitOp(RXGate(2 * coeff)) # pylint: disable=cyclic-import from ..operator_globals import I left_pad = I.tensorpower(sig_qubit_index) right_pad = I.tensorpower(self.num_qubits - sig_qubit_index - 1) # Need to use overloaded operators here in case left_pad == I^0 return left_pad ^ rot_op ^ right_pad else: from ..evolutions.evolved_op import EvolvedOp return EvolvedOp(self) def to_circuit(self) -> QuantumCircuit: pauli = self.primitive.to_label()[-self.num_qubits :] phase = self.primitive.phase qc = QuantumCircuit(self.num_qubits) if pauli == "I" * self.num_qubits: qc.global_phase = -phase * pi / 2 return qc if self.num_qubits == 1: if pauli != "I": gate = {"X": XGate, "Y": YGate, "Z": ZGate}[pauli] qc.append(gate(), [0]) else: gate = PauliGate(pauli) qc.append(gate, range(self.num_qubits)) if not phase: return qc qc.global_phase = -phase * pi / 2 return qc def to_instruction(self) -> Instruction: # TODO should we just do the following because performance of adding and deleting IGates # doesn't matter? # (Reduce removes extra IGates). # return PrimitiveOp(self.primitive.to_instruction(), coeff=self.coeff).reduce() return self.primitive.to_instruction() def to_pauli_op(self, massive: bool = False) -> "PauliOp": return self
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2020, 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. """PrimitiveOp Class""" from typing import Dict, List, Optional, Set, Union, cast import numpy as np import scipy.linalg from scipy.sparse import spmatrix from qiskit import QuantumCircuit from qiskit.circuit import Instruction, ParameterExpression from qiskit.opflow.operator_base import OperatorBase from qiskit.quantum_info import Operator, Pauli, SparsePauliOp, Statevector from qiskit.utils.deprecation import deprecate_func class PrimitiveOp(OperatorBase): r""" Deprecated: A class for representing basic Operators, backed by Operator primitives from Terra. This class (and inheritors) primarily serves to allow the underlying primitives to "flow" - i.e. interoperability and adherence to the Operator formalism - while the core computational logic mostly remains in the underlying primitives. For example, we would not produce an interface in Terra in which ``QuantumCircuit1 + QuantumCircuit2`` equaled the Operator sum of the circuit unitaries, rather than simply appending the circuits. However, within the Operator flow summing the unitaries is the expected behavior. Note that all mathematical methods are not in-place, meaning that they return a new object, but the underlying primitives are not copied. """ def __init_subclass__(cls): cls.__new__ = lambda cls, *args, **kwargs: super().__new__(cls) @staticmethod # pylint: disable=unused-argument def __new__( cls, primitive: Union[ Instruction, QuantumCircuit, List, np.ndarray, spmatrix, Operator, Pauli, SparsePauliOp ], coeff: Union[complex, ParameterExpression] = 1.0, ) -> "PrimitiveOp": """A factory method to produce the correct type of PrimitiveOp subclass based on the primitive passed in. Primitive and coeff arguments are passed into subclass's init() as-is automatically by new(). Args: primitive: The operator primitive being wrapped. coeff: A coefficient multiplying the primitive. Returns: The appropriate PrimitiveOp subclass for ``primitive``. Raises: TypeError: Unsupported primitive type passed. """ # pylint: disable=cyclic-import if isinstance(primitive, (Instruction, QuantumCircuit)): from .circuit_op import CircuitOp return super().__new__(CircuitOp) if isinstance(primitive, (list, np.ndarray, spmatrix, Operator)): from .matrix_op import MatrixOp return super().__new__(MatrixOp) if isinstance(primitive, Pauli): from .pauli_op import PauliOp return super().__new__(PauliOp) if isinstance(primitive, SparsePauliOp): from .pauli_sum_op import PauliSumOp return super().__new__(PauliSumOp) raise TypeError( "Unsupported primitive type {} passed into PrimitiveOp " "factory constructor".format(type(primitive)) ) @deprecate_func( since="0.24.0", additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__( self, primitive: Union[QuantumCircuit, Operator, Pauli, SparsePauliOp, OperatorBase], coeff: Union[complex, ParameterExpression] = 1.0, ) -> None: """ Args: primitive: The operator primitive being wrapped. coeff: A coefficient multiplying the primitive. """ super().__init__() self._primitive = primitive self._coeff = coeff @property def primitive(self) -> Union[QuantumCircuit, Operator, Pauli, SparsePauliOp, OperatorBase]: """The primitive defining the underlying function of the Operator. Returns: The primitive object. """ return self._primitive @property def coeff(self) -> Union[complex, ParameterExpression]: """ The scalar coefficient multiplying the Operator. Returns: The coefficient. """ return self._coeff @property def num_qubits(self) -> int: raise NotImplementedError @property def settings(self) -> Dict: """Return operator settings.""" return {"primitive": self._primitive, "coeff": self._coeff} def primitive_strings(self) -> Set[str]: raise NotImplementedError def add(self, other: OperatorBase) -> OperatorBase: raise NotImplementedError def adjoint(self) -> OperatorBase: raise NotImplementedError def equals(self, other: OperatorBase) -> bool: raise NotImplementedError def mul(self, scalar: Union[complex, ParameterExpression]) -> OperatorBase: if not isinstance(scalar, (int, float, complex, ParameterExpression)): raise ValueError( "Operators can only be scalar multiplied by float or complex, not " "{} of type {}.".format(scalar, type(scalar)) ) # Need to return self.__class__ in case the object is one of the inherited OpPrimitives return self.__class__(self.primitive, coeff=self.coeff * scalar) def tensor(self, other: OperatorBase) -> OperatorBase: raise NotImplementedError def tensorpower(self, other: int) -> Union[OperatorBase, int]: # Hack to make Z^(I^0) work as intended. if other == 0: return 1 if not isinstance(other, int) or other < 0: raise TypeError("Tensorpower can only take positive int arguments") temp = PrimitiveOp(self.primitive, coeff=self.coeff) # type: OperatorBase for _ in range(other - 1): temp = temp.tensor(self) return temp def compose( self, other: OperatorBase, permutation: Optional[List[int]] = None, front: bool = False ) -> OperatorBase: # pylint: disable=cyclic-import from ..list_ops.composed_op import ComposedOp new_self, other = self._expand_shorter_operator_and_permute(other, permutation) if isinstance(other, ComposedOp): comp_with_first = new_self.compose(other.oplist[0]) if not isinstance(comp_with_first, ComposedOp): new_oplist = [comp_with_first] + other.oplist[1:] return ComposedOp(new_oplist, coeff=other.coeff) return ComposedOp([new_self] + other.oplist, coeff=other.coeff) return ComposedOp([new_self, other]) def _expand_dim(self, num_qubits: int) -> OperatorBase: raise NotImplementedError def permute(self, permutation: List[int]) -> OperatorBase: raise NotImplementedError def exp_i(self) -> OperatorBase: """Return Operator exponentiation, equaling e^(-i * op)""" # pylint: disable=cyclic-import from ..evolutions.evolved_op import EvolvedOp return EvolvedOp(self) def log_i(self, massive: bool = False) -> OperatorBase: """Return a ``MatrixOp`` equivalent to log(H)/-i for this operator H. This function is the effective inverse of exp_i, equivalent to finding the Hermitian Operator which produces self when exponentiated.""" # pylint: disable=cyclic-import from ..operator_globals import EVAL_SIG_DIGITS from .matrix_op import MatrixOp return MatrixOp( np.around( scipy.linalg.logm(self.to_matrix(massive=massive)) / -1j, decimals=EVAL_SIG_DIGITS ) ) def __str__(self) -> str: raise NotImplementedError def __repr__(self) -> str: return f"{type(self).__name__}({repr(self.primitive)}, coeff={self.coeff})" def eval( self, front: Optional[ Union[str, Dict[str, complex], np.ndarray, OperatorBase, Statevector] ] = None, ) -> Union[OperatorBase, complex]: raise NotImplementedError @property def parameters(self): params = set() if isinstance(self.primitive, (OperatorBase, QuantumCircuit)): params.update(self.primitive.parameters) if isinstance(self.coeff, ParameterExpression): params.update(self.coeff.parameters) return params def assign_parameters(self, param_dict: dict) -> OperatorBase: param_value = self.coeff if isinstance(self.coeff, ParameterExpression): unrolled_dict = self._unroll_param_dict(param_dict) if isinstance(unrolled_dict, list): # pylint: disable=cyclic-import from ..list_ops.list_op import ListOp return ListOp([self.assign_parameters(param_dict) for param_dict in unrolled_dict]) if self.coeff.parameters <= set(unrolled_dict.keys()): binds = {param: unrolled_dict[param] for param in self.coeff.parameters} param_value = complex(self.coeff.bind(binds)) if abs(param_value.imag) == 0: param_value = param_value.real return self.__class__(self.primitive, coeff=param_value) # Nothing to collapse here. def reduce(self) -> OperatorBase: return self def to_matrix(self, massive: bool = False) -> np.ndarray: raise NotImplementedError def to_matrix_op(self, massive: bool = False) -> OperatorBase: """Returns a ``MatrixOp`` equivalent to this Operator.""" coeff = self.coeff op = self.copy() op._coeff = 1 prim_mat = op.to_matrix(massive=massive) from .matrix_op import MatrixOp return MatrixOp(prim_mat, coeff=coeff) def to_instruction(self) -> Instruction: """Returns an ``Instruction`` equivalent to this Operator.""" raise NotImplementedError def to_circuit(self) -> QuantumCircuit: """Returns a ``QuantumCircuit`` equivalent to this Operator.""" qc = QuantumCircuit(self.num_qubits) qc.append(self.to_instruction(), qargs=range(self.primitive.num_qubits)) return qc.decompose() def to_circuit_op(self) -> OperatorBase: """Returns a ``CircuitOp`` equivalent to this Operator.""" from .circuit_op import CircuitOp if self.coeff == 0: return CircuitOp(QuantumCircuit(self.num_qubits), coeff=0) return CircuitOp(self.to_circuit(), coeff=self.coeff) def to_pauli_op(self, massive: bool = False) -> OperatorBase: """Returns a sum of ``PauliOp`` s equivalent to this Operator.""" # pylint: disable=cyclic-import from .matrix_op import MatrixOp mat_op = cast(MatrixOp, self.to_matrix_op(massive=massive)) sparse_pauli = SparsePauliOp.from_operator(mat_op.primitive) if not sparse_pauli.to_list(): from ..operator_globals import I return (I ^ self.num_qubits) * 0.0 from .pauli_op import PauliOp if len(sparse_pauli) == 1: label, coeff = sparse_pauli.to_list()[0] coeff = coeff.real if np.isreal(coeff) else coeff return PauliOp(Pauli(label), coeff * self.coeff) from ..list_ops.summed_op import SummedOp return SummedOp( [ PrimitiveOp( Pauli(label), coeff.real if coeff == coeff.real else coeff, ) for (label, coeff) in sparse_pauli.to_list() ], self.coeff, )
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2020, 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. """CircuitStateFn Class""" from typing import Dict, List, Optional, Set, Union, cast import numpy as np from qiskit import BasicAer, ClassicalRegister, QuantumCircuit, transpile from qiskit.circuit import Instruction, ParameterExpression from qiskit.circuit.exceptions import CircuitError from qiskit.circuit.library import IGate, StatePreparation from qiskit.opflow.exceptions import OpflowError from qiskit.opflow.list_ops.composed_op import ComposedOp from qiskit.opflow.list_ops.list_op import ListOp from qiskit.opflow.list_ops.summed_op import SummedOp from qiskit.opflow.list_ops.tensored_op import TensoredOp from qiskit.opflow.operator_base import OperatorBase from qiskit.opflow.primitive_ops.circuit_op import CircuitOp from qiskit.opflow.primitive_ops.matrix_op import MatrixOp from qiskit.opflow.primitive_ops.pauli_op import PauliOp from qiskit.opflow.state_fns.state_fn import StateFn from qiskit.opflow.state_fns.vector_state_fn import VectorStateFn from qiskit.quantum_info import Statevector from qiskit.utils.deprecation import deprecate_func class CircuitStateFn(StateFn): r""" Deprecated: A class for state functions and measurements which are defined by the action of a QuantumCircuit starting from \|0⟩, and stored using Terra's ``QuantumCircuit`` class. """ primitive: QuantumCircuit # TODO allow normalization somehow? @deprecate_func( since="0.24.0", additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__( self, primitive: Union[QuantumCircuit, Instruction] = None, coeff: Union[complex, ParameterExpression] = 1.0, is_measurement: bool = False, from_operator: bool = False, ) -> None: """ Args: primitive: The ``QuantumCircuit`` (or ``Instruction``, which will be converted) which defines the behavior of the underlying function. coeff: A coefficient multiplying the state function. is_measurement: Whether the StateFn is a measurement operator. from_operator: if True the StateFn is derived from OperatorStateFn. (Default: False) Raises: TypeError: Unsupported primitive, or primitive has ClassicalRegisters. """ if isinstance(primitive, Instruction): qc = QuantumCircuit(primitive.num_qubits) qc.append(primitive, qargs=range(primitive.num_qubits)) primitive = qc if not isinstance(primitive, QuantumCircuit): raise TypeError( "CircuitStateFn can only be instantiated " "with QuantumCircuit, not {}".format(type(primitive)) ) if len(primitive.clbits) != 0: raise TypeError("CircuitOp does not support QuantumCircuits with ClassicalRegisters.") super().__init__(primitive, coeff=coeff, is_measurement=is_measurement) self.from_operator = from_operator @staticmethod def from_dict(density_dict: dict) -> "CircuitStateFn": """Construct the CircuitStateFn from a dict mapping strings to probability densities. Args: density_dict: The dict representing the desired state. Returns: The CircuitStateFn created from the dict. """ # If the dict is sparse (elements <= qubits), don't go # building a statevector to pass to Qiskit's # initializer, just create a sum. if len(density_dict) <= len(list(density_dict.keys())[0]): statefn_circuits = [] for bstr, prob in density_dict.items(): qc = QuantumCircuit(len(bstr)) # NOTE: Reversing endianness!! for (index, bit) in enumerate(reversed(bstr)): if bit == "1": qc.x(index) sf_circuit = CircuitStateFn(qc, coeff=prob) statefn_circuits += [sf_circuit] if len(statefn_circuits) == 1: return statefn_circuits[0] else: return cast(CircuitStateFn, SummedOp(cast(List[OperatorBase], statefn_circuits))) else: sf_dict = StateFn(density_dict) return CircuitStateFn.from_vector(sf_dict.to_matrix()) @staticmethod def from_vector(statevector: np.ndarray) -> "CircuitStateFn": """Construct the CircuitStateFn from a vector representing the statevector. Args: statevector: The statevector representing the desired state. Returns: The CircuitStateFn created from the vector. """ normalization_coeff = np.linalg.norm(statevector) normalized_sv = statevector / normalization_coeff return CircuitStateFn(StatePreparation(normalized_sv), coeff=normalization_coeff) def primitive_strings(self) -> Set[str]: return {"QuantumCircuit"} @property def settings(self) -> Dict: """Return settings.""" data = super().settings data["from_operator"] = self.from_operator return data @property def num_qubits(self) -> int: return self.primitive.num_qubits def add(self, other: OperatorBase) -> OperatorBase: if not self.num_qubits == other.num_qubits: raise ValueError( "Sum over operators with different numbers of qubits, " "{} and {}, is not well " "defined".format(self.num_qubits, other.num_qubits) ) if isinstance(other, CircuitStateFn) and self.primitive == other.primitive: return CircuitStateFn(self.primitive, coeff=self.coeff + other.coeff) # Covers all else. return SummedOp([self, other]) def adjoint(self) -> "CircuitStateFn": try: inverse = self.primitive.inverse() except CircuitError as missing_inverse: raise OpflowError( "Failed to take the inverse of the underlying circuit, the circuit " "is likely not unitary and can therefore not be inverted." ) from missing_inverse return CircuitStateFn( inverse, coeff=self.coeff.conjugate(), is_measurement=(not self.is_measurement) ) def compose( self, other: OperatorBase, permutation: Optional[List[int]] = None, front: bool = False ) -> OperatorBase: if not self.is_measurement and not front: raise ValueError( "Composition with a Statefunctions in the first operand is not defined." ) new_self, other = self._expand_shorter_operator_and_permute(other, permutation) new_self.from_operator = self.from_operator if front: return other.compose(new_self) if isinstance(other, (PauliOp, CircuitOp, MatrixOp)): op_circuit_self = CircuitOp(self.primitive) # Avoid reimplementing compose logic composed_op_circs = cast(CircuitOp, op_circuit_self.compose(other.to_circuit_op())) # Returning CircuitStateFn return CircuitStateFn( composed_op_circs.primitive, is_measurement=self.is_measurement, coeff=self.coeff * other.coeff, from_operator=self.from_operator, ) if isinstance(other, CircuitStateFn) and self.is_measurement: # pylint: disable=cyclic-import from ..operator_globals import Zero return self.compose(CircuitOp(other.primitive)).compose( (Zero ^ self.num_qubits) * other.coeff ) return ComposedOp([new_self, other]) def tensor(self, other: OperatorBase) -> Union["CircuitStateFn", TensoredOp]: r""" Return tensor product between self and other, overloaded by ``^``. Note: You must be conscious of Qiskit's big-endian bit printing convention. Meaning, Plus.tensor(Zero) produces a \|+⟩ on qubit 0 and a \|0⟩ on qubit 1, or \|+⟩⨂\|0⟩, but would produce a QuantumCircuit like: \|0⟩-- \|+⟩-- Because Terra prints circuits and results with qubit 0 at the end of the string or circuit. Args: other: The ``OperatorBase`` to tensor product with self. Returns: An ``OperatorBase`` equivalent to the tensor product of self and other. """ if isinstance(other, CircuitStateFn) and other.is_measurement == self.is_measurement: # Avoid reimplementing tensor, just use CircuitOp's c_op_self = CircuitOp(self.primitive, self.coeff) c_op_other = CircuitOp(other.primitive, other.coeff) c_op = c_op_self.tensor(c_op_other) if isinstance(c_op, CircuitOp): return CircuitStateFn( primitive=c_op.primitive, coeff=c_op.coeff, is_measurement=self.is_measurement, ) return TensoredOp([self, other]) def to_density_matrix(self, massive: bool = False) -> np.ndarray: """ Return numpy matrix of density operator, warn if more than 16 qubits to force the user to set massive=True if they want such a large matrix. Generally big methods like this should require the use of a converter, but in this case a convenience method for quick hacking and access to classical tools is appropriate. """ OperatorBase._check_massive("to_density_matrix", True, self.num_qubits, massive) # Rely on VectorStateFn's logic here. return VectorStateFn(self.to_matrix(massive=massive) * self.coeff).to_density_matrix() def to_matrix(self, massive: bool = False) -> np.ndarray: OperatorBase._check_massive("to_matrix", False, self.num_qubits, massive) # Need to adjoint to get forward statevector and then reverse if self.is_measurement: return np.conj(self.adjoint().to_matrix(massive=massive)) qc = self.to_circuit(meas=False) statevector_backend = BasicAer.get_backend("statevector_simulator") transpiled = transpile(qc, statevector_backend, optimization_level=0) statevector = statevector_backend.run(transpiled).result().get_statevector() from ..operator_globals import EVAL_SIG_DIGITS return np.round(statevector * self.coeff, decimals=EVAL_SIG_DIGITS) def __str__(self) -> str: qc = cast(CircuitStateFn, self.reduce()).to_circuit() prim_str = str(qc.draw(output="text")) if self.coeff == 1.0: return "{}(\n{}\n)".format( "CircuitStateFn" if not self.is_measurement else "CircuitMeasurement", prim_str ) else: return "{}(\n{}\n) * {}".format( "CircuitStateFn" if not self.is_measurement else "CircuitMeasurement", prim_str, self.coeff, ) def assign_parameters(self, param_dict: dict) -> Union["CircuitStateFn", ListOp]: param_value = self.coeff qc = self.primitive if isinstance(self.coeff, ParameterExpression) or self.primitive.parameters: unrolled_dict = self._unroll_param_dict(param_dict) if isinstance(unrolled_dict, list): return ListOp([self.assign_parameters(param_dict) for param_dict in unrolled_dict]) if isinstance(self.coeff, ParameterExpression) and self.coeff.parameters <= set( unrolled_dict.keys() ): param_instersection = set(unrolled_dict.keys()) & self.coeff.parameters binds = {param: unrolled_dict[param] for param in param_instersection} param_value = float(self.coeff.bind(binds)) # & is set intersection, check if any parameters in unrolled are present in circuit # This is different from bind_parameters in Terra because they check for set equality if set(unrolled_dict.keys()) & self.primitive.parameters: # Only bind the params found in the circuit param_instersection = set(unrolled_dict.keys()) & self.primitive.parameters binds = {param: unrolled_dict[param] for param in param_instersection} qc = self.to_circuit().assign_parameters(binds) return self.__class__(qc, coeff=param_value, is_measurement=self.is_measurement) def eval( self, front: Optional[ Union[str, Dict[str, complex], np.ndarray, OperatorBase, Statevector] ] = None, ) -> Union[OperatorBase, complex]: if front is None: vector_state_fn = self.to_matrix_op().eval() return vector_state_fn if not self.is_measurement and isinstance(front, OperatorBase): raise ValueError( "Cannot compute overlap with StateFn or Operator if not Measurement. Try taking " "sf.adjoint() first to convert to measurement." ) if isinstance(front, ListOp) and front.distributive: return front.combo_fn( [self.eval(front.coeff * front_elem) for front_elem in front.oplist] ) # Composable with circuit if isinstance(front, (PauliOp, CircuitOp, MatrixOp, CircuitStateFn)): new_front = self.compose(front) return new_front.eval() return self.to_matrix_op().eval(front) def to_circuit(self, meas: bool = False) -> QuantumCircuit: """Return QuantumCircuit representing StateFn""" if meas: meas_qc = self.primitive.copy() meas_qc.add_register(ClassicalRegister(self.num_qubits)) meas_qc.measure(qubit=range(self.num_qubits), cbit=range(self.num_qubits)) return meas_qc else: return self.primitive def to_circuit_op(self) -> OperatorBase: """Return ``StateFnCircuit`` corresponding to this StateFn.""" return self def to_instruction(self): """Return Instruction corresponding to primitive.""" return self.primitive.to_instruction() # TODO specify backend? def sample( self, shots: int = 1024, massive: bool = False, reverse_endianness: bool = False ) -> dict: """ Sample the state function as a normalized probability distribution. Returns dict of bitstrings in order of probability, with values being probability. """ OperatorBase._check_massive("sample", False, self.num_qubits, massive) qc = self.to_circuit(meas=True) qasm_backend = BasicAer.get_backend("qasm_simulator") transpiled = transpile(qc, qasm_backend, optimization_level=0) counts = qasm_backend.run(transpiled, shots=shots).result().get_counts() if reverse_endianness: scaled_dict = {bstr[::-1]: (prob / shots) for (bstr, prob) in counts.items()} else: scaled_dict = {bstr: (prob / shots) for (bstr, prob) in counts.items()} return dict(sorted(scaled_dict.items(), key=lambda x: x[1], reverse=True)) # Warning - modifying primitive!! def reduce(self) -> "CircuitStateFn": if self.primitive.data is not None: # Need to do this from the end because we're deleting items! for i in reversed(range(len(self.primitive.data))): gate = self.primitive.data[i].operation # Check if Identity or empty instruction (need to check that type is exactly # Instruction because some gates have lazy gate.definition population) # pylint: disable=unidiomatic-typecheck if isinstance(gate, IGate) or ( type(gate) == Instruction and gate.definition.data == [] ): del self.primitive.data[i] return self def _expand_dim(self, num_qubits: int) -> "CircuitStateFn": # this is equivalent to self.tensor(identity_operator), but optimized for better performance # just like in tensor method, qiskit endianness is reversed here return self.permute(list(range(num_qubits, num_qubits + self.num_qubits))) def permute(self, permutation: List[int]) -> "CircuitStateFn": r""" Permute the qubits of the circuit. Args: permutation: A list defining where each qubit should be permuted. The qubit at index j of the circuit should be permuted to position permutation[j]. Returns: A new CircuitStateFn containing the permuted circuit. """ new_qc = QuantumCircuit(max(permutation) + 1).compose(self.primitive, qubits=permutation) return CircuitStateFn(new_qc, coeff=self.coeff, is_measurement=self.is_measurement)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2020, 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. """StateFn Class""" from typing import Callable, Dict, List, Optional, Set, Tuple, Union import numpy as np from qiskit import QuantumCircuit from qiskit.circuit import Instruction, ParameterExpression from qiskit.opflow.operator_base import OperatorBase from qiskit.quantum_info import Statevector from qiskit.result import Result from qiskit.utils.deprecation import deprecate_func class StateFn(OperatorBase): r""" Deprecated: A class for representing state functions and measurements. State functions are defined to be complex functions over a single binary string (as compared to an operator, which is defined as a function over two binary strings, or a function taking a binary function to another binary function). This function may be called by the eval() method. Measurements are defined to be functionals over StateFns, taking them to real values. Generally, this real value is interpreted to represent the probability of some classical state (binary string) being observed from a probabilistic or quantum system represented by a StateFn. This leads to the equivalent definition, which is that a measurement m is a function over binary strings producing StateFns, such that the probability of measuring a given binary string b from a system with StateFn f is equal to the inner product between f and m(b). NOTE: State functions here are not restricted to wave functions, as there is no requirement of normalization. """ def __init_subclass__(cls): cls.__new__ = lambda cls, *args, **kwargs: super().__new__(cls) @staticmethod # pylint: disable=unused-argument def __new__( cls, primitive: Union[ str, dict, Result, list, np.ndarray, Statevector, QuantumCircuit, Instruction, OperatorBase, ] = None, coeff: Union[complex, ParameterExpression] = 1.0, is_measurement: bool = False, ) -> "StateFn": """A factory method to produce the correct type of StateFn subclass based on the primitive passed in. Primitive, coeff, and is_measurement arguments are passed into subclass's init() as-is automatically by new(). Args: primitive: The primitive which defines the behavior of the underlying State function. coeff: A coefficient by which the state function is multiplied. is_measurement: Whether the StateFn is a measurement operator Returns: The appropriate StateFn subclass for ``primitive``. Raises: TypeError: Unsupported primitive type passed. """ # Prevents infinite recursion when subclasses are created if cls.__name__ != StateFn.__name__: return super().__new__(cls) # pylint: disable=cyclic-import if isinstance(primitive, (str, dict, Result)): from .dict_state_fn import DictStateFn return DictStateFn.__new__(DictStateFn) if isinstance(primitive, (list, np.ndarray, Statevector)): from .vector_state_fn import VectorStateFn return VectorStateFn.__new__(VectorStateFn) if isinstance(primitive, (QuantumCircuit, Instruction)): from .circuit_state_fn import CircuitStateFn return CircuitStateFn.__new__(CircuitStateFn) if isinstance(primitive, OperatorBase): from .operator_state_fn import OperatorStateFn return OperatorStateFn.__new__(OperatorStateFn) raise TypeError( "Unsupported primitive type {} passed into StateFn " "factory constructor".format(type(primitive)) ) # TODO allow normalization somehow? @deprecate_func( since="0.24.0", additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__( self, primitive: Union[ str, dict, Result, list, np.ndarray, Statevector, QuantumCircuit, Instruction, OperatorBase, ] = None, coeff: Union[complex, ParameterExpression] = 1.0, is_measurement: bool = False, ) -> None: """ Args: primitive: The primitive which defines the behavior of the underlying State function. coeff: A coefficient by which the state function is multiplied. is_measurement: Whether the StateFn is a measurement operator """ super().__init__() self._primitive = primitive self._is_measurement = is_measurement self._coeff = coeff @property def primitive(self): """The primitive which defines the behavior of the underlying State function.""" return self._primitive @property def coeff(self) -> Union[complex, ParameterExpression]: """A coefficient by which the state function is multiplied.""" return self._coeff @property def is_measurement(self) -> bool: """Whether the StateFn object is a measurement Operator.""" return self._is_measurement @property def settings(self) -> Dict: """Return settings.""" return { "primitive": self._primitive, "coeff": self._coeff, "is_measurement": self._is_measurement, } def primitive_strings(self) -> Set[str]: raise NotImplementedError @property def num_qubits(self) -> int: raise NotImplementedError def add(self, other: OperatorBase) -> OperatorBase: raise NotImplementedError def adjoint(self) -> OperatorBase: raise NotImplementedError def _expand_dim(self, num_qubits: int) -> "StateFn": raise NotImplementedError def permute(self, permutation: List[int]) -> OperatorBase: """Permute the qubits of the state function. Args: permutation: A list defining where each qubit should be permuted. The qubit at index j of the circuit should be permuted to position permutation[j]. Returns: A new StateFn containing the permuted primitive. """ raise NotImplementedError def equals(self, other: OperatorBase) -> bool: if not isinstance(other, type(self)) or not self.coeff == other.coeff: return False return self.primitive == other.primitive # Will return NotImplementedError if not supported def mul(self, scalar: Union[complex, ParameterExpression]) -> OperatorBase: if not isinstance(scalar, (int, float, complex, ParameterExpression)): raise ValueError( "Operators can only be scalar multiplied by float or complex, not " "{} of type {}.".format(scalar, type(scalar)) ) if hasattr(self, "from_operator"): return self.__class__( self.primitive, coeff=self.coeff * scalar, is_measurement=self.is_measurement, from_operator=self.from_operator, ) else: return self.__class__( self.primitive, coeff=self.coeff * scalar, is_measurement=self.is_measurement ) def tensor(self, other: OperatorBase) -> OperatorBase: r""" Return tensor product between self and other, overloaded by ``^``. Note: You must be conscious of Qiskit's big-endian bit printing convention. Meaning, Plus.tensor(Zero) produces a \|+⟩ on qubit 0 and a \|0⟩ on qubit 1, or \|+⟩⨂\|0⟩, but would produce a QuantumCircuit like \|0⟩-- \|+⟩-- Because Terra prints circuits and results with qubit 0 at the end of the string or circuit. Args: other: The ``OperatorBase`` to tensor product with self. Returns: An ``OperatorBase`` equivalent to the tensor product of self and other. """ raise NotImplementedError def tensorpower(self, other: int) -> Union[OperatorBase, int]: if not isinstance(other, int) or other <= 0: raise TypeError("Tensorpower can only take positive int arguments") temp = StateFn( self.primitive, coeff=self.coeff, is_measurement=self.is_measurement ) # type: OperatorBase for _ in range(other - 1): temp = temp.tensor(self) return temp def _expand_shorter_operator_and_permute( self, other: OperatorBase, permutation: Optional[List[int]] = None ) -> Tuple[OperatorBase, OperatorBase]: # pylint: disable=cyclic-import from ..operator_globals import Zero if self == StateFn({"0": 1}, is_measurement=True): # Zero is special - we'll expand it to the correct qubit number. return StateFn("0" * other.num_qubits, is_measurement=True), other elif other == Zero: # Zero is special - we'll expand it to the correct qubit number. return self, StateFn("0" * self.num_qubits) return super()._expand_shorter_operator_and_permute(other, permutation) def to_matrix(self, massive: bool = False) -> np.ndarray: raise NotImplementedError def to_density_matrix(self, massive: bool = False) -> np.ndarray: """Return matrix representing product of StateFn evaluated on pairs of basis states. Overridden by child classes. Args: massive: Whether to allow large conversions, e.g. creating a matrix representing over 16 qubits. Returns: The NumPy array representing the density matrix of the State function. Raises: ValueError: If massive is set to False, and exponentially large computation is needed. """ raise NotImplementedError def compose( self, other: OperatorBase, permutation: Optional[List[int]] = None, front: bool = False ) -> OperatorBase: r""" Composition (Linear algebra-style: A@B(x) = A(B(x))) is not well defined for states in the binary function model, but is well defined for measurements. Args: other: The Operator to compose with self. permutation: ``List[int]`` which defines permutation on other operator. front: If front==True, return ``other.compose(self)``. Returns: An Operator equivalent to the function composition of self and other. Raises: ValueError: If self is not a measurement, it cannot be composed from the right. """ # TODO maybe allow outers later to produce density operators or projectors, but not yet. if not self.is_measurement and not front: raise ValueError( "Composition with a Statefunction in the first operand is not defined." ) new_self, other = self._expand_shorter_operator_and_permute(other, permutation) if front: return other.compose(self) # TODO maybe include some reduction here in the subclasses - vector and Op, op and Op, etc. from ..primitive_ops.circuit_op import CircuitOp if self.primitive == {"0" * self.num_qubits: 1.0} and isinstance(other, CircuitOp): # Returning CircuitStateFn return StateFn( other.primitive, is_measurement=self.is_measurement, coeff=self.coeff * other.coeff ) from ..list_ops.composed_op import ComposedOp if isinstance(other, ComposedOp): return ComposedOp([new_self] + other.oplist, coeff=new_self.coeff * other.coeff) return ComposedOp([new_self, other]) def power(self, exponent: int) -> OperatorBase: """Compose with Self Multiple Times, undefined for StateFns. Args: exponent: The number of times to compose self with self. Raises: ValueError: This function is not defined for StateFns. """ raise ValueError("Composition power over Statefunctions or Measurements is not defined.") def __str__(self) -> str: prim_str = str(self.primitive) if self.coeff == 1.0: return "{}({})".format( "StateFunction" if not self.is_measurement else "Measurement", self.coeff ) else: return "{}({}) * {}".format( "StateFunction" if not self.is_measurement else "Measurement", self.coeff, prim_str ) def __repr__(self) -> str: return "{}({}, coeff={}, is_measurement={})".format( self.__class__.__name__, repr(self.primitive), self.coeff, self.is_measurement ) def eval( self, front: Optional[ Union[str, Dict[str, complex], np.ndarray, OperatorBase, Statevector] ] = None, ) -> Union[OperatorBase, complex]: raise NotImplementedError @property def parameters(self): params = set() if isinstance(self.primitive, (OperatorBase, QuantumCircuit)): params.update(self.primitive.parameters) if isinstance(self.coeff, ParameterExpression): params.update(self.coeff.parameters) return params def assign_parameters(self, param_dict: dict) -> OperatorBase: param_value = self.coeff if isinstance(self.coeff, ParameterExpression): unrolled_dict = self._unroll_param_dict(param_dict) if isinstance(unrolled_dict, list): from ..list_ops.list_op import ListOp return ListOp([self.assign_parameters(param_dict) for param_dict in unrolled_dict]) if self.coeff.parameters <= set(unrolled_dict.keys()): binds = {param: unrolled_dict[param] for param in self.coeff.parameters} param_value = float(self.coeff.bind(binds)) return self.traverse(lambda x: x.assign_parameters(param_dict), coeff=param_value) # Try collapsing primitives where possible. Nothing to collapse here. def reduce(self) -> OperatorBase: return self def traverse( self, convert_fn: Callable, coeff: Optional[Union[complex, ParameterExpression]] = None ) -> OperatorBase: r""" Apply the convert_fn to the internal primitive if the primitive is an Operator (as in the case of ``OperatorStateFn``). Otherwise do nothing. Used by converters. Args: convert_fn: The function to apply to the internal OperatorBase. coeff: A coefficient to multiply by after applying convert_fn. If it is None, self.coeff is used instead. Returns: The converted StateFn. """ if coeff is None: coeff = self.coeff if isinstance(self.primitive, OperatorBase): return StateFn( convert_fn(self.primitive), coeff=coeff, is_measurement=self.is_measurement ) else: return self def to_matrix_op(self, massive: bool = False) -> OperatorBase: """Return a ``VectorStateFn`` for this ``StateFn``. Args: massive: Whether to allow large conversions, e.g. creating a matrix representing over 16 qubits. Returns: A VectorStateFn equivalent to self. """ # pylint: disable=cyclic-import from .vector_state_fn import VectorStateFn return VectorStateFn(self.to_matrix(massive=massive), is_measurement=self.is_measurement) def to_circuit_op(self) -> OperatorBase: """Returns a ``CircuitOp`` equivalent to this Operator.""" raise NotImplementedError # TODO to_dict_op def sample( self, shots: int = 1024, massive: bool = False, reverse_endianness: bool = False ) -> Dict[str, float]: """Sample the state function as a normalized probability distribution. Returns dict of bitstrings in order of probability, with values being probability. Args: shots: The number of samples to take to approximate the State function. massive: Whether to allow large conversions, e.g. creating a matrix representing over 16 qubits. reverse_endianness: Whether to reverse the endianness of the bitstrings in the return dict to match Terra's big-endianness. Returns: A dict containing pairs sampled strings from the State function and sampling frequency divided by shots. """ raise NotImplementedError
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2020, 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. """VectorStateFn Class""" from typing import Dict, List, Optional, Set, Union, cast import numpy as np from qiskit import QuantumCircuit from qiskit.circuit import ParameterExpression from qiskit.opflow.list_ops.list_op import ListOp from qiskit.opflow.list_ops.summed_op import SummedOp from qiskit.opflow.list_ops.tensored_op import TensoredOp from qiskit.opflow.operator_base import OperatorBase from qiskit.opflow.state_fns.state_fn import StateFn from qiskit.quantum_info import Statevector from qiskit.utils import algorithm_globals, arithmetic from qiskit.utils.deprecation import deprecate_func class VectorStateFn(StateFn): """Deprecated: A class for state functions and measurements which are defined in vector representation, and stored using Terra's ``Statevector`` class. """ primitive: Statevector # TODO allow normalization somehow? @deprecate_func( since="0.24.0", additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__( self, primitive: Union[list, np.ndarray, Statevector] = None, coeff: Union[complex, ParameterExpression] = 1.0, is_measurement: bool = False, ) -> None: """ Args: primitive: The ``Statevector``, NumPy array, or list, which defines the behavior of the underlying function. coeff: A coefficient multiplying the state function. is_measurement: Whether the StateFn is a measurement operator """ # Lists and Numpy arrays representing statevectors are stored # in Statevector objects for easier handling. if isinstance(primitive, (np.ndarray, list)): primitive = Statevector(primitive) super().__init__(primitive, coeff=coeff, is_measurement=is_measurement) def primitive_strings(self) -> Set[str]: return {"Vector"} @property def num_qubits(self) -> int: return len(self.primitive.dims()) def add(self, other: OperatorBase) -> OperatorBase: if not self.num_qubits == other.num_qubits: raise ValueError( "Sum over statefns with different numbers of qubits, {} and {}, is not well " "defined".format(self.num_qubits, other.num_qubits) ) # Right now doesn't make sense to add a StateFn to a Measurement if isinstance(other, VectorStateFn) and self.is_measurement == other.is_measurement: # Covers Statevector and custom. return VectorStateFn( (self.coeff * self.primitive) + (other.primitive * other.coeff), is_measurement=self._is_measurement, ) return SummedOp([self, other]) def adjoint(self) -> "VectorStateFn": return VectorStateFn( self.primitive.conjugate(), coeff=self.coeff.conjugate(), is_measurement=(not self.is_measurement), ) def permute(self, permutation: List[int]) -> "VectorStateFn": new_self = self new_num_qubits = max(permutation) + 1 if self.num_qubits != len(permutation): # raise OpflowError("New index must be defined for each qubit of the operator.") pass if self.num_qubits < new_num_qubits: # pad the operator with identities new_self = self._expand_dim(new_num_qubits - self.num_qubits) qc = QuantumCircuit(new_num_qubits) # extend the permutation indices to match the size of the new matrix permutation = ( list(filter(lambda x: x not in permutation, range(new_num_qubits))) + permutation ) # decompose permutation into sequence of transpositions transpositions = arithmetic.transpositions(permutation) for trans in transpositions: qc.swap(trans[0], trans[1]) from ..primitive_ops.circuit_op import CircuitOp matrix = CircuitOp(qc).to_matrix() vector = new_self.primitive.data new_vector = cast(np.ndarray, matrix.dot(vector)) return VectorStateFn( primitive=new_vector, coeff=self.coeff, is_measurement=self.is_measurement ) def to_dict_fn(self) -> StateFn: """Creates the equivalent state function of type DictStateFn. Returns: A new DictStateFn equivalent to ``self``. """ from .dict_state_fn import DictStateFn num_qubits = self.num_qubits new_dict = {format(i, "b").zfill(num_qubits): v for i, v in enumerate(self.primitive.data)} return DictStateFn(new_dict, coeff=self.coeff, is_measurement=self.is_measurement) def _expand_dim(self, num_qubits: int) -> "VectorStateFn": primitive = np.zeros(2**num_qubits, dtype=complex) return VectorStateFn( self.primitive.tensor(primitive), coeff=self.coeff, is_measurement=self.is_measurement ) def tensor(self, other: OperatorBase) -> OperatorBase: if isinstance(other, VectorStateFn): return StateFn( self.primitive.tensor(other.primitive), coeff=self.coeff * other.coeff, is_measurement=self.is_measurement, ) return TensoredOp([self, other]) def to_density_matrix(self, massive: bool = False) -> np.ndarray: OperatorBase._check_massive("to_density_matrix", True, self.num_qubits, massive) return self.primitive.to_operator().data * self.coeff def to_matrix(self, massive: bool = False) -> np.ndarray: OperatorBase._check_massive("to_matrix", False, self.num_qubits, massive) vec = self.primitive.data * self.coeff return vec if not self.is_measurement else vec.reshape(1, -1) def to_matrix_op(self, massive: bool = False) -> OperatorBase: return self def to_circuit_op(self) -> OperatorBase: """Return ``StateFnCircuit`` corresponding to this StateFn.""" # pylint: disable=cyclic-import from .circuit_state_fn import CircuitStateFn csfn = CircuitStateFn.from_vector(self.primitive.data) * self.coeff return csfn.adjoint() if self.is_measurement else csfn def __str__(self) -> str: prim_str = str(self.primitive) if self.coeff == 1.0: return "{}({})".format( "VectorStateFn" if not self.is_measurement else "MeasurementVector", prim_str ) else: return "{}({}) * {}".format( "VectorStateFn" if not self.is_measurement else "MeasurementVector", prim_str, self.coeff, ) # pylint: disable=too-many-return-statements def eval( self, front: Optional[ Union[str, Dict[str, complex], np.ndarray, Statevector, OperatorBase] ] = None, ) -> Union[OperatorBase, complex]: if front is None: # this object is already a VectorStateFn return self if not self.is_measurement and isinstance(front, OperatorBase): raise ValueError( "Cannot compute overlap with StateFn or Operator if not Measurement. Try taking " "sf.adjoint() first to convert to measurement." ) if isinstance(front, ListOp) and front.distributive: return front.combo_fn( [self.eval(front.coeff * front_elem) for front_elem in front.oplist] ) if not isinstance(front, OperatorBase): front = StateFn(front) # pylint: disable=cyclic-import from ..operator_globals import EVAL_SIG_DIGITS from .operator_state_fn import OperatorStateFn from .circuit_state_fn import CircuitStateFn from .dict_state_fn import DictStateFn if isinstance(front, DictStateFn): return np.round( sum( v * self.primitive.data[int(b, 2)] * front.coeff for (b, v) in front.primitive.items() ) * self.coeff, decimals=EVAL_SIG_DIGITS, ) if isinstance(front, VectorStateFn): # Need to extract the element or np.array([1]) is returned. return np.round( np.dot(self.to_matrix(), front.to_matrix())[0], decimals=EVAL_SIG_DIGITS ) if isinstance(front, CircuitStateFn): # Don't reimplement logic from CircuitStateFn return np.conj(front.adjoint().eval(self.adjoint().primitive)) * self.coeff if isinstance(front, OperatorStateFn): return front.adjoint().eval(self.primitive) * self.coeff return front.adjoint().eval(self.adjoint().primitive).adjoint() * self.coeff # type: ignore def sample( self, shots: int = 1024, massive: bool = False, reverse_endianness: bool = False ) -> dict: deterministic_counts = self.primitive.probabilities_dict() # Don't need to square because probabilities_dict already does. probs = np.array(list(deterministic_counts.values())) unique, counts = np.unique( algorithm_globals.random.choice( list(deterministic_counts.keys()), size=shots, p=(probs / sum(probs)) ), return_counts=True, ) counts = dict(zip(unique, counts)) if reverse_endianness: scaled_dict = {bstr[::-1]: (prob / shots) for (bstr, prob) in counts.items()} else: scaled_dict = {bstr: (prob / shots) for (bstr, prob) in counts.items()} return dict(sorted(scaled_dict.items(), key=lambda x: x[1], reverse=True))
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# 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. r""" =================== Overview of Sampler =================== Sampler class calculates probabilities or quasi-probabilities of bitstrings from quantum circuits. A sampler is initialized with an empty parameter set. The sampler is used to create a :class:`~qiskit.providers.JobV1`, via the :meth:`qiskit.primitives.Sampler.run()` method. This method is called with the following parameters * quantum circuits (:math:`\psi_i(\theta)`): list of (parameterized) quantum circuits. (a list of :class:`~qiskit.circuit.QuantumCircuit` objects) * parameter values (:math:`\theta_k`): list of sets of parameter values to be bound to the parameters of the quantum circuits. (list of list of float) The method returns a :class:`~qiskit.providers.JobV1` object, calling :meth:`qiskit.providers.JobV1.result()` yields a :class:`~qiskit.primitives.SamplerResult` object, which contains probabilities or quasi-probabilities of bitstrings, plus optional metadata like error bars in the samples. Here is an example of how sampler is used. .. code-block:: python from qiskit.primitives import Sampler from qiskit import QuantumCircuit from qiskit.circuit.library import RealAmplitudes # a Bell circuit bell = QuantumCircuit(2) bell.h(0) bell.cx(0, 1) bell.measure_all() # two parameterized circuits pqc = RealAmplitudes(num_qubits=2, reps=2) pqc.measure_all() pqc2 = RealAmplitudes(num_qubits=2, reps=3) pqc2.measure_all() theta1 = [0, 1, 1, 2, 3, 5] theta2 = [0, 1, 2, 3, 4, 5, 6, 7] # initialization of the sampler sampler = Sampler() # Sampler runs a job on the Bell circuit job = sampler.run(circuits=[bell], parameter_values=[[]], parameters=[[]]) job_result = job.result() print([q.binary_probabilities() for q in job_result.quasi_dists]) # Sampler runs a job on the parameterized circuits job2 = sampler.run( circuits=[pqc, pqc2], parameter_values=[theta1, theta2], parameters=[pqc.parameters, pqc2.parameters]) job_result = job2.result() print([q.binary_probabilities() for q in job_result.quasi_dists]) """ from __future__ import annotations from abc import abstractmethod from collections.abc import Sequence from copy import copy from typing import Generic, TypeVar from qiskit.circuit import QuantumCircuit from qiskit.circuit.parametertable import ParameterView from qiskit.providers import JobV1 as Job from .base_primitive import BasePrimitive T = TypeVar("T", bound=Job) class BaseSampler(BasePrimitive, Generic[T]): """Sampler base class Base class of Sampler that calculates quasi-probabilities of bitstrings from quantum circuits. """ __hash__ = None def __init__( self, *, options: dict | None = None, ): """ Args: options: Default options. """ self._circuits = [] self._parameters = [] super().__init__(options) def run( self, circuits: QuantumCircuit | Sequence[QuantumCircuit], parameter_values: Sequence[float] | Sequence[Sequence[float]] | None = None, **run_options, ) -> T: """Run the job of the sampling of bitstrings. Args: circuits: One of more circuit objects. parameter_values: Parameters to be bound to the circuit. run_options: Backend runtime options used for circuit execution. Returns: The job object of the result of the sampler. The i-th result corresponds to ``circuits[i]`` evaluated with parameters bound as ``parameter_values[i]``. Raises: ValueError: Invalid arguments are given. """ # Singular validation circuits = self._validate_circuits(circuits) parameter_values = self._validate_parameter_values( parameter_values, default=[()] * len(circuits), ) # Cross-validation self._cross_validate_circuits_parameter_values(circuits, parameter_values) # Options run_opts = copy(self.options) run_opts.update_options(**run_options) return self._run( circuits, parameter_values, **run_opts.__dict__, ) @abstractmethod def _run( self, circuits: tuple[QuantumCircuit, ...], parameter_values: tuple[tuple[float, ...], ...], **run_options, ) -> T: raise NotImplementedError("The subclass of BaseSampler must implment `_run` method.") # TODO: validate measurement gates are present @classmethod def _validate_circuits( cls, circuits: Sequence[QuantumCircuit] | QuantumCircuit, ) -> tuple[QuantumCircuit, ...]: circuits = super()._validate_circuits(circuits) for i, circuit in enumerate(circuits): if circuit.num_clbits == 0: raise ValueError( f"The {i}-th circuit does not have any classical bit. " "Sampler requires classical bits, plus measurements " "on the desired qubits." ) return circuits @property def circuits(self) -> tuple[QuantumCircuit, ...]: """Quantum circuits to be sampled. Returns: The quantum circuits to be sampled. """ return tuple(self._circuits) @property def parameters(self) -> tuple[ParameterView, ...]: """Parameters of quantum circuits. Returns: List of the parameters in each quantum circuit. """ return tuple(self._parameters)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# 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. """Contains functions used by the basic aer simulators. """ from string import ascii_uppercase, ascii_lowercase from typing import List, Optional import numpy as np import qiskit.circuit.library.standard_gates as gates from qiskit.exceptions import QiskitError # Single qubit gates supported by ``single_gate_params``. SINGLE_QUBIT_GATES = ("U", "u1", "u2", "u3", "rz", "sx", "x") def single_gate_matrix(gate: str, params: Optional[List[float]] = None): """Get the matrix for a single qubit. Args: gate: the single qubit gate name params: the operation parameters op['params'] Returns: array: A numpy array representing the matrix Raises: QiskitError: If a gate outside the supported set is passed in for the ``Gate`` argument. """ if params is None: params = [] if gate == "U": gc = gates.UGate elif gate == "u3": gc = gates.U3Gate elif gate == "u2": gc = gates.U2Gate elif gate == "u1": gc = gates.U1Gate elif gate == "rz": gc = gates.RZGate elif gate == "id": gc = gates.IGate elif gate == "sx": gc = gates.SXGate elif gate == "x": gc = gates.XGate else: raise QiskitError("Gate is not a valid basis gate for this simulator: %s" % gate) return gc(*params).to_matrix() # Cache CX matrix as no parameters. _CX_MATRIX = gates.CXGate().to_matrix() def cx_gate_matrix(): """Get the matrix for a controlled-NOT gate.""" return np.array([[1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0]], dtype=complex) def einsum_matmul_index(gate_indices, number_of_qubits): """Return the index string for Numpy.einsum matrix-matrix multiplication. The returned indices are to perform a matrix multiplication A.B where the matrix A is an M-qubit matrix, matrix B is an N-qubit matrix, and M <= N, and identity matrices are implied on the subsystems where A has no support on B. Args: gate_indices (list[int]): the indices of the right matrix subsystems to contract with the left matrix. number_of_qubits (int): the total number of qubits for the right matrix. Returns: str: An indices string for the Numpy.einsum function. """ mat_l, mat_r, tens_lin, tens_lout = _einsum_matmul_index_helper(gate_indices, number_of_qubits) # Right indices for the N-qubit input and output tensor tens_r = ascii_uppercase[:number_of_qubits] # Combine indices into matrix multiplication string format # for numpy.einsum function return "{mat_l}{mat_r}, ".format( mat_l=mat_l, mat_r=mat_r ) + "{tens_lin}{tens_r}->{tens_lout}{tens_r}".format( tens_lin=tens_lin, tens_lout=tens_lout, tens_r=tens_r ) def einsum_vecmul_index(gate_indices, number_of_qubits): """Return the index string for Numpy.einsum matrix-vector multiplication. The returned indices are to perform a matrix multiplication A.v where the matrix A is an M-qubit matrix, vector v is an N-qubit vector, and M <= N, and identity matrices are implied on the subsystems where A has no support on v. Args: gate_indices (list[int]): the indices of the right matrix subsystems to contract with the left matrix. number_of_qubits (int): the total number of qubits for the right matrix. Returns: str: An indices string for the Numpy.einsum function. """ mat_l, mat_r, tens_lin, tens_lout = _einsum_matmul_index_helper(gate_indices, number_of_qubits) # Combine indices into matrix multiplication string format # for numpy.einsum function return f"{mat_l}{mat_r}, " + "{tens_lin}->{tens_lout}".format( tens_lin=tens_lin, tens_lout=tens_lout ) def _einsum_matmul_index_helper(gate_indices, number_of_qubits): """Return the index string for Numpy.einsum matrix multiplication. The returned indices are to perform a matrix multiplication A.v where the matrix A is an M-qubit matrix, matrix v is an N-qubit vector, and M <= N, and identity matrices are implied on the subsystems where A has no support on v. Args: gate_indices (list[int]): the indices of the right matrix subsystems to contract with the left matrix. number_of_qubits (int): the total number of qubits for the right matrix. Returns: tuple: (mat_left, mat_right, tens_in, tens_out) of index strings for that may be combined into a Numpy.einsum function string. Raises: QiskitError: if the total number of qubits plus the number of contracted indices is greater than 26. """ # Since we use ASCII alphabet for einsum index labels we are limited # to 26 total free left (lowercase) and 26 right (uppercase) indexes. # The rank of the contracted tensor reduces this as we need to use that # many characters for the contracted indices if len(gate_indices) + number_of_qubits > 26: raise QiskitError("Total number of free indexes limited to 26") # Indices for N-qubit input tensor tens_in = ascii_lowercase[:number_of_qubits] # Indices for the N-qubit output tensor tens_out = list(tens_in) # Left and right indices for the M-qubit multiplying tensor mat_left = "" mat_right = "" # Update left indices for mat and output for pos, idx in enumerate(reversed(gate_indices)): mat_left += ascii_lowercase[-1 - pos] mat_right += tens_in[-1 - idx] tens_out[-1 - idx] = ascii_lowercase[-1 - pos] tens_out = "".join(tens_out) # Combine indices into matrix multiplication string format # for numpy.einsum function return mat_left, mat_right, tens_in, tens_out
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
import sys import os current_dir = os.getcwd() sys.path.append(current_dir) from quantum_circuit import QuantumCircuit # import qiskit.providers.fake_provider from qiskit.transpiler import CouplingMap import qiskit_ibm_runtime.fake_provider from Backend.backend import Backend class FakeBackend(Backend): def __init__(self, backend_name : str) -> None: self.backend = FakeBackend.get_ibm_fake_backend(backend_name=backend_name) @staticmethod def get_ibm_fake_backend_name_list() -> list[str]: ibm_dir = dir(qiskit_ibm_runtime.fake_provider) return [val for val in ibm_dir if '__' not in val and 'Fake' in val] @staticmethod def get_ibm_fake_backend(backend_name : str): try: return getattr(qiskit_ibm_runtime.fake_provider, backend_name)() except: pass fake_backend_name = FakeBackend.get_ibm_fake_backend_name_list() for backend in fake_backend_name: backend = FakeBackend.get_ibm_fake_backend(backend) if backend is not None: try: if backend.name == backend_name: return backend except: pass return None @staticmethod def get_ibm_fake_backend_names_with_limit(min_qubit : int = 1, max_qubit: int = float('inf')) -> list[str]: limited_backend = [] fake_backend_name = FakeBackend.get_ibm_fake_backend_name_list() for backend in fake_backend_name: backend = FakeBackend.get_ibm_fake_backend(backend) if backend is not None: try: num_qubit = backend.num_qubits if num_qubit >= min_qubit and num_qubit <= max_qubit: limited_backend.append(backend.name) except: pass return limited_backend if __name__ == "__main__": print(FakeBackend.get_ibm_fake_backend_name_list()) backend = FakeBackend('fake_auckland') qc = QuantumCircuit(2) qc.x(0) qc.h(1) qc.measure_all() print(qc.draw()) job = backend.run(qc) print(job.result()) qc_transpile = backend.traspile_qiskit(qc)[0] print(qc_transpile.draw()) job = backend.run(qc_transpile) print(job.result())
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# 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. r""" .. _pulse_builder: ============= Pulse Builder ============= .. We actually want people to think of these functions as being defined within the ``qiskit.pulse`` namespace, not the submodule ``qiskit.pulse.builder``. .. currentmodule: qiskit.pulse Use the pulse builder DSL to write pulse programs with an imperative syntax. .. warning:: The pulse builder interface is still in active development. It may have breaking API changes without deprecation warnings in future releases until otherwise indicated. The pulse builder provides an imperative API for writing pulse programs with less difficulty than the :class:`~qiskit.pulse.Schedule` API. It contextually constructs a pulse schedule and then emits the schedule for execution. For example, to play a series of pulses on channels is as simple as: .. plot:: :include-source: from qiskit import pulse dc = pulse.DriveChannel d0, d1, d2, d3, d4 = dc(0), dc(1), dc(2), dc(3), dc(4) with pulse.build(name='pulse_programming_in') as pulse_prog: pulse.play([1, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1], d0) pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0], d1) pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0], d2) pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0], d3) pulse.play([1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0], d4) pulse_prog.draw() To begin pulse programming we must first initialize our program builder context with :func:`build`, after which we can begin adding program statements. For example, below we write a simple program that :func:`play`\s a pulse: .. plot:: :include-source: from qiskit import execute, pulse d0 = pulse.DriveChannel(0) with pulse.build() as pulse_prog: pulse.play(pulse.Constant(100, 1.0), d0) pulse_prog.draw() The builder initializes a :class:`.pulse.Schedule`, ``pulse_prog`` and then begins to construct the program within the context. The output pulse schedule will survive after the context is exited and can be executed like a normal Qiskit schedule using ``qiskit.execute(pulse_prog, backend)``. Pulse programming has a simple imperative style. This leaves the programmer to worry about the raw experimental physics of pulse programming and not constructing cumbersome data structures. We can optionally pass a :class:`~qiskit.providers.Backend` to :func:`build` to enable enhanced functionality. Below, we prepare a Bell state by automatically compiling the required pulses from their gate-level representations, while simultaneously applying a long decoupling pulse to a neighboring qubit. We terminate the experiment with a measurement to observe the state we prepared. This program which mixes circuits and pulses will be automatically lowered to be run as a pulse program: .. plot:: :include-source: import math from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse3Q # TODO: This example should use a real mock backend. backend = FakeOpenPulse3Q() d2 = pulse.DriveChannel(2) with pulse.build(backend) as bell_prep: pulse.u2(0, math.pi, 0) pulse.cx(0, 1) with pulse.build(backend) as decoupled_bell_prep_and_measure: # We call our bell state preparation schedule constructed above. with pulse.align_right(): pulse.call(bell_prep) pulse.play(pulse.Constant(bell_prep.duration, 0.02), d2) pulse.barrier(0, 1, 2) registers = pulse.measure_all() decoupled_bell_prep_and_measure.draw() With the pulse builder we are able to blend programming on qubits and channels. While the pulse schedule is based on instructions that operate on channels, the pulse builder automatically handles the mapping from qubits to channels for you. In the example below we demonstrate some more features of the pulse builder: .. code-block:: import math from qiskit import pulse, QuantumCircuit from qiskit.pulse import library from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend) as pulse_prog: # Create a pulse. gaussian_pulse = library.gaussian(10, 1.0, 2) # Get the qubit's corresponding drive channel from the backend. d0 = pulse.drive_channel(0) d1 = pulse.drive_channel(1) # Play a pulse at t=0. pulse.play(gaussian_pulse, d0) # Play another pulse directly after the previous pulse at t=10. pulse.play(gaussian_pulse, d0) # The default scheduling behavior is to schedule pulses in parallel # across channels. For example, the statement below # plays the same pulse on a different channel at t=0. pulse.play(gaussian_pulse, d1) # We also provide pulse scheduling alignment contexts. # The default alignment context is align_left. # The sequential context schedules pulse instructions sequentially in time. # This context starts at t=10 due to earlier pulses above. with pulse.align_sequential(): pulse.play(gaussian_pulse, d0) # Play another pulse after at t=20. pulse.play(gaussian_pulse, d1) # We can also nest contexts as each instruction is # contained in its local scheduling context. # The output of a child context is a context-schedule # with the internal instructions timing fixed relative to # one another. This is schedule is then called in the parent context. # Context starts at t=30. with pulse.align_left(): # Start at t=30. pulse.play(gaussian_pulse, d0) # Start at t=30. pulse.play(gaussian_pulse, d1) # Context ends at t=40. # Alignment context where all pulse instructions are # aligned to the right, ie., as late as possible. with pulse.align_right(): # Shift the phase of a pulse channel. pulse.shift_phase(math.pi, d1) # Starts at t=40. pulse.delay(100, d0) # Ends at t=140. # Starts at t=130. pulse.play(gaussian_pulse, d1) # Ends at t=140. # Acquire data for a qubit and store in a memory slot. pulse.acquire(100, 0, pulse.MemorySlot(0)) # We also support a variety of macros for common operations. # Measure all qubits. pulse.measure_all() # Delay on some qubits. # This requires knowledge of which channels belong to which qubits. # delay for 100 cycles on qubits 0 and 1. pulse.delay_qubits(100, 0, 1) # Call a quantum circuit. The pulse builder lazily constructs a quantum # circuit which is then transpiled and scheduled before inserting into # a pulse schedule. # NOTE: Quantum register indices correspond to physical qubit indices. qc = QuantumCircuit(2, 2) qc.cx(0, 1) pulse.call(qc) # Calling a small set of standard gates and decomposing to pulses is # also supported with more natural syntax. pulse.u3(0, math.pi, 0, 0) pulse.cx(0, 1) # It is also be possible to call a preexisting schedule tmp_sched = pulse.Schedule() tmp_sched += pulse.Play(gaussian_pulse, d0) pulse.call(tmp_sched) # We also support: # frequency instructions pulse.set_frequency(5.0e9, d0) # phase instructions pulse.shift_phase(0.1, d0) # offset contexts with pulse.phase_offset(math.pi, d0): pulse.play(gaussian_pulse, d0) The above is just a small taste of what is possible with the builder. See the rest of the module documentation for more information on its capabilities. .. autofunction:: build Channels ======== Methods to return the correct channels for the respective qubit indices. .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeArmonk backend = FakeArmonk() with pulse.build(backend) as drive_sched: d0 = pulse.drive_channel(0) print(d0) .. parsed-literal:: DriveChannel(0) .. autofunction:: acquire_channel .. autofunction:: control_channels .. autofunction:: drive_channel .. autofunction:: measure_channel Instructions ============ Pulse instructions are available within the builder interface. Here's an example: .. plot:: :include-source: from qiskit import pulse from qiskit.providers.fake_provider import FakeArmonk backend = FakeArmonk() with pulse.build(backend) as drive_sched: d0 = pulse.drive_channel(0) a0 = pulse.acquire_channel(0) pulse.play(pulse.library.Constant(10, 1.0), d0) pulse.delay(20, d0) pulse.shift_phase(3.14/2, d0) pulse.set_phase(3.14, d0) pulse.shift_frequency(1e7, d0) pulse.set_frequency(5e9, d0) with pulse.build() as temp_sched: pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), d0) pulse.play(pulse.library.Gaussian(20, -1.0, 3.0), d0) pulse.call(temp_sched) pulse.acquire(30, a0, pulse.MemorySlot(0)) drive_sched.draw() .. autofunction:: acquire .. autofunction:: barrier .. autofunction:: call .. autofunction:: delay .. autofunction:: play .. autofunction:: reference .. autofunction:: set_frequency .. autofunction:: set_phase .. autofunction:: shift_frequency .. autofunction:: shift_phase .. autofunction:: snapshot Contexts ======== Builder aware contexts that modify the construction of a pulse program. For example an alignment context like :func:`align_right` may be used to align all pulses as late as possible in a pulse program. .. plot:: :include-source: from qiskit import pulse d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) with pulse.build() as pulse_prog: with pulse.align_right(): # this pulse will start at t=0 pulse.play(pulse.Constant(100, 1.0), d0) # this pulse will start at t=80 pulse.play(pulse.Constant(20, 1.0), d1) pulse_prog.draw() .. autofunction:: align_equispaced .. autofunction:: align_func .. autofunction:: align_left .. autofunction:: align_right .. autofunction:: align_sequential .. autofunction:: circuit_scheduler_settings .. autofunction:: frequency_offset .. autofunction:: phase_offset .. autofunction:: transpiler_settings Macros ====== Macros help you add more complex functionality to your pulse program. .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeArmonk backend = FakeArmonk() with pulse.build(backend) as measure_sched: mem_slot = pulse.measure(0) print(mem_slot) .. parsed-literal:: MemorySlot(0) .. autofunction:: measure .. autofunction:: measure_all .. autofunction:: delay_qubits Circuit Gates ============= To use circuit level gates within your pulse program call a circuit with :func:`call`. .. warning:: These will be removed in future versions with the release of a circuit builder interface in which it will be possible to calibrate a gate in terms of pulses and use that gate in a circuit. .. code-block:: import math from qiskit import pulse from qiskit.providers.fake_provider import FakeArmonk backend = FakeArmonk() with pulse.build(backend) as u3_sched: pulse.u3(math.pi, 0, math.pi, 0) .. autofunction:: cx .. autofunction:: u1 .. autofunction:: u2 .. autofunction:: u3 .. autofunction:: x Utilities ========= The utility functions can be used to gather attributes about the backend and modify how the program is built. .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeArmonk backend = FakeArmonk() with pulse.build(backend) as u3_sched: print('Number of qubits in backend: {}'.format(pulse.num_qubits())) samples = 160 print('There are {} samples in {} seconds'.format( samples, pulse.samples_to_seconds(160))) seconds = 1e-6 print('There are {} seconds in {} samples.'.format( seconds, pulse.seconds_to_samples(1e-6))) .. parsed-literal:: Number of qubits in backend: 1 There are 160 samples in 3.5555555555555554e-08 seconds There are 1e-06 seconds in 4500 samples. .. autofunction:: active_backend .. autofunction:: active_transpiler_settings .. autofunction:: active_circuit_scheduler_settings .. autofunction:: num_qubits .. autofunction:: qubit_channels .. autofunction:: samples_to_seconds .. autofunction:: seconds_to_samples """ import collections import contextvars import functools import itertools import uuid import warnings from contextlib import contextmanager from functools import singledispatchmethod from typing import ( Any, Callable, ContextManager, Dict, Iterable, List, Mapping, Optional, Set, Tuple, TypeVar, Union, NewType, ) import numpy as np from qiskit import circuit from qiskit.circuit.library import standard_gates as gates from qiskit.circuit.parameterexpression import ParameterExpression, ParameterValueType from qiskit.pulse import ( channels as chans, configuration, exceptions, instructions, macros, library, transforms, ) from qiskit.providers.backend import BackendV2 from qiskit.pulse.instructions import directives from qiskit.pulse.schedule import Schedule, ScheduleBlock from qiskit.pulse.transforms.alignments import AlignmentKind #: contextvars.ContextVar[BuilderContext]: active builder BUILDER_CONTEXTVAR = contextvars.ContextVar("backend") T = TypeVar("T") StorageLocation = NewType("StorageLocation", Union[chans.MemorySlot, chans.RegisterSlot]) def _compile_lazy_circuit_before(function: Callable[..., T]) -> Callable[..., T]: """Decorator thats schedules and calls the lazily compiled circuit before executing the decorated builder method.""" @functools.wraps(function) def wrapper(self, *args, **kwargs): self._compile_lazy_circuit() return function(self, *args, **kwargs) return wrapper def _requires_backend(function: Callable[..., T]) -> Callable[..., T]: """Decorator a function to raise if it is called without a builder with a set backend. """ @functools.wraps(function) def wrapper(self, *args, **kwargs): if self.backend is None: raise exceptions.BackendNotSet( 'This function requires the builder to have a "backend" set.' ) return function(self, *args, **kwargs) return wrapper class _PulseBuilder: """Builder context class.""" __alignment_kinds__ = { "left": transforms.AlignLeft(), "right": transforms.AlignRight(), "sequential": transforms.AlignSequential(), } def __init__( self, backend=None, block: Optional[ScheduleBlock] = None, name: Optional[str] = None, default_alignment: Union[str, AlignmentKind] = "left", default_transpiler_settings: Mapping = None, default_circuit_scheduler_settings: Mapping = None, ): """Initialize the builder context. .. note:: At some point we may consider incorporating the builder into the :class:`~qiskit.pulse.Schedule` class. However, the risk of this is tying the user interface to the intermediate representation. For now we avoid this at the cost of some code duplication. Args: backend (Backend): Input backend to use in builder. If not set certain functionality will be unavailable. block: Initital ``ScheduleBlock`` to build on. name: Name of pulse program to be built. default_alignment: Default scheduling alignment for builder. One of ``left``, ``right``, ``sequential`` or an instance of :class:`~qiskit.pulse.transforms.alignments.AlignmentKind` subclass. default_transpiler_settings: Default settings for the transpiler. default_circuit_scheduler_settings: Default settings for the circuit to pulse scheduler. Raises: PulseError: When invalid ``default_alignment`` or `block` is specified. """ #: Backend: Backend instance for context builder. self._backend = backend #: Union[None, ContextVar]: Token for this ``_PulseBuilder``'s ``ContextVar``. self._backend_ctx_token = None #: QuantumCircuit: Lazily constructed quantum circuit self._lazy_circuit = None #: Dict[str, Any]: Transpiler setting dictionary. self._transpiler_settings = default_transpiler_settings or {} #: Dict[str, Any]: Scheduler setting dictionary. self._circuit_scheduler_settings = default_circuit_scheduler_settings or {} #: List[ScheduleBlock]: Stack of context. self._context_stack = [] #: str: Name of the output program self._name = name # Add root block if provided. Schedule will be built on top of this. if block is not None: if isinstance(block, ScheduleBlock): root_block = block elif isinstance(block, Schedule): root_block = self._naive_typecast_schedule(block) else: raise exceptions.PulseError( f"Input `block` type {block.__class__.__name__} is " "not a valid format. Specify a pulse program." ) self._context_stack.append(root_block) # Set default alignment context alignment = _PulseBuilder.__alignment_kinds__.get(default_alignment, default_alignment) if not isinstance(alignment, AlignmentKind): raise exceptions.PulseError( f"Given `default_alignment` {repr(default_alignment)} is " "not a valid transformation. Set one of " f'{", ".join(_PulseBuilder.__alignment_kinds__.keys())}, ' "or set an instance of `AlignmentKind` subclass." ) self.push_context(alignment) def __enter__(self) -> ScheduleBlock: """Enter this builder context and yield either the supplied schedule or the schedule created for the user. Returns: The schedule that the builder will build on. """ self._backend_ctx_token = BUILDER_CONTEXTVAR.set(self) output = self._context_stack[0] output._name = self._name or output.name return output @_compile_lazy_circuit_before def __exit__(self, exc_type, exc_val, exc_tb): """Exit the builder context and compile the built pulse program.""" self.compile() BUILDER_CONTEXTVAR.reset(self._backend_ctx_token) @property def backend(self): """Returns the builder backend if set. Returns: Optional[Backend]: The builder's backend. """ return self._backend @_compile_lazy_circuit_before def push_context(self, alignment: AlignmentKind): """Push new context to the stack.""" self._context_stack.append(ScheduleBlock(alignment_context=alignment)) @_compile_lazy_circuit_before def pop_context(self) -> ScheduleBlock: """Pop the last context from the stack.""" if len(self._context_stack) == 1: raise exceptions.PulseError("The root context cannot be popped out.") return self._context_stack.pop() def get_context(self) -> ScheduleBlock: """Get current context. Notes: New instruction can be added by `.append_subroutine` or `.append_instruction` method. Use above methods rather than directly accessing to the current context. """ return self._context_stack[-1] @property @_requires_backend def num_qubits(self): """Get the number of qubits in the backend.""" # backendV2 if isinstance(self.backend, BackendV2): return self.backend.num_qubits return self.backend.configuration().n_qubits @property def transpiler_settings(self) -> Mapping: """The builder's transpiler settings.""" return self._transpiler_settings @transpiler_settings.setter @_compile_lazy_circuit_before def transpiler_settings(self, settings: Mapping): self._compile_lazy_circuit() self._transpiler_settings = settings @property def circuit_scheduler_settings(self) -> Mapping: """The builder's circuit to pulse scheduler settings.""" return self._circuit_scheduler_settings @circuit_scheduler_settings.setter @_compile_lazy_circuit_before def circuit_scheduler_settings(self, settings: Mapping): self._compile_lazy_circuit() self._circuit_scheduler_settings = settings @_compile_lazy_circuit_before def compile(self) -> ScheduleBlock: """Compile and output the built pulse program.""" # Not much happens because we currently compile as we build. # This should be offloaded to a true compilation module # once we define a more sophisticated IR. while len(self._context_stack) > 1: current = self.pop_context() self.append_subroutine(current) return self._context_stack[0] def _compile_lazy_circuit(self): """Call a context QuantumCircuit (lazy circuit) and append the output pulse schedule to the builder's context schedule. Note that the lazy circuit is not stored as a call instruction. """ if self._lazy_circuit: lazy_circuit = self._lazy_circuit # reset lazy circuit self._lazy_circuit = self._new_circuit() self.call_subroutine(self._compile_circuit(lazy_circuit)) def _compile_circuit(self, circ) -> Schedule: """Take a QuantumCircuit and output the pulse schedule associated with the circuit.""" from qiskit import compiler # pylint: disable=cyclic-import transpiled_circuit = compiler.transpile(circ, self.backend, **self.transpiler_settings) sched = compiler.schedule( transpiled_circuit, self.backend, **self.circuit_scheduler_settings ) return sched def _new_circuit(self): """Create a new circuit for lazy circuit scheduling.""" return circuit.QuantumCircuit(self.num_qubits) @_compile_lazy_circuit_before def append_instruction(self, instruction: instructions.Instruction): """Add an instruction to the builder's context schedule. Args: instruction: Instruction to append. """ self._context_stack[-1].append(instruction) def append_reference(self, name: str, *extra_keys: str): """Add external program as a :class:`~qiskit.pulse.instructions.Reference` instruction. Args: name: Name of subroutine. extra_keys: Assistance keys to uniquely specify the subroutine. """ inst = instructions.Reference(name, *extra_keys) self.append_instruction(inst) @_compile_lazy_circuit_before def append_subroutine(self, subroutine: Union[Schedule, ScheduleBlock]): """Append a :class:`ScheduleBlock` to the builder's context schedule. This operation doesn't create a reference. Subroutine is directly appended to current context schedule. Args: subroutine: ScheduleBlock to append to the current context block. Raises: PulseError: When subroutine is not Schedule nor ScheduleBlock. """ if not isinstance(subroutine, (ScheduleBlock, Schedule)): raise exceptions.PulseError( f"'{subroutine.__class__.__name__}' is not valid data format in the builder. " "'Schedule' and 'ScheduleBlock' can be appended to the builder context." ) if len(subroutine) == 0: return if isinstance(subroutine, Schedule): subroutine = self._naive_typecast_schedule(subroutine) self._context_stack[-1].append(subroutine) @singledispatchmethod def call_subroutine( self, subroutine: Union[circuit.QuantumCircuit, Schedule, ScheduleBlock], name: Optional[str] = None, value_dict: Optional[Dict[ParameterExpression, ParameterValueType]] = None, **kw_params: ParameterValueType, ): """Call a schedule or circuit defined outside of the current scope. The ``subroutine`` is appended to the context schedule as a call instruction. This logic just generates a convenient program representation in the compiler. Thus, this doesn't affect execution of inline subroutines. See :class:`~pulse.instructions.Call` for more details. Args: subroutine: Target schedule or circuit to append to the current context. name: Name of subroutine if defined. value_dict: Parameter object and assigned value mapping. This is more precise way to identify a parameter since mapping is managed with unique object id rather than name. Especially there is any name collision in a parameter table. kw_params: Parameter values to bind to the target subroutine with string parameter names. If there are parameter name overlapping, these parameters are updated with the same assigned value. Raises: PulseError: - When input subroutine is not valid data format. """ raise exceptions.PulseError( f"Subroutine type {subroutine.__class__.__name__} is " "not valid data format. Call QuantumCircuit, " "Schedule, or ScheduleBlock." ) @call_subroutine.register def _( self, target_block: ScheduleBlock, name: Optional[str] = None, value_dict: Optional[Dict[ParameterExpression, ParameterValueType]] = None, **kw_params: ParameterValueType, ): if len(target_block) == 0: return # Create local parameter assignment local_assignment = {} for param_name, value in kw_params.items(): params = target_block.get_parameters(param_name) if not params: raise exceptions.PulseError( f"Parameter {param_name} is not defined in the target subroutine. " f'{", ".join(map(str, target_block.parameters))} can be specified.' ) for param in params: local_assignment[param] = value if value_dict: if local_assignment.keys() & value_dict.keys(): warnings.warn( "Some parameters provided by 'value_dict' conflict with one through " "keyword arguments. Parameter values in the keyword arguments " "are overridden by the dictionary values.", UserWarning, ) local_assignment.update(value_dict) if local_assignment: target_block = target_block.assign_parameters(local_assignment, inplace=False) if name is None: # Add unique string, not to accidentally override existing reference entry. keys = (target_block.name, uuid.uuid4().hex) else: keys = (name,) self.append_reference(*keys) self.get_context().assign_references({keys: target_block}, inplace=True) @call_subroutine.register def _( self, target_schedule: Schedule, name: Optional[str] = None, value_dict: Optional[Dict[ParameterExpression, ParameterValueType]] = None, **kw_params: ParameterValueType, ): if len(target_schedule) == 0: return self.call_subroutine( self._naive_typecast_schedule(target_schedule), name=name, value_dict=value_dict, **kw_params, ) @call_subroutine.register def _( self, target_circuit: circuit.QuantumCircuit, name: Optional[str] = None, value_dict: Optional[Dict[ParameterExpression, ParameterValueType]] = None, **kw_params: ParameterValueType, ): if len(target_circuit) == 0: return self._compile_lazy_circuit() self.call_subroutine( self._compile_circuit(target_circuit), name=name, value_dict=value_dict, **kw_params, ) @_requires_backend def call_gate(self, gate: circuit.Gate, qubits: Tuple[int, ...], lazy: bool = True): """Call the circuit ``gate`` in the pulse program. The qubits are assumed to be defined on physical qubits. If ``lazy == True`` this circuit will extend a lazily constructed quantum circuit. When an operation occurs that breaks the underlying circuit scheduling assumptions such as adding a pulse instruction or changing the alignment context the circuit will be transpiled and scheduled into pulses with the current active settings. Args: gate: Gate to call. qubits: Qubits to call gate on. lazy: If false the circuit will be transpiled and pulse scheduled immediately. Otherwise, it will extend the active lazy circuit as defined above. """ try: iter(qubits) except TypeError: qubits = (qubits,) if lazy: self._call_gate(gate, qubits) else: self._compile_lazy_circuit() self._call_gate(gate, qubits) self._compile_lazy_circuit() def _call_gate(self, gate, qargs): if self._lazy_circuit is None: self._lazy_circuit = self._new_circuit() self._lazy_circuit.append(gate, qargs=qargs) @staticmethod def _naive_typecast_schedule(schedule: Schedule): # Naively convert into ScheduleBlock from qiskit.pulse.transforms import inline_subroutines, flatten, pad preprocessed_schedule = inline_subroutines(flatten(schedule)) pad(preprocessed_schedule, inplace=True, pad_with=instructions.TimeBlockade) # default to left alignment, namely ASAP scheduling target_block = ScheduleBlock(name=schedule.name) for _, inst in preprocessed_schedule.instructions: target_block.append(inst, inplace=True) return target_block def get_dt(self): """Retrieve dt differently based on the type of Backend""" if isinstance(self.backend, BackendV2): return self.backend.dt return self.backend.configuration().dt def build( backend=None, schedule: Optional[ScheduleBlock] = None, name: Optional[str] = None, default_alignment: Optional[Union[str, AlignmentKind]] = "left", default_transpiler_settings: Optional[Dict[str, Any]] = None, default_circuit_scheduler_settings: Optional[Dict[str, Any]] = None, ) -> ContextManager[ScheduleBlock]: """Create a context manager for launching the imperative pulse builder DSL. To enter a building context and starting building a pulse program: .. code-block:: from qiskit import execute, pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() d0 = pulse.DriveChannel(0) with pulse.build() as pulse_prog: pulse.play(pulse.Constant(100, 0.5), d0) While the output program ``pulse_prog`` cannot be executed as we are using a mock backend. If a real backend is being used, executing the program is done with: .. code-block:: python qiskit.execute(pulse_prog, backend) Args: backend (Backend): A Qiskit backend. If not supplied certain builder functionality will be unavailable. schedule: A pulse ``ScheduleBlock`` in which your pulse program will be built. name: Name of pulse program to be built. default_alignment: Default scheduling alignment for builder. One of ``left``, ``right``, ``sequential`` or an alignment context. default_transpiler_settings: Default settings for the transpiler. default_circuit_scheduler_settings: Default settings for the circuit to pulse scheduler. Returns: A new builder context which has the active builder initialized. """ return _PulseBuilder( backend=backend, block=schedule, name=name, default_alignment=default_alignment, default_transpiler_settings=default_transpiler_settings, default_circuit_scheduler_settings=default_circuit_scheduler_settings, ) # Builder Utilities def _active_builder() -> _PulseBuilder: """Get the active builder in the active context. Returns: The active active builder in this context. Raises: exceptions.NoActiveBuilder: If a pulse builder function is called outside of a builder context. """ try: return BUILDER_CONTEXTVAR.get() except LookupError as ex: raise exceptions.NoActiveBuilder( "A Pulse builder function was called outside of " "a builder context. Try calling within a builder " 'context, eg., "with pulse.build() as schedule: ...".' ) from ex def active_backend(): """Get the backend of the currently active builder context. Returns: Backend: The active backend in the currently active builder context. Raises: exceptions.BackendNotSet: If the builder does not have a backend set. """ builder = _active_builder().backend if builder is None: raise exceptions.BackendNotSet( 'This function requires the active builder to have a "backend" set.' ) return builder def append_schedule(schedule: Union[Schedule, ScheduleBlock]): """Call a schedule by appending to the active builder's context block. Args: schedule: Schedule or ScheduleBlock to append. """ _active_builder().append_subroutine(schedule) def append_instruction(instruction: instructions.Instruction): """Append an instruction to the active builder's context schedule. Examples: .. code-block:: from qiskit import pulse d0 = pulse.DriveChannel(0) with pulse.build() as pulse_prog: pulse.builder.append_instruction(pulse.Delay(10, d0)) print(pulse_prog.instructions) .. parsed-literal:: ((0, Delay(10, DriveChannel(0))),) """ _active_builder().append_instruction(instruction) def num_qubits() -> int: """Return number of qubits in the currently active backend. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend): print(pulse.num_qubits()) .. parsed-literal:: 2 .. note:: Requires the active builder context to have a backend set. """ if isinstance(active_backend(), BackendV2): return active_backend().num_qubits return active_backend().configuration().n_qubits def seconds_to_samples(seconds: Union[float, np.ndarray]) -> Union[int, np.ndarray]: """Obtain the number of samples that will elapse in ``seconds`` on the active backend. Rounds down. Args: seconds: Time in seconds to convert to samples. Returns: The number of samples for the time to elapse """ dt = _active_builder().get_dt() if isinstance(seconds, np.ndarray): return (seconds / dt).astype(int) return int(seconds / dt) def samples_to_seconds(samples: Union[int, np.ndarray]) -> Union[float, np.ndarray]: """Obtain the time in seconds that will elapse for the input number of samples on the active backend. Args: samples: Number of samples to convert to time in seconds. Returns: The time that elapses in ``samples``. """ return samples * _active_builder().get_dt() def qubit_channels(qubit: int) -> Set[chans.Channel]: """Returns the set of channels associated with a qubit. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend): print(pulse.qubit_channels(0)) .. parsed-literal:: {MeasureChannel(0), ControlChannel(0), DriveChannel(0), AcquireChannel(0), ControlChannel(1)} .. note:: Requires the active builder context to have a backend set. .. note:: A channel may still be associated with another qubit in this list such as in the case where significant crosstalk exists. """ # implement as the inner function to avoid API change for a patch release in 0.24.2. def get_qubit_channels_v2(backend: BackendV2, qubit: int): r"""Return a list of channels which operate on the given ``qubit``. Returns: List of ``Channel``\s operated on my the given ``qubit``. """ channels = [] # add multi-qubit channels for node_qubits in backend.coupling_map: if qubit in node_qubits: control_channel = backend.control_channel(node_qubits) if control_channel: channels.extend(control_channel) # add single qubit channels channels.append(backend.drive_channel(qubit)) channels.append(backend.measure_channel(qubit)) channels.append(backend.acquire_channel(qubit)) return channels # backendV2 if isinstance(active_backend(), BackendV2): return set(get_qubit_channels_v2(active_backend(), qubit)) return set(active_backend().configuration().get_qubit_channels(qubit)) def _qubits_to_channels(*channels_or_qubits: Union[int, chans.Channel]) -> Set[chans.Channel]: """Returns the unique channels of the input qubits.""" channels = set() for channel_or_qubit in channels_or_qubits: if isinstance(channel_or_qubit, int): channels |= qubit_channels(channel_or_qubit) elif isinstance(channel_or_qubit, chans.Channel): channels.add(channel_or_qubit) else: raise exceptions.PulseError( f'{channel_or_qubit} is not a "Channel" or qubit (integer).' ) return channels def active_transpiler_settings() -> Dict[str, Any]: """Return the current active builder context's transpiler settings. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() transpiler_settings = {'optimization_level': 3} with pulse.build(backend, default_transpiler_settings=transpiler_settings): print(pulse.active_transpiler_settings()) .. parsed-literal:: {'optimization_level': 3} """ return dict(_active_builder().transpiler_settings) def active_circuit_scheduler_settings() -> Dict[str, Any]: """Return the current active builder context's circuit scheduler settings. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() circuit_scheduler_settings = {'method': 'alap'} with pulse.build( backend, default_circuit_scheduler_settings=circuit_scheduler_settings): print(pulse.active_circuit_scheduler_settings()) .. parsed-literal:: {'method': 'alap'} """ return dict(_active_builder().circuit_scheduler_settings) # Contexts @contextmanager def align_left() -> ContextManager[None]: """Left alignment pulse scheduling context. Pulse instructions within this context are scheduled as early as possible by shifting them left to the earliest available time. Examples: .. code-block:: from qiskit import pulse d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) with pulse.build() as pulse_prog: with pulse.align_left(): # this pulse will start at t=0 pulse.play(pulse.Constant(100, 1.0), d0) # this pulse will start at t=0 pulse.play(pulse.Constant(20, 1.0), d1) pulse_prog = pulse.transforms.block_to_schedule(pulse_prog) assert pulse_prog.ch_start_time(d0) == pulse_prog.ch_start_time(d1) Yields: None """ builder = _active_builder() builder.push_context(transforms.AlignLeft()) try: yield finally: current = builder.pop_context() builder.append_subroutine(current) @contextmanager def align_right() -> AlignmentKind: """Right alignment pulse scheduling context. Pulse instructions within this context are scheduled as late as possible by shifting them right to the latest available time. Examples: .. code-block:: from qiskit import pulse d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) with pulse.build() as pulse_prog: with pulse.align_right(): # this pulse will start at t=0 pulse.play(pulse.Constant(100, 1.0), d0) # this pulse will start at t=80 pulse.play(pulse.Constant(20, 1.0), d1) pulse_prog = pulse.transforms.block_to_schedule(pulse_prog) assert pulse_prog.ch_stop_time(d0) == pulse_prog.ch_stop_time(d1) Yields: None """ builder = _active_builder() builder.push_context(transforms.AlignRight()) try: yield finally: current = builder.pop_context() builder.append_subroutine(current) @contextmanager def align_sequential() -> AlignmentKind: """Sequential alignment pulse scheduling context. Pulse instructions within this context are scheduled sequentially in time such that no two instructions will be played at the same time. Examples: .. code-block:: from qiskit import pulse d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) with pulse.build() as pulse_prog: with pulse.align_sequential(): # this pulse will start at t=0 pulse.play(pulse.Constant(100, 1.0), d0) # this pulse will also start at t=100 pulse.play(pulse.Constant(20, 1.0), d1) pulse_prog = pulse.transforms.block_to_schedule(pulse_prog) assert pulse_prog.ch_stop_time(d0) == pulse_prog.ch_start_time(d1) Yields: None """ builder = _active_builder() builder.push_context(transforms.AlignSequential()) try: yield finally: current = builder.pop_context() builder.append_subroutine(current) @contextmanager def align_equispaced(duration: Union[int, ParameterExpression]) -> AlignmentKind: """Equispaced alignment pulse scheduling context. Pulse instructions within this context are scheduled with the same interval spacing such that the total length of the context block is ``duration``. If the total free ``duration`` cannot be evenly divided by the number of instructions within the context, the modulo is split and then prepended and appended to the returned schedule. Delay instructions are automatically inserted in between pulses. This context is convenient to write a schedule for periodical dynamic decoupling or the Hahn echo sequence. Examples: .. plot:: :include-source: from qiskit import pulse d0 = pulse.DriveChannel(0) x90 = pulse.Gaussian(10, 0.1, 3) x180 = pulse.Gaussian(10, 0.2, 3) with pulse.build() as hahn_echo: with pulse.align_equispaced(duration=100): pulse.play(x90, d0) pulse.play(x180, d0) pulse.play(x90, d0) hahn_echo.draw() Args: duration: Duration of this context. This should be larger than the schedule duration. Yields: None Notes: The scheduling is performed for sub-schedules within the context rather than channel-wise. If you want to apply the equispaced context for each channel, you should use the context independently for channels. """ builder = _active_builder() builder.push_context(transforms.AlignEquispaced(duration=duration)) try: yield finally: current = builder.pop_context() builder.append_subroutine(current) @contextmanager def align_func( duration: Union[int, ParameterExpression], func: Callable[[int], float] ) -> AlignmentKind: """Callback defined alignment pulse scheduling context. Pulse instructions within this context are scheduled at the location specified by arbitrary callback function `position` that takes integer index and returns the associated fractional location within [0, 1]. Delay instruction is automatically inserted in between pulses. This context may be convenient to write a schedule of arbitrary dynamical decoupling sequences such as Uhrig dynamical decoupling. Examples: .. plot:: :include-source: import numpy as np from qiskit import pulse d0 = pulse.DriveChannel(0) x90 = pulse.Gaussian(10, 0.1, 3) x180 = pulse.Gaussian(10, 0.2, 3) def udd10_pos(j): return np.sin(np.pi*j/(2*10 + 2))**2 with pulse.build() as udd_sched: pulse.play(x90, d0) with pulse.align_func(duration=300, func=udd10_pos): for _ in range(10): pulse.play(x180, d0) pulse.play(x90, d0) udd_sched.draw() Args: duration: Duration of context. This should be larger than the schedule duration. func: A function that takes an index of sub-schedule and returns the fractional coordinate of of that sub-schedule. The returned value should be defined within [0, 1]. The pulse index starts from 1. Yields: None Notes: The scheduling is performed for sub-schedules within the context rather than channel-wise. If you want to apply the numerical context for each channel, you need to apply the context independently to channels. """ builder = _active_builder() builder.push_context(transforms.AlignFunc(duration=duration, func=func)) try: yield finally: current = builder.pop_context() builder.append_subroutine(current) @contextmanager def general_transforms(alignment_context: AlignmentKind) -> ContextManager[None]: """Arbitrary alignment transformation defined by a subclass instance of :class:`~qiskit.pulse.transforms.alignments.AlignmentKind`. Args: alignment_context: Alignment context instance that defines schedule transformation. Yields: None Raises: PulseError: When input ``alignment_context`` is not ``AlignmentKind`` subclasses. """ if not isinstance(alignment_context, AlignmentKind): raise exceptions.PulseError("Input alignment context is not `AlignmentKind` subclass.") builder = _active_builder() builder.push_context(alignment_context) try: yield finally: current = builder.pop_context() builder.append_subroutine(current) @contextmanager def transpiler_settings(**settings) -> ContextManager[None]: """Set the currently active transpiler settings for this context. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend): print(pulse.active_transpiler_settings()) with pulse.transpiler_settings(optimization_level=3): print(pulse.active_transpiler_settings()) .. parsed-literal:: {} {'optimization_level': 3} """ builder = _active_builder() curr_transpiler_settings = builder.transpiler_settings builder.transpiler_settings = collections.ChainMap(settings, curr_transpiler_settings) try: yield finally: builder.transpiler_settings = curr_transpiler_settings @contextmanager def circuit_scheduler_settings(**settings) -> ContextManager[None]: """Set the currently active circuit scheduler settings for this context. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend): print(pulse.active_circuit_scheduler_settings()) with pulse.circuit_scheduler_settings(method='alap'): print(pulse.active_circuit_scheduler_settings()) .. parsed-literal:: {} {'method': 'alap'} """ builder = _active_builder() curr_circuit_scheduler_settings = builder.circuit_scheduler_settings builder.circuit_scheduler_settings = collections.ChainMap( settings, curr_circuit_scheduler_settings ) try: yield finally: builder.circuit_scheduler_settings = curr_circuit_scheduler_settings @contextmanager def phase_offset(phase: float, *channels: chans.PulseChannel) -> ContextManager[None]: """Shift the phase of input channels on entry into context and undo on exit. Examples: .. code-block:: import math from qiskit import pulse d0 = pulse.DriveChannel(0) with pulse.build() as pulse_prog: with pulse.phase_offset(math.pi, d0): pulse.play(pulse.Constant(10, 1.0), d0) assert len(pulse_prog.instructions) == 3 Args: phase: Amount of phase offset in radians. channels: Channels to offset phase of. Yields: None """ for channel in channels: shift_phase(phase, channel) try: yield finally: for channel in channels: shift_phase(-phase, channel) @contextmanager def frequency_offset( frequency: float, *channels: chans.PulseChannel, compensate_phase: bool = False ) -> ContextManager[None]: """Shift the frequency of inputs channels on entry into context and undo on exit. Examples: .. code-block:: python :emphasize-lines: 7, 16 from qiskit import pulse d0 = pulse.DriveChannel(0) with pulse.build(backend) as pulse_prog: # shift frequency by 1GHz with pulse.frequency_offset(1e9, d0): pulse.play(pulse.Constant(10, 1.0), d0) assert len(pulse_prog.instructions) == 3 with pulse.build(backend) as pulse_prog: # Shift frequency by 1GHz. # Undo accumulated phase in the shifted frequency frame # when exiting the context. with pulse.frequency_offset(1e9, d0, compensate_phase=True): pulse.play(pulse.Constant(10, 1.0), d0) assert len(pulse_prog.instructions) == 4 Args: frequency: Amount of frequency offset in Hz. channels: Channels to offset frequency of. compensate_phase: Compensate for accumulated phase accumulated with respect to the channels' frame at its initial frequency. Yields: None """ builder = _active_builder() # TODO: Need proper implementation of compensation. t0 may depend on the parent context. # For example, the instruction position within the equispaced context depends on # the current total number of instructions, thus adding more instruction after # offset context may change the t0 when the parent context is transformed. t0 = builder.get_context().duration for channel in channels: shift_frequency(frequency, channel) try: yield finally: if compensate_phase: duration = builder.get_context().duration - t0 accumulated_phase = 2 * np.pi * ((duration * builder.get_dt() * frequency) % 1) for channel in channels: shift_phase(-accumulated_phase, channel) for channel in channels: shift_frequency(-frequency, channel) # Channels def drive_channel(qubit: int) -> chans.DriveChannel: """Return ``DriveChannel`` for ``qubit`` on the active builder backend. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend): assert pulse.drive_channel(0) == pulse.DriveChannel(0) .. note:: Requires the active builder context to have a backend set. """ # backendV2 if isinstance(active_backend(), BackendV2): return active_backend().drive_channel(qubit) return active_backend().configuration().drive(qubit) def measure_channel(qubit: int) -> chans.MeasureChannel: """Return ``MeasureChannel`` for ``qubit`` on the active builder backend. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend): assert pulse.measure_channel(0) == pulse.MeasureChannel(0) .. note:: Requires the active builder context to have a backend set. """ # backendV2 if isinstance(active_backend(), BackendV2): return active_backend().measure_channel(qubit) return active_backend().configuration().measure(qubit) def acquire_channel(qubit: int) -> chans.AcquireChannel: """Return ``AcquireChannel`` for ``qubit`` on the active builder backend. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend): assert pulse.acquire_channel(0) == pulse.AcquireChannel(0) .. note:: Requires the active builder context to have a backend set. """ # backendV2 if isinstance(active_backend(), BackendV2): return active_backend().acquire_channel(qubit) return active_backend().configuration().acquire(qubit) def control_channels(*qubits: Iterable[int]) -> List[chans.ControlChannel]: """Return ``ControlChannel`` for ``qubit`` on the active builder backend. Return the secondary drive channel for the given qubit -- typically utilized for controlling multi-qubit interactions. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend): assert pulse.control_channels(0, 1) == [pulse.ControlChannel(0)] .. note:: Requires the active builder context to have a backend set. Args: qubits: Tuple or list of ordered qubits of the form `(control_qubit, target_qubit)`. Returns: List of control channels associated with the supplied ordered list of qubits. """ # backendV2 if isinstance(active_backend(), BackendV2): return active_backend().control_channel(qubits) return active_backend().configuration().control(qubits=qubits) # Base Instructions def delay(duration: int, channel: chans.Channel, name: Optional[str] = None): """Delay on a ``channel`` for a ``duration``. Examples: .. code-block:: from qiskit import pulse d0 = pulse.DriveChannel(0) with pulse.build() as pulse_prog: pulse.delay(10, d0) Args: duration: Number of cycles to delay for on ``channel``. channel: Channel to delay on. name: Name of the instruction. """ append_instruction(instructions.Delay(duration, channel, name=name)) def play( pulse: Union[library.Pulse, np.ndarray], channel: chans.PulseChannel, name: Optional[str] = None ): """Play a ``pulse`` on a ``channel``. Examples: .. code-block:: from qiskit import pulse d0 = pulse.DriveChannel(0) with pulse.build() as pulse_prog: pulse.play(pulse.Constant(10, 1.0), d0) Args: pulse: Pulse to play. channel: Channel to play pulse on. name: Name of the pulse. """ if not isinstance(pulse, library.Pulse): pulse = library.Waveform(pulse) append_instruction(instructions.Play(pulse, channel, name=name)) def acquire( duration: int, qubit_or_channel: Union[int, chans.AcquireChannel], register: StorageLocation, **metadata: Union[configuration.Kernel, configuration.Discriminator], ): """Acquire for a ``duration`` on a ``channel`` and store the result in a ``register``. Examples: .. code-block:: from qiskit import pulse acq0 = pulse.AcquireChannel(0) mem0 = pulse.MemorySlot(0) with pulse.build() as pulse_prog: pulse.acquire(100, acq0, mem0) # measurement metadata kernel = pulse.configuration.Kernel('linear_discriminator') pulse.acquire(100, acq0, mem0, kernel=kernel) .. note:: The type of data acquire will depend on the execution ``meas_level``. Args: duration: Duration to acquire data for qubit_or_channel: Either the qubit to acquire data for or the specific :class:`~qiskit.pulse.channels.AcquireChannel` to acquire on. register: Location to store measured result. metadata: Additional metadata for measurement. See :class:`~qiskit.pulse.instructions.Acquire` for more information. Raises: exceptions.PulseError: If the register type is not supported. """ if isinstance(qubit_or_channel, int): qubit_or_channel = chans.AcquireChannel(qubit_or_channel) if isinstance(register, chans.MemorySlot): append_instruction( instructions.Acquire(duration, qubit_or_channel, mem_slot=register, **metadata) ) elif isinstance(register, chans.RegisterSlot): append_instruction( instructions.Acquire(duration, qubit_or_channel, reg_slot=register, **metadata) ) else: raise exceptions.PulseError(f'Register of type: "{type(register)}" is not supported') def set_frequency(frequency: float, channel: chans.PulseChannel, name: Optional[str] = None): """Set the ``frequency`` of a pulse ``channel``. Examples: .. code-block:: from qiskit import pulse d0 = pulse.DriveChannel(0) with pulse.build() as pulse_prog: pulse.set_frequency(1e9, d0) Args: frequency: Frequency in Hz to set channel to. channel: Channel to set frequency of. name: Name of the instruction. """ append_instruction(instructions.SetFrequency(frequency, channel, name=name)) def shift_frequency(frequency: float, channel: chans.PulseChannel, name: Optional[str] = None): """Shift the ``frequency`` of a pulse ``channel``. Examples: .. code-block:: python :emphasize-lines: 6 from qiskit import pulse d0 = pulse.DriveChannel(0) with pulse.build() as pulse_prog: pulse.shift_frequency(1e9, d0) Args: frequency: Frequency in Hz to shift channel frequency by. channel: Channel to shift frequency of. name: Name of the instruction. """ append_instruction(instructions.ShiftFrequency(frequency, channel, name=name)) def set_phase(phase: float, channel: chans.PulseChannel, name: Optional[str] = None): """Set the ``phase`` of a pulse ``channel``. Examples: .. code-block:: python :emphasize-lines: 8 import math from qiskit import pulse d0 = pulse.DriveChannel(0) with pulse.build() as pulse_prog: pulse.set_phase(math.pi, d0) Args: phase: Phase in radians to set channel carrier signal to. channel: Channel to set phase of. name: Name of the instruction. """ append_instruction(instructions.SetPhase(phase, channel, name=name)) def shift_phase(phase: float, channel: chans.PulseChannel, name: Optional[str] = None): """Shift the ``phase`` of a pulse ``channel``. Examples: .. code-block:: import math from qiskit import pulse d0 = pulse.DriveChannel(0) with pulse.build() as pulse_prog: pulse.shift_phase(math.pi, d0) Args: phase: Phase in radians to shift channel carrier signal by. channel: Channel to shift phase of. name: Name of the instruction. """ append_instruction(instructions.ShiftPhase(phase, channel, name)) def snapshot(label: str, snapshot_type: str = "statevector"): """Simulator snapshot. Examples: .. code-block:: from qiskit import pulse with pulse.build() as pulse_prog: pulse.snapshot('first', 'statevector') Args: label: Label for snapshot. snapshot_type: Type of snapshot. """ append_instruction(instructions.Snapshot(label, snapshot_type=snapshot_type)) def call( target: Optional[Union[circuit.QuantumCircuit, Schedule, ScheduleBlock]], name: Optional[str] = None, value_dict: Optional[Dict[ParameterValueType, ParameterValueType]] = None, **kw_params: ParameterValueType, ): """Call the subroutine within the currently active builder context with arbitrary parameters which will be assigned to the target program. .. note:: If the ``target`` program is a :class:`.ScheduleBlock`, then a :class:`.Reference` instruction will be created and appended to the current context. The ``target`` program will be immediately assigned to the current scope as a subroutine. If the ``target`` program is :class:`.Schedule`, it will be wrapped by the :class:`.Call` instruction and appended to the current context to avoid a mixed representation of :class:`.ScheduleBlock` and :class:`.Schedule`. If the ``target`` program is a :class:`.QuantumCircuit` it will be scheduled and the new :class:`.Schedule` will be added as a :class:`.Call` instruction. Examples: 1. Calling a schedule block (recommended) .. code-block:: from qiskit import circuit, pulse from qiskit.providers.fake_provider import FakeBogotaV2 backend = FakeBogotaV2() with pulse.build() as x_sched: pulse.play(pulse.Gaussian(160, 0.1, 40), pulse.DriveChannel(0)) with pulse.build() as pulse_prog: pulse.call(x_sched) print(pulse_prog) .. parsed-literal:: ScheduleBlock( ScheduleBlock( Play( Gaussian(duration=160, amp=(0.1+0j), sigma=40), DriveChannel(0) ), name="block0", transform=AlignLeft() ), name="block1", transform=AlignLeft() ) The actual program is stored in the reference table attached to the schedule. .. code-block:: print(pulse_prog.references) .. parsed-literal:: ReferenceManager: - ('block0', '634b3b50bd684e26a673af1fbd2d6c81'): ScheduleBlock(Play(Gaussian(... In addition, you can call a parameterized target program with parameter assignment. .. code-block:: amp = circuit.Parameter("amp") with pulse.build() as subroutine: pulse.play(pulse.Gaussian(160, amp, 40), pulse.DriveChannel(0)) with pulse.build() as pulse_prog: pulse.call(subroutine, amp=0.1) pulse.call(subroutine, amp=0.3) print(pulse_prog) .. parsed-literal:: ScheduleBlock( ScheduleBlock( Play( Gaussian(duration=160, amp=(0.1+0j), sigma=40), DriveChannel(0) ), name="block2", transform=AlignLeft() ), ScheduleBlock( Play( Gaussian(duration=160, amp=(0.3+0j), sigma=40), DriveChannel(0) ), name="block2", transform=AlignLeft() ), name="block3", transform=AlignLeft() ) If there is a name collision between parameters, you can distinguish them by specifying each parameter object in a python dictionary. For example, .. code-block:: amp1 = circuit.Parameter('amp') amp2 = circuit.Parameter('amp') with pulse.build() as subroutine: pulse.play(pulse.Gaussian(160, amp1, 40), pulse.DriveChannel(0)) pulse.play(pulse.Gaussian(160, amp2, 40), pulse.DriveChannel(1)) with pulse.build() as pulse_prog: pulse.call(subroutine, value_dict={amp1: 0.1, amp2: 0.3}) print(pulse_prog) .. parsed-literal:: ScheduleBlock( ScheduleBlock( Play(Gaussian(duration=160, amp=(0.1+0j), sigma=40), DriveChannel(0)), Play(Gaussian(duration=160, amp=(0.3+0j), sigma=40), DriveChannel(1)), name="block4", transform=AlignLeft() ), name="block5", transform=AlignLeft() ) 2. Calling a schedule .. code-block:: x_sched = backend.instruction_schedule_map.get("x", (0,)) with pulse.build(backend) as pulse_prog: pulse.call(x_sched) print(pulse_prog) .. parsed-literal:: ScheduleBlock( Call( Schedule( ( 0, Play( Drag( duration=160, amp=(0.18989731546729305+0j), sigma=40, beta=-1.201258305015517, name='drag_86a8' ), DriveChannel(0), name='drag_86a8' ) ), name="x" ), name='x' ), name="block6", transform=AlignLeft() ) Currently, the backend calibrated gates are provided in the form of :class:`~.Schedule`. The parameter assignment mechanism is available also for schedules. However, the called schedule is not treated as a reference. 3. Calling a quantum circuit .. code-block:: backend = FakeBogotaV2() qc = circuit.QuantumCircuit(1) qc.x(0) with pulse.build(backend) as pulse_prog: pulse.call(qc) print(pulse_prog) .. parsed-literal:: ScheduleBlock( Call( Schedule( ( 0, Play( Drag( duration=160, amp=(0.18989731546729305+0j), sigma=40, beta=-1.201258305015517, name='drag_86a8' ), DriveChannel(0), name='drag_86a8' ) ), name="circuit-87" ), name='circuit-87' ), name="block7", transform=AlignLeft() ) .. warning:: Calling a circuit from a schedule is not encouraged. Currently, the Qiskit execution model is migrating toward the pulse gate model, where schedules are attached to circuits through the :meth:`.QuantumCircuit.add_calibration` method. Args: target: Target circuit or pulse schedule to call. name: Optional. A unique name of subroutine if defined. When the name is explicitly provided, one cannot call different schedule blocks with the same name. value_dict: Optional. Parameters assigned to the ``target`` program. If this dictionary is provided, the ``target`` program is copied and then stored in the main built schedule and its parameters are assigned to the given values. This dictionary is keyed on :class:`~.Parameter` objects, allowing parameter name collision to be avoided. kw_params: Alternative way to provide parameters. Since this is keyed on the string parameter name, the parameters having the same name are all updated together. If you want to avoid name collision, use ``value_dict`` with :class:`~.Parameter` objects instead. """ _active_builder().call_subroutine(target, name, value_dict, **kw_params) def reference(name: str, *extra_keys: str): """Refer to undefined subroutine by string keys. A :class:`~qiskit.pulse.instructions.Reference` instruction is implicitly created and a schedule can be separately registered to the reference at a later stage. .. code-block:: python from qiskit import pulse with pulse.build() as main_prog: pulse.reference("x_gate", "q0") with pulse.build() as subroutine: pulse.play(pulse.Gaussian(160, 0.1, 40), pulse.DriveChannel(0)) main_prog.assign_references(subroutine_dict={("x_gate", "q0"): subroutine}) Args: name: Name of subroutine. extra_keys: Helper keys to uniquely specify the subroutine. """ _active_builder().append_reference(name, *extra_keys) # Directives def barrier(*channels_or_qubits: Union[chans.Channel, int], name: Optional[str] = None): """Barrier directive for a set of channels and qubits. This directive prevents the compiler from moving instructions across the barrier. Consider the case where we want to enforce that one pulse happens after another on separate channels, this can be done with: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) with pulse.build(backend) as barrier_pulse_prog: pulse.play(pulse.Constant(10, 1.0), d0) pulse.barrier(d0, d1) pulse.play(pulse.Constant(10, 1.0), d1) Of course this could have been accomplished with: .. code-block:: from qiskit.pulse import transforms with pulse.build(backend) as aligned_pulse_prog: with pulse.align_sequential(): pulse.play(pulse.Constant(10, 1.0), d0) pulse.play(pulse.Constant(10, 1.0), d1) barrier_pulse_prog = transforms.target_qobj_transform(barrier_pulse_prog) aligned_pulse_prog = transforms.target_qobj_transform(aligned_pulse_prog) assert barrier_pulse_prog == aligned_pulse_prog The barrier allows the pulse compiler to take care of more advanced scheduling alignment operations across channels. For example in the case where we are calling an outside circuit or schedule and want to align a pulse at the end of one call: .. code-block:: import math d0 = pulse.DriveChannel(0) with pulse.build(backend) as pulse_prog: with pulse.align_right(): pulse.x(1) # Barrier qubit 1 and d0. pulse.barrier(1, d0) # Due to barrier this will play before the gate on qubit 1. pulse.play(pulse.Constant(10, 1.0), d0) # This will end at the same time as the pulse above due to # the barrier. pulse.x(1) .. note:: Requires the active builder context to have a backend set if qubits are barriered on. Args: channels_or_qubits: Channels or qubits to barrier. name: Name for the barrier """ channels = _qubits_to_channels(*channels_or_qubits) if len(channels) > 1: append_instruction(directives.RelativeBarrier(*channels, name=name)) # Macros def macro(func: Callable): """Wrap a Python function and activate the parent builder context at calling time. This enables embedding Python functions as builder macros. This generates a new :class:`pulse.Schedule` that is embedded in the parent builder context with every call of the decorated macro function. The decorated macro function will behave as if the function code was embedded inline in the parent builder context after parameter substitution. Examples: .. plot:: :include-source: from qiskit import pulse @pulse.macro def measure(qubit: int): pulse.play(pulse.GaussianSquare(16384, 256, 15872), pulse.measure_channel(qubit)) mem_slot = pulse.MemorySlot(qubit) pulse.acquire(16384, pulse.acquire_channel(qubit), mem_slot) return mem_slot with pulse.build(backend=backend) as sched: mem_slot = measure(0) print(f"Qubit measured into {mem_slot}") sched.draw() Args: func: The Python function to enable as a builder macro. There are no requirements on the signature of the function, any calls to pulse builder methods will be added to builder context the wrapped function is called from. Returns: Callable: The wrapped ``func``. """ func_name = getattr(func, "__name__", repr(func)) @functools.wraps(func) def wrapper(*args, **kwargs): _builder = _active_builder() # activate the pulse builder before calling the function with build(backend=_builder.backend, name=func_name) as built: output = func(*args, **kwargs) _builder.call_subroutine(built) return output return wrapper def measure( qubits: Union[List[int], int], registers: Union[List[StorageLocation], StorageLocation] = None, ) -> Union[List[StorageLocation], StorageLocation]: """Measure a qubit within the currently active builder context. At the pulse level a measurement is composed of both a stimulus pulse and an acquisition instruction which tells the systems measurement unit to acquire data and process it. We provide this measurement macro to automate the process for you, but if desired full control is still available with :func:`acquire` and :func:`play`. To use the measurement it is as simple as specifying the qubit you wish to measure: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() qubit = 0 with pulse.build(backend) as pulse_prog: # Do something to the qubit. qubit_drive_chan = pulse.drive_channel(0) pulse.play(pulse.Constant(100, 1.0), qubit_drive_chan) # Measure the qubit. reg = pulse.measure(qubit) For now it is not possible to do much with the handle to ``reg`` but in the future we will support using this handle to a result register to build up ones program. It is also possible to supply this register: .. code-block:: with pulse.build(backend) as pulse_prog: pulse.play(pulse.Constant(100, 1.0), qubit_drive_chan) # Measure the qubit. mem0 = pulse.MemorySlot(0) reg = pulse.measure(qubit, mem0) assert reg == mem0 .. note:: Requires the active builder context to have a backend set. Args: qubits: Physical qubit to measure. registers: Register to store result in. If not selected the current behavior is to return the :class:`MemorySlot` with the same index as ``qubit``. This register will be returned. Returns: The ``register`` the qubit measurement result will be stored in. """ backend = active_backend() try: qubits = list(qubits) except TypeError: qubits = [qubits] if registers is None: registers = [chans.MemorySlot(qubit) for qubit in qubits] else: try: registers = list(registers) except TypeError: registers = [registers] measure_sched = macros.measure( qubits=qubits, backend=backend, qubit_mem_slots={qubit: register.index for qubit, register in zip(qubits, registers)}, ) # note this is not a subroutine. # just a macro to automate combination of stimulus and acquisition. # prepare unique reference name based on qubit and memory slot index. qubits_repr = "&".join(map(str, qubits)) mslots_repr = "&".join((str(r.index) for r in registers)) _active_builder().call_subroutine(measure_sched, name=f"measure_{qubits_repr}..{mslots_repr}") if len(qubits) == 1: return registers[0] else: return registers def measure_all() -> List[chans.MemorySlot]: r"""Measure all qubits within the currently active builder context. A simple macro function to measure all of the qubits in the device at the same time. This is useful for handling device ``meas_map`` and single measurement constraints. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend) as pulse_prog: # Measure all qubits and return associated registers. regs = pulse.measure_all() .. note:: Requires the active builder context to have a backend set. Returns: The ``register``\s the qubit measurement results will be stored in. """ backend = active_backend() qubits = range(num_qubits()) registers = [chans.MemorySlot(qubit) for qubit in qubits] measure_sched = macros.measure( qubits=qubits, backend=backend, qubit_mem_slots={qubit: qubit for qubit in qubits}, ) # note this is not a subroutine. # just a macro to automate combination of stimulus and acquisition. _active_builder().call_subroutine(measure_sched, name="measure_all") return registers def delay_qubits(duration: int, *qubits: Union[int, Iterable[int]]): r"""Insert delays on all of the :class:`channels.Channel`\s that correspond to the input ``qubits`` at the same time. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse3Q backend = FakeOpenPulse3Q() with pulse.build(backend) as pulse_prog: # Delay for 100 cycles on qubits 0, 1 and 2. regs = pulse.delay_qubits(100, 0, 1, 2) .. note:: Requires the active builder context to have a backend set. Args: duration: Duration to delay for. qubits: Physical qubits to delay on. Delays will be inserted based on the channels returned by :func:`pulse.qubit_channels`. """ qubit_chans = set(itertools.chain.from_iterable(qubit_channels(qubit) for qubit in qubits)) with align_left(): for chan in qubit_chans: delay(duration, chan) # Gate instructions def call_gate(gate: circuit.Gate, qubits: Tuple[int, ...], lazy: bool = True): """Call a gate and lazily schedule it to its corresponding pulse instruction. .. note:: Calling gates directly within the pulse builder namespace will be deprecated in the future in favor of tight integration with a circuit builder interface which is under development. Examples: .. code-block:: from qiskit import pulse from qiskit.pulse import builder from qiskit.circuit.library import standard_gates as gates from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend) as pulse_prog: builder.call_gate(gates.CXGate(), (0, 1)) We can see the role of the transpiler in scheduling gates by optimizing away two consecutive CNOT gates: .. code-block:: with pulse.build(backend) as pulse_prog: with pulse.transpiler_settings(optimization_level=3): builder.call_gate(gates.CXGate(), (0, 1)) builder.call_gate(gates.CXGate(), (0, 1)) assert pulse_prog == pulse.Schedule() .. note:: If multiple gates are called in a row they may be optimized by the transpiler, depending on the :func:`pulse.active_transpiler_settings``. .. note:: Requires the active builder context to have a backend set. Args: gate: Circuit gate instance to call. qubits: Qubits to call gate on. lazy: If ``false`` the gate will be compiled immediately, otherwise it will be added onto a lazily evaluated quantum circuit to be compiled when the builder is forced to by a circuit assumption being broken, such as the inclusion of a pulse instruction or new alignment context. """ _active_builder().call_gate(gate, qubits, lazy=lazy) def cx(control: int, target: int): # pylint: disable=invalid-name """Call a :class:`~qiskit.circuit.library.standard_gates.CXGate` on the input physical qubits. .. note:: Calling gates directly within the pulse builder namespace will be deprecated in the future in favor of tight integration with a circuit builder interface which is under development. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend) as pulse_prog: pulse.cx(0, 1) """ call_gate(gates.CXGate(), (control, target)) def u1(theta: float, qubit: int): # pylint: disable=invalid-name """Call a :class:`~qiskit.circuit.library.standard_gates.U1Gate` on the input physical qubit. .. note:: Calling gates directly within the pulse builder namespace will be deprecated in the future in favor of tight integration with a circuit builder interface which is under development. Examples: .. code-block:: import math from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend) as pulse_prog: pulse.u1(math.pi, 1) """ call_gate(gates.U1Gate(theta), qubit) def u2(phi: float, lam: float, qubit: int): # pylint: disable=invalid-name """Call a :class:`~qiskit.circuit.library.standard_gates.U2Gate` on the input physical qubit. .. note:: Calling gates directly within the pulse builder namespace will be deprecated in the future in favor of tight integration with a circuit builder interface which is under development. Examples: .. code-block:: import math from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend) as pulse_prog: pulse.u2(0, math.pi, 1) """ call_gate(gates.U2Gate(phi, lam), qubit) def u3(theta: float, phi: float, lam: float, qubit: int): # pylint: disable=invalid-name """Call a :class:`~qiskit.circuit.library.standard_gates.U3Gate` on the input physical qubit. .. note:: Calling gates directly within the pulse builder namespace will be deprecated in the future in favor of tight integration with a circuit builder interface which is under development. Examples: .. code-block:: import math from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend) as pulse_prog: pulse.u3(math.pi, 0, math.pi, 1) """ call_gate(gates.U3Gate(theta, phi, lam), qubit) def x(qubit: int): """Call a :class:`~qiskit.circuit.library.standard_gates.XGate` on the input physical qubit. .. note:: Calling gates directly within the pulse builder namespace will be deprecated in the future in favor of tight integration with a circuit builder interface which is under development. Examples: .. code-block:: from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse2Q backend = FakeOpenPulse2Q() with pulse.build(backend) as pulse_prog: pulse.x(0) """ call_gate(gates.XGate(), qubit)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# 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=cyclic-import """ ========= Schedules ========= .. currentmodule:: qiskit.pulse Schedules are Pulse programs. They describe instruction sequences for the control hardware. The Schedule is one of the most fundamental objects to this pulse-level programming module. A ``Schedule`` is a representation of a *program* in Pulse. Each schedule tracks the time of each instruction occuring in parallel over multiple signal *channels*. .. autosummary:: :toctree: ../stubs/ Schedule ScheduleBlock """ import abc import copy import functools import itertools import multiprocessing as mp import re import sys import warnings from typing import List, Tuple, Iterable, Union, Dict, Callable, Set, Optional, Any import numpy as np import rustworkx as rx from qiskit.circuit.parameter import Parameter from qiskit.circuit.parameterexpression import ParameterExpression, ParameterValueType from qiskit.pulse.channels import Channel from qiskit.pulse.exceptions import PulseError, UnassignedReferenceError from qiskit.pulse.instructions import Instruction, Reference from qiskit.pulse.utils import instruction_duration_validation from qiskit.pulse.reference_manager import ReferenceManager from qiskit.utils.multiprocessing import is_main_process Interval = Tuple[int, int] """An interval type is a tuple of a start time (inclusive) and an end time (exclusive).""" TimeSlots = Dict[Channel, List[Interval]] """List of timeslots occupied by instructions for each channel.""" class Schedule: """A quantum program *schedule* with exact time constraints for its instructions, operating over all input signal *channels* and supporting special syntaxes for building. Pulse program representation for the original Qiskit Pulse model [1]. Instructions are not allowed to overlap in time on the same channel. This overlap constraint is immediately evaluated when a new instruction is added to the ``Schedule`` object. It is necessary to specify the absolute start time and duration for each instruction so as to deterministically fix its execution time. The ``Schedule`` program supports some syntax sugar for easier programming. - Appending an instruction to the end of a channel .. code-block:: python sched = Schedule() sched += Play(Gaussian(160, 0.1, 40), DriveChannel(0)) - Appending an instruction shifted in time by a given amount .. code-block:: python sched = Schedule() sched += Play(Gaussian(160, 0.1, 40), DriveChannel(0)) << 30 - Merge two schedules .. code-block:: python sched1 = Schedule() sched1 += Play(Gaussian(160, 0.1, 40), DriveChannel(0)) sched2 = Schedule() sched2 += Play(Gaussian(160, 0.1, 40), DriveChannel(1)) sched2 = sched1 | sched2 A :obj:`.PulseError` is immediately raised when the overlap constraint is violated. In the schedule representation, we cannot parametrize the duration of instructions. Thus we need to create a new schedule object for each duration. To parametrize an instruction's duration, the :class:`~qiskit.pulse.ScheduleBlock` representation may be used instead. References: [1]: https://arxiv.org/abs/2004.06755 """ # Prefix to use for auto naming. prefix = "sched" # Counter to count instance number. instances_counter = itertools.count() def __init__( self, *schedules: Union["ScheduleComponent", Tuple[int, "ScheduleComponent"]], name: Optional[str] = None, metadata: Optional[dict] = None, ): """Create an empty schedule. Args: *schedules: Child Schedules of this parent Schedule. May either be passed as the list of schedules, or a list of ``(start_time, schedule)`` pairs. name: Name of this schedule. Defaults to an autogenerated string if not provided. metadata: Arbitrary key value metadata to associate with the schedule. This gets stored as free-form data in a dict in the :attr:`~qiskit.pulse.Schedule.metadata` attribute. It will not be directly used in the schedule. Raises: TypeError: if metadata is not a dict. """ from qiskit.pulse.parameter_manager import ParameterManager if name is None: name = self.prefix + str(next(self.instances_counter)) if sys.platform != "win32" and not is_main_process(): name += f"-{mp.current_process().pid}" self._name = name self._parameter_manager = ParameterManager() if not isinstance(metadata, dict) and metadata is not None: raise TypeError("Only a dictionary or None is accepted for schedule metadata") self._metadata = metadata or {} self._duration = 0 # These attributes are populated by ``_mutable_insert`` self._timeslots = {} self._children = [] for sched_pair in schedules: try: time, sched = sched_pair except TypeError: # recreate as sequence starting at 0. time, sched = 0, sched_pair self._mutable_insert(time, sched) @classmethod def initialize_from(cls, other_program: Any, name: Optional[str] = None) -> "Schedule": """Create new schedule object with metadata of another schedule object. Args: other_program: Qiskit program that provides metadata to new object. name: Name of new schedule. Name of ``schedule`` is used by default. Returns: New schedule object with name and metadata. Raises: PulseError: When `other_program` does not provide necessary information. """ try: name = name or other_program.name if other_program.metadata: metadata = other_program.metadata.copy() else: metadata = None return cls(name=name, metadata=metadata) except AttributeError as ex: raise PulseError( f"{cls.__name__} cannot be initialized from the program data " f"{other_program.__class__.__name__}." ) from ex @property def name(self) -> str: """Name of this Schedule""" return self._name @property def metadata(self) -> Dict[str, Any]: """The user provided metadata associated with the schedule. User provided ``dict`` of metadata for the schedule. The metadata contents do not affect the semantics of the program but are used to influence the execution of the schedule. It is expected to be passed between all transforms of the schedule and that providers will associate any schedule metadata with the results it returns from the execution of that schedule. """ return self._metadata @metadata.setter def metadata(self, metadata): """Update the schedule metadata""" if not isinstance(metadata, dict) and metadata is not None: raise TypeError("Only a dictionary or None is accepted for schedule metadata") self._metadata = metadata or {} @property def timeslots(self) -> TimeSlots: """Time keeping attribute.""" return self._timeslots @property def duration(self) -> int: """Duration of this schedule.""" return self._duration @property def start_time(self) -> int: """Starting time of this schedule.""" return self.ch_start_time(*self.channels) @property def stop_time(self) -> int: """Stopping time of this schedule.""" return self.duration @property def channels(self) -> Tuple[Channel]: """Returns channels that this schedule uses.""" return tuple(self._timeslots.keys()) @property def children(self) -> Tuple[Tuple[int, "ScheduleComponent"], ...]: """Return the child schedule components of this ``Schedule`` in the order they were added to the schedule. Notes: Nested schedules are returned as-is. If you want to collect only instructions, use py:meth:`~Schedule.instructions` instead. Returns: A tuple, where each element is a two-tuple containing the initial scheduled time of each ``NamedValue`` and the component itself. """ return tuple(self._children) @property def instructions(self) -> Tuple[Tuple[int, Instruction]]: """Get the time-ordered instructions from self.""" def key(time_inst_pair): inst = time_inst_pair[1] return time_inst_pair[0], inst.duration, sorted(chan.name for chan in inst.channels) return tuple(sorted(self._instructions(), key=key)) @property def parameters(self) -> Set: """Parameters which determine the schedule behavior.""" return self._parameter_manager.parameters def ch_duration(self, *channels: Channel) -> int: """Return the time of the end of the last instruction over the supplied channels. Args: *channels: Channels within ``self`` to include. """ return self.ch_stop_time(*channels) def ch_start_time(self, *channels: Channel) -> int: """Return the time of the start of the first instruction over the supplied channels. Args: *channels: Channels within ``self`` to include. """ try: chan_intervals = (self._timeslots[chan] for chan in channels if chan in self._timeslots) return min(intervals[0][0] for intervals in chan_intervals) except ValueError: # If there are no instructions over channels return 0 def ch_stop_time(self, *channels: Channel) -> int: """Return maximum start time over supplied channels. Args: *channels: Channels within ``self`` to include. """ try: chan_intervals = (self._timeslots[chan] for chan in channels if chan in self._timeslots) return max(intervals[-1][1] for intervals in chan_intervals) except ValueError: # If there are no instructions over channels return 0 def _instructions(self, time: int = 0): """Iterable for flattening Schedule tree. Args: time: Shifted time due to parent. Yields: Iterable[Tuple[int, Instruction]]: Tuple containing the time each :class:`~qiskit.pulse.Instruction` starts at and the flattened :class:`~qiskit.pulse.Instruction` s. """ for insert_time, child_sched in self.children: yield from child_sched._instructions(time + insert_time) def shift(self, time: int, name: Optional[str] = None, inplace: bool = False) -> "Schedule": """Return a schedule shifted forward by ``time``. Args: time: Time to shift by. name: Name of the new schedule. Defaults to the name of self. inplace: Perform operation inplace on this schedule. Otherwise return a new ``Schedule``. """ if inplace: return self._mutable_shift(time) return self._immutable_shift(time, name=name) def _immutable_shift(self, time: int, name: Optional[str] = None) -> "Schedule": """Return a new schedule shifted forward by `time`. Args: time: Time to shift by name: Name of the new schedule if call was mutable. Defaults to name of self """ shift_sched = Schedule.initialize_from(self, name) shift_sched.insert(time, self, inplace=True) return shift_sched def _mutable_shift(self, time: int) -> "Schedule": """Return this schedule shifted forward by `time`. Args: time: Time to shift by Raises: PulseError: if ``time`` is not an integer. """ if not isinstance(time, int): raise PulseError("Schedule start time must be an integer.") timeslots = {} for chan, ch_timeslots in self._timeslots.items(): timeslots[chan] = [(ts[0] + time, ts[1] + time) for ts in ch_timeslots] _check_nonnegative_timeslot(timeslots) self._duration = self._duration + time self._timeslots = timeslots self._children = [(orig_time + time, child) for orig_time, child in self.children] return self def insert( self, start_time: int, schedule: "ScheduleComponent", name: Optional[str] = None, inplace: bool = False, ) -> "Schedule": """Return a new schedule with ``schedule`` inserted into ``self`` at ``start_time``. Args: start_time: Time to insert the schedule. schedule: Schedule to insert. name: Name of the new schedule. Defaults to the name of self. inplace: Perform operation inplace on this schedule. Otherwise return a new ``Schedule``. """ if inplace: return self._mutable_insert(start_time, schedule) return self._immutable_insert(start_time, schedule, name=name) def _mutable_insert(self, start_time: int, schedule: "ScheduleComponent") -> "Schedule": """Mutably insert `schedule` into `self` at `start_time`. Args: start_time: Time to insert the second schedule. schedule: Schedule to mutably insert. """ self._add_timeslots(start_time, schedule) self._children.append((start_time, schedule)) self._parameter_manager.update_parameter_table(schedule) return self def _immutable_insert( self, start_time: int, schedule: "ScheduleComponent", name: Optional[str] = None, ) -> "Schedule": """Return a new schedule with ``schedule`` inserted into ``self`` at ``start_time``. Args: start_time: Time to insert the schedule. schedule: Schedule to insert. name: Name of the new ``Schedule``. Defaults to name of ``self``. """ new_sched = Schedule.initialize_from(self, name) new_sched._mutable_insert(0, self) new_sched._mutable_insert(start_time, schedule) return new_sched def append( self, schedule: "ScheduleComponent", name: Optional[str] = None, inplace: bool = False ) -> "Schedule": r"""Return a new schedule with ``schedule`` inserted at the maximum time over all channels shared between ``self`` and ``schedule``. .. math:: t = \textrm{max}(\texttt{x.stop_time} |\texttt{x} \in \texttt{self.channels} \cap \texttt{schedule.channels}) Args: schedule: Schedule to be appended. name: Name of the new ``Schedule``. Defaults to name of ``self``. inplace: Perform operation inplace on this schedule. Otherwise return a new ``Schedule``. """ common_channels = set(self.channels) & set(schedule.channels) time = self.ch_stop_time(*common_channels) return self.insert(time, schedule, name=name, inplace=inplace) def filter( self, *filter_funcs: Callable, channels: Optional[Iterable[Channel]] = None, instruction_types: Union[Iterable[abc.ABCMeta], abc.ABCMeta] = None, time_ranges: Optional[Iterable[Tuple[int, int]]] = None, intervals: Optional[Iterable[Interval]] = None, check_subroutine: bool = True, ) -> "Schedule": """Return a new ``Schedule`` with only the instructions from this ``Schedule`` which pass though the provided filters; i.e. an instruction will be retained iff every function in ``filter_funcs`` returns ``True``, the instruction occurs on a channel type contained in ``channels``, the instruction type is contained in ``instruction_types``, and the period over which the instruction operates is *fully* contained in one specified in ``time_ranges`` or ``intervals``. If no arguments are provided, ``self`` is returned. Args: filter_funcs: A list of Callables which take a (int, Union['Schedule', Instruction]) tuple and return a bool. channels: For example, ``[DriveChannel(0), AcquireChannel(0)]``. instruction_types: For example, ``[PulseInstruction, AcquireInstruction]``. time_ranges: For example, ``[(0, 5), (6, 10)]``. intervals: For example, ``[(0, 5), (6, 10)]``. check_subroutine: Set `True` to individually filter instructions inside of a subroutine defined by the :py:class:`~qiskit.pulse.instructions.Call` instruction. """ from qiskit.pulse.filters import composite_filter, filter_instructions filters = composite_filter(channels, instruction_types, time_ranges, intervals) filters.extend(filter_funcs) return filter_instructions( self, filters=filters, negate=False, recurse_subroutines=check_subroutine ) def exclude( self, *filter_funcs: Callable, channels: Optional[Iterable[Channel]] = None, instruction_types: Union[Iterable[abc.ABCMeta], abc.ABCMeta] = None, time_ranges: Optional[Iterable[Tuple[int, int]]] = None, intervals: Optional[Iterable[Interval]] = None, check_subroutine: bool = True, ) -> "Schedule": """Return a ``Schedule`` with only the instructions from this Schedule *failing* at least one of the provided filters. This method is the complement of py:meth:`~self.filter`, so that:: self.filter(args) | self.exclude(args) == self Args: filter_funcs: A list of Callables which take a (int, Union['Schedule', Instruction]) tuple and return a bool. channels: For example, ``[DriveChannel(0), AcquireChannel(0)]``. instruction_types: For example, ``[PulseInstruction, AcquireInstruction]``. time_ranges: For example, ``[(0, 5), (6, 10)]``. intervals: For example, ``[(0, 5), (6, 10)]``. check_subroutine: Set `True` to individually filter instructions inside of a subroutine defined by the :py:class:`~qiskit.pulse.instructions.Call` instruction. """ from qiskit.pulse.filters import composite_filter, filter_instructions filters = composite_filter(channels, instruction_types, time_ranges, intervals) filters.extend(filter_funcs) return filter_instructions( self, filters=filters, negate=True, recurse_subroutines=check_subroutine ) def _add_timeslots(self, time: int, schedule: "ScheduleComponent") -> None: """Update all time tracking within this schedule based on the given schedule. Args: time: The time to insert the schedule into self. schedule: The schedule to insert into self. Raises: PulseError: If timeslots overlap or an invalid start time is provided. """ if not np.issubdtype(type(time), np.integer): raise PulseError("Schedule start time must be an integer.") other_timeslots = _get_timeslots(schedule) self._duration = max(self._duration, time + schedule.duration) for channel in schedule.channels: if channel not in self._timeslots: if time == 0: self._timeslots[channel] = copy.copy(other_timeslots[channel]) else: self._timeslots[channel] = [ (i[0] + time, i[1] + time) for i in other_timeslots[channel] ] continue for idx, interval in enumerate(other_timeslots[channel]): if interval[0] + time >= self._timeslots[channel][-1][1]: # Can append the remaining intervals self._timeslots[channel].extend( [(i[0] + time, i[1] + time) for i in other_timeslots[channel][idx:]] ) break try: interval = (interval[0] + time, interval[1] + time) index = _find_insertion_index(self._timeslots[channel], interval) self._timeslots[channel].insert(index, interval) except PulseError as ex: raise PulseError( "Schedule(name='{new}') cannot be inserted into Schedule(name='{old}') at " "time {time} because its instruction on channel {ch} scheduled from time " "{t0} to {tf} overlaps with an existing instruction." "".format( new=schedule.name or "", old=self.name or "", time=time, ch=channel, t0=interval[0], tf=interval[1], ) ) from ex _check_nonnegative_timeslot(self._timeslots) def _remove_timeslots(self, time: int, schedule: "ScheduleComponent"): """Delete the timeslots if present for the respective schedule component. Args: time: The time to remove the timeslots for the ``schedule`` component. schedule: The schedule to insert into self. Raises: PulseError: If timeslots overlap or an invalid start time is provided. """ if not isinstance(time, int): raise PulseError("Schedule start time must be an integer.") for channel in schedule.channels: if channel not in self._timeslots: raise PulseError(f"The channel {channel} is not present in the schedule") channel_timeslots = self._timeslots[channel] other_timeslots = _get_timeslots(schedule) for interval in other_timeslots[channel]: if channel_timeslots: interval = (interval[0] + time, interval[1] + time) index = _interval_index(channel_timeslots, interval) if channel_timeslots[index] == interval: channel_timeslots.pop(index) continue raise PulseError( "Cannot find interval ({t0}, {tf}) to remove from " "channel {ch} in Schedule(name='{name}').".format( ch=channel, t0=interval[0], tf=interval[1], name=schedule.name ) ) if not channel_timeslots: self._timeslots.pop(channel) def _replace_timeslots(self, time: int, old: "ScheduleComponent", new: "ScheduleComponent"): """Replace the timeslots of ``old`` if present with the timeslots of ``new``. Args: time: The time to remove the timeslots for the ``schedule`` component. old: Instruction to replace. new: Instruction to replace with. """ self._remove_timeslots(time, old) self._add_timeslots(time, new) def _renew_timeslots(self): """Regenerate timeslots based on current instructions.""" self._timeslots.clear() for t0, inst in self.instructions: self._add_timeslots(t0, inst) def replace( self, old: "ScheduleComponent", new: "ScheduleComponent", inplace: bool = False, ) -> "Schedule": """Return a ``Schedule`` with the ``old`` instruction replaced with a ``new`` instruction. The replacement matching is based on an instruction equality check. .. code-block:: from qiskit import pulse d0 = pulse.DriveChannel(0) sched = pulse.Schedule() old = pulse.Play(pulse.Constant(100, 1.0), d0) new = pulse.Play(pulse.Constant(100, 0.1), d0) sched += old sched = sched.replace(old, new) assert sched == pulse.Schedule(new) Only matches at the top-level of the schedule tree. If you wish to perform this replacement over all instructions in the schedule tree. Flatten the schedule prior to running:: .. code-block:: sched = pulse.Schedule() sched += pulse.Schedule(old) sched = sched.flatten() sched = sched.replace(old, new) assert sched == pulse.Schedule(new) Args: old: Instruction to replace. new: Instruction to replace with. inplace: Replace instruction by mutably modifying this ``Schedule``. Returns: The modified schedule with ``old`` replaced by ``new``. Raises: PulseError: If the ``Schedule`` after replacements will has a timing overlap. """ from qiskit.pulse.parameter_manager import ParameterManager new_children = [] new_parameters = ParameterManager() for time, child in self.children: if child == old: new_children.append((time, new)) new_parameters.update_parameter_table(new) else: new_children.append((time, child)) new_parameters.update_parameter_table(child) if inplace: self._children = new_children self._parameter_manager = new_parameters self._renew_timeslots() return self else: try: new_sched = Schedule.initialize_from(self) for time, inst in new_children: new_sched.insert(time, inst, inplace=True) return new_sched except PulseError as err: raise PulseError( f"Replacement of {old} with {new} results in overlapping instructions." ) from err def is_parameterized(self) -> bool: """Return True iff the instruction is parameterized.""" return self._parameter_manager.is_parameterized() def assign_parameters( self, value_dict: Dict[ParameterExpression, ParameterValueType], inplace: bool = True ) -> "Schedule": """Assign the parameters in this schedule according to the input. Args: value_dict: A mapping from Parameters to either numeric values or another Parameter expression. inplace: Set ``True`` to override this instance with new parameter. Returns: Schedule with updated parameters. """ if not inplace: new_schedule = copy.deepcopy(self) return new_schedule.assign_parameters(value_dict, inplace=True) return self._parameter_manager.assign_parameters(pulse_program=self, value_dict=value_dict) def get_parameters(self, parameter_name: str) -> List[Parameter]: """Get parameter object bound to this schedule by string name. Because different ``Parameter`` objects can have the same name, this method returns a list of ``Parameter`` s for the provided name. Args: parameter_name: Name of parameter. Returns: Parameter objects that have corresponding name. """ return self._parameter_manager.get_parameters(parameter_name) def __len__(self) -> int: """Return number of instructions in the schedule.""" return len(self.instructions) def __add__(self, other: "ScheduleComponent") -> "Schedule": """Return a new schedule with ``other`` inserted within ``self`` at ``start_time``.""" return self.append(other) def __or__(self, other: "ScheduleComponent") -> "Schedule": """Return a new schedule which is the union of `self` and `other`.""" return self.insert(0, other) def __lshift__(self, time: int) -> "Schedule": """Return a new schedule which is shifted forward by ``time``.""" return self.shift(time) def __eq__(self, other: "ScheduleComponent") -> bool: """Test if two Schedule are equal. Equality is checked by verifying there is an equal instruction at every time in ``other`` for every instruction in this ``Schedule``. .. warning:: This does not check for logical equivalency. Ie., ```python >>> Delay(10, DriveChannel(0)) + Delay(10, DriveChannel(0)) == Delay(20, DriveChannel(0)) False ``` """ # 0. type check, we consider Instruction is a subtype of schedule if not isinstance(other, (type(self), Instruction)): return False # 1. channel check if set(self.channels) != set(other.channels): return False # 2. size check if len(self.instructions) != len(other.instructions): return False # 3. instruction check return all( self_inst == other_inst for self_inst, other_inst in zip(self.instructions, other.instructions) ) def __repr__(self) -> str: name = format(self._name) if self._name else "" instructions = ", ".join([repr(instr) for instr in self.instructions[:50]]) if len(self.instructions) > 25: instructions += ", ..." return f'{self.__class__.__name__}({instructions}, name="{name}")' def _require_schedule_conversion(function: Callable) -> Callable: """A method decorator to convert schedule block to pulse schedule. This conversation is performed for backward compatibility only if all durations are assigned. """ @functools.wraps(function) def wrapper(self, *args, **kwargs): from qiskit.pulse.transforms import block_to_schedule return function(block_to_schedule(self), *args, **kwargs) return wrapper class ScheduleBlock: """Time-ordered sequence of instructions with alignment context. :class:`.ScheduleBlock` supports lazy scheduling of context instructions, i.e. their timeslots is always generated at runtime. This indicates we can parametrize instruction durations as well as other parameters. In contrast to :class:`.Schedule` being somewhat static, :class:`.ScheduleBlock` is a dynamic representation of a pulse program. .. rubric:: Pulse Builder The Qiskit pulse builder is a domain specific language that is developed on top of the schedule block. Use of the builder syntax will improve the workflow of pulse programming. See :ref:`pulse_builder` for a user guide. .. rubric:: Alignment contexts A schedule block is always relatively scheduled. Instead of taking individual instructions with absolute execution time ``t0``, the schedule block defines a context of scheduling and instructions under the same context are scheduled in the same manner (alignment). Several contexts are available in :ref:`pulse_alignments`. A schedule block is instantiated with one of these alignment contexts. The default context is :class:`AlignLeft`, for which all instructions are left-justified, in other words, meaning they use as-soon-as-possible scheduling. If you need an absolute-time interval in between instructions, you can explicitly insert :class:`~qiskit.pulse.instructions.Delay` instructions. .. rubric:: Nested blocks A schedule block can contain other nested blocks with different alignment contexts. This enables advanced scheduling, where a subset of instructions is locally scheduled in a different manner. Note that a :class:`.Schedule` instance cannot be directly added to a schedule block. To add a :class:`.Schedule` instance, wrap it in a :class:`.Call` instruction. This is implicitly performed when a schedule is added through the :ref:`pulse_builder`. .. rubric:: Unsupported operations Because the schedule block representation lacks timeslots, it cannot perform particular :class:`.Schedule` operations such as :meth:`insert` or :meth:`shift` that require instruction start time ``t0``. In addition, :meth:`exclude` and :meth:`filter` methods are not supported because these operations may identify the target instruction with ``t0``. Except for these operations, :class:`.ScheduleBlock` provides full compatibility with :class:`.Schedule`. .. rubric:: Subroutine The timeslots-free representation offers much greater flexibility for writing pulse programs. Because :class:`.ScheduleBlock` only cares about the ordering of the child blocks we can add an undefined pulse sequence as a subroutine of the main program. If your program contains the same sequence multiple times, this representation may reduce the memory footprint required by the program construction. Such a subroutine is realized by the special compiler directive :class:`~qiskit.pulse.instructions.Reference` that is defined by a unique set of reference key strings to the subroutine. The (executable) subroutine is separately stored in the main program. Appended reference directives are resolved when the main program is executed. Subroutines must be assigned through :meth:`assign_references` before execution. .. rubric:: Program Scoping When you call a subroutine from another subroutine, or append a schedule block to another schedule block, the management of references and parameters can be a hard task. Schedule block offers a convenient feature to help with this by automatically scoping the parameters and subroutines. .. code-block:: from qiskit import pulse from qiskit.circuit.parameter import Parameter amp1 = Parameter("amp") with pulse.build() as sched1: pulse.play(pulse.Constant(100, amp1), pulse.DriveChannel(0)) print(sched1.scoped_parameters()) .. parsed-literal:: (Parameter(root::amp),) The :meth:`~ScheduleBlock.scoped_parameters` method returns all :class:`~.Parameter` objects defined in the schedule block. The parameter name is updated to reflect its scope information, i.e. where it is defined. The outer scope is called "root". Since the "amp" parameter is directly used in the current builder context, it is prefixed with "root". Note that the :class:`Parameter` object returned by :meth:`~ScheduleBlock.scoped_parameters` preserves the hidden `UUID`_ key, and thus the scoped name doesn't break references to the original :class:`Parameter`. You may want to call this program from another program. In this example, the program is called with the reference key "grand_child". You can call a subroutine without specifying a substantial program (like ``sched1`` above which we will assign later). .. code-block:: amp2 = Parameter("amp") with pulse.build() as sched2: with pulse.align_right(): pulse.reference("grand_child") pulse.play(pulse.Constant(200, amp2), pulse.DriveChannel(0)) print(sched2.scoped_parameters()) .. parsed-literal:: (Parameter(root::amp),) This only returns "root::amp" because the "grand_child" reference is unknown. Now you assign the actual pulse program to this reference. .. code-block:: sched2.assign_references({("grand_child", ): sched1}) print(sched2.scoped_parameters()) .. parsed-literal:: (Parameter(root::amp), Parameter(root::grand_child::amp)) Now you get two parameters "root::amp" and "root::grand_child::amp". The second parameter name indicates it is defined within the referred program "grand_child". The program calling the "grand_child" has a reference program description which is accessed through :attr:`ScheduleBlock.references`. .. code-block:: print(sched2.references) .. parsed-literal:: ReferenceManager: - ('grand_child',): ScheduleBlock(Play(Constant(duration=100, amp=amp,... Finally, you may want to call this program from another program. Here we try a different approach to define subroutine. Namely, we call a subroutine from the root program with the actual program ``sched2``. .. code-block:: amp3 = Parameter("amp") with pulse.build() as main: pulse.play(pulse.Constant(300, amp3), pulse.DriveChannel(0)) pulse.call(sched2, name="child") print(main.scoped_parameters()) .. parsed-literal:: (Parameter(root::amp), Parameter(root::child::amp), Parameter(root::child::grand_child::amp)) This implicitly creates a reference named "child" within the root program and assigns ``sched2`` to it. You get three parameters "root::amp", "root::child::amp", and "root::child::grand_child::amp". As you can see, each parameter name reflects the layer of calls from the root program. If you know the scope of a parameter, you can directly get the parameter object using :meth:`ScheduleBlock.search_parameters` as follows. .. code-block:: main.search_parameters("root::child::grand_child::amp") You can use a regular expression to specify the scope. The following returns the parameters defined within the scope of "ground_child" regardless of its parent scope. This is sometimes convenient if you want to extract parameters from a deeply nested program. .. code-block:: main.search_parameters("\\S::grand_child::amp") Note that the root program is only aware of its direct references. .. code-block:: print(main.references) .. parsed-literal:: ReferenceManager: - ('child',): ScheduleBlock(ScheduleBlock(ScheduleBlock(Play(Con... As you can see the main program cannot directly assign a subroutine to the "grand_child" because this subroutine is not called within the root program, i.e. it is indirectly called by "child". However, the returned :class:`.ReferenceManager` is a dict-like object, and you can still reach to "grand_child" via the "child" program with the following chained dict access. .. code-block:: main.references[("child", )].references[("grand_child", )] Note that :attr:`ScheduleBlock.parameters` and :meth:`ScheduleBlock.scoped_parameters()` still collect all parameters also from the subroutine once it's assigned. .. _UUID: https://docs.python.org/3/library/uuid.html#module-uuid """ __slots__ = ( "_parent", "_name", "_reference_manager", "_parameter_manager", "_alignment_context", "_blocks", "_metadata", ) # Prefix to use for auto naming. prefix = "block" # Counter to count instance number. instances_counter = itertools.count() def __init__( self, name: Optional[str] = None, metadata: Optional[dict] = None, alignment_context=None ): """Create an empty schedule block. Args: name: Name of this schedule. Defaults to an autogenerated string if not provided. metadata: Arbitrary key value metadata to associate with the schedule. This gets stored as free-form data in a dict in the :attr:`~qiskit.pulse.ScheduleBlock.metadata` attribute. It will not be directly used in the schedule. alignment_context (AlignmentKind): ``AlignmentKind`` instance that manages scheduling of instructions in this block. Raises: TypeError: if metadata is not a dict. """ from qiskit.pulse.parameter_manager import ParameterManager from qiskit.pulse.transforms import AlignLeft if name is None: name = self.prefix + str(next(self.instances_counter)) if sys.platform != "win32" and not is_main_process(): name += f"-{mp.current_process().pid}" # This points to the parent schedule object in the current scope. # Note that schedule block can be nested without referencing, e.g. .append(child_block), # and parent=None indicates the root program of the current scope. # The nested schedule block objects should not have _reference_manager and # should refer to the one of the root program. # This also means referenced program should be assigned to the root program, not to child. self._parent = None self._name = name self._parameter_manager = ParameterManager() self._reference_manager = ReferenceManager() self._alignment_context = alignment_context or AlignLeft() self._blocks = [] # get parameters from context self._parameter_manager.update_parameter_table(self._alignment_context) if not isinstance(metadata, dict) and metadata is not None: raise TypeError("Only a dictionary or None is accepted for schedule metadata") self._metadata = metadata or {} @classmethod def initialize_from(cls, other_program: Any, name: Optional[str] = None) -> "ScheduleBlock": """Create new schedule object with metadata of another schedule object. Args: other_program: Qiskit program that provides metadata to new object. name: Name of new schedule. Name of ``block`` is used by default. Returns: New block object with name and metadata. Raises: PulseError: When ``other_program`` does not provide necessary information. """ try: name = name or other_program.name if other_program.metadata: metadata = other_program.metadata.copy() else: metadata = None try: alignment_context = other_program.alignment_context except AttributeError: alignment_context = None return cls(name=name, metadata=metadata, alignment_context=alignment_context) except AttributeError as ex: raise PulseError( f"{cls.__name__} cannot be initialized from the program data " f"{other_program.__class__.__name__}." ) from ex @property def name(self) -> str: """Return name of this schedule""" return self._name @property def metadata(self) -> Dict[str, Any]: """The user provided metadata associated with the schedule. User provided ``dict`` of metadata for the schedule. The metadata contents do not affect the semantics of the program but are used to influence the execution of the schedule. It is expected to be passed between all transforms of the schedule and that providers will associate any schedule metadata with the results it returns from the execution of that schedule. """ return self._metadata @metadata.setter def metadata(self, metadata): """Update the schedule metadata""" if not isinstance(metadata, dict) and metadata is not None: raise TypeError("Only a dictionary or None is accepted for schedule metadata") self._metadata = metadata or {} @property def alignment_context(self): """Return alignment instance that allocates block component to generate schedule.""" return self._alignment_context def is_schedulable(self) -> bool: """Return ``True`` if all durations are assigned.""" # check context assignment for context_param in self._alignment_context._context_params: if isinstance(context_param, ParameterExpression): return False # check duration assignment for elm in self.blocks: if isinstance(elm, ScheduleBlock): if not elm.is_schedulable(): return False else: try: if not isinstance(elm.duration, int): return False except UnassignedReferenceError: return False return True @property @_require_schedule_conversion def duration(self) -> int: """Duration of this schedule block.""" return self.duration @property def channels(self) -> Tuple[Channel]: """Returns channels that this schedule block uses.""" chans = set() for elm in self.blocks: if isinstance(elm, Reference): raise UnassignedReferenceError( f"This schedule contains unassigned reference {elm.ref_keys} " "and channels are ambiguous. Please assign the subroutine first." ) chans = chans | set(elm.channels) return tuple(chans) @property @_require_schedule_conversion def instructions(self) -> Tuple[Tuple[int, Instruction]]: """Get the time-ordered instructions from self.""" return self.instructions @property def blocks(self) -> Tuple["BlockComponent", ...]: """Get the block elements added to self. .. note:: The sequence of elements is returned in order of addition. Because the first element is schedule first, e.g. FIFO, the returned sequence is roughly time-ordered. However, in the parallel alignment context, especially in the as-late-as-possible scheduling, or :class:`.AlignRight` context, the actual timing of when the instructions are issued is unknown until the :class:`.ScheduleBlock` is scheduled and converted into a :class:`.Schedule`. """ blocks = [] for elm in self._blocks: if isinstance(elm, Reference): elm = self.references.get(elm.ref_keys, None) or elm blocks.append(elm) return tuple(blocks) @property def parameters(self) -> Set[Parameter]: """Return unassigned parameters with raw names.""" # Need new object not to mutate parameter_manager.parameters out_params = set() out_params |= self._parameter_manager.parameters for subroutine in self.references.values(): if subroutine is None: continue out_params |= subroutine.parameters return out_params def scoped_parameters(self) -> Tuple[Parameter]: """Return unassigned parameters with scoped names. .. note:: If a parameter is defined within a nested scope, it is prefixed with all parent-scope names with the delimiter string, which is "::". If a reference key of the scope consists of multiple key strings, it will be represented by a single string joined with ",". For example, "root::xgate,q0::amp" for the parameter "amp" defined in the reference specified by the key strings ("xgate", "q0"). """ return tuple( sorted( _collect_scoped_parameters(self, current_scope="root").values(), key=lambda p: p.name, ) ) @property def references(self) -> ReferenceManager: """Return a reference manager of the current scope.""" if self._parent is not None: return self._parent.references return self._reference_manager @_require_schedule_conversion def ch_duration(self, *channels: Channel) -> int: """Return the time of the end of the last instruction over the supplied channels. Args: *channels: Channels within ``self`` to include. """ return self.ch_duration(*channels) def append( self, block: "BlockComponent", name: Optional[str] = None, inplace: bool = True ) -> "ScheduleBlock": """Return a new schedule block with ``block`` appended to the context block. The execution time is automatically assigned when the block is converted into schedule. Args: block: ScheduleBlock to be appended. name: Name of the new ``Schedule``. Defaults to name of ``self``. inplace: Perform operation inplace on this schedule. Otherwise, return a new ``Schedule``. Returns: Schedule block with appended schedule. Raises: PulseError: When invalid schedule type is specified. """ if not isinstance(block, (ScheduleBlock, Instruction)): raise PulseError( f"Appended `schedule` {block.__class__.__name__} is invalid type. " "Only `Instruction` and `ScheduleBlock` can be accepted." ) if not inplace: schedule = copy.deepcopy(self) schedule._name = name or self.name schedule.append(block, inplace=True) return schedule if isinstance(block, Reference) and block.ref_keys not in self.references: self.references[block.ref_keys] = None elif isinstance(block, ScheduleBlock): block = copy.deepcopy(block) # Expose subroutines to the current main scope. # Note that this 'block' is not called. # The block is just directly appended to the current scope. if block.is_referenced(): if block._parent is not None: # This is an edge case: # If this is not a parent, block.references points to the parent's reference # where subroutine not referred within the 'block' may exist. # Move only references existing in the 'block'. # See 'test.python.pulse.test_reference.TestReference.test_appending_child_block' for ref in _get_references(block._blocks): self.references[ref.ref_keys] = block.references[ref.ref_keys] else: # Avoid using dict.update and explicitly call __set_item__ for validation. # Reference manager of appended block is cleared because of data reduction. for ref_keys, ref in block._reference_manager.items(): self.references[ref_keys] = ref block._reference_manager.clear() # Now switch the parent because block is appended to self. block._parent = self self._blocks.append(block) self._parameter_manager.update_parameter_table(block) return self def filter( self, *filter_funcs: List[Callable], channels: Optional[Iterable[Channel]] = None, instruction_types: Union[Iterable[abc.ABCMeta], abc.ABCMeta] = None, check_subroutine: bool = True, ): """Return a new ``ScheduleBlock`` with only the instructions from this ``ScheduleBlock`` which pass though the provided filters; i.e. an instruction will be retained if every function in ``filter_funcs`` returns ``True``, the instruction occurs on a channel type contained in ``channels``, and the instruction type is contained in ``instruction_types``. .. warning:: Because ``ScheduleBlock`` is not aware of the execution time of the context instructions, filtering out some instructions may change the execution time of the remaining instructions. If no arguments are provided, ``self`` is returned. Args: filter_funcs: A list of Callables which take a ``Instruction`` and return a bool. channels: For example, ``[DriveChannel(0), AcquireChannel(0)]``. instruction_types: For example, ``[PulseInstruction, AcquireInstruction]``. check_subroutine: Set `True` to individually filter instructions inside a subroutine defined by the :py:class:`~qiskit.pulse.instructions.Call` instruction. Returns: ``ScheduleBlock`` consisting of instructions that matches with filtering condition. """ from qiskit.pulse.filters import composite_filter, filter_instructions filters = composite_filter(channels, instruction_types) filters.extend(filter_funcs) return filter_instructions( self, filters=filters, negate=False, recurse_subroutines=check_subroutine ) def exclude( self, *filter_funcs: List[Callable], channels: Optional[Iterable[Channel]] = None, instruction_types: Union[Iterable[abc.ABCMeta], abc.ABCMeta] = None, check_subroutine: bool = True, ): """Return a new ``ScheduleBlock`` with only the instructions from this ``ScheduleBlock`` *failing* at least one of the provided filters. This method is the complement of py:meth:`~self.filter`, so that:: self.filter(args) + self.exclude(args) == self in terms of instructions included. .. warning:: Because ``ScheduleBlock`` is not aware of the execution time of the context instructions, excluding some instructions may change the execution time of the remaining instructions. Args: filter_funcs: A list of Callables which take a ``Instruction`` and return a bool. channels: For example, ``[DriveChannel(0), AcquireChannel(0)]``. instruction_types: For example, ``[PulseInstruction, AcquireInstruction]``. check_subroutine: Set `True` to individually filter instructions inside of a subroutine defined by the :py:class:`~qiskit.pulse.instructions.Call` instruction. Returns: ``ScheduleBlock`` consisting of instructions that do not match with at least one of filtering conditions. """ from qiskit.pulse.filters import composite_filter, filter_instructions filters = composite_filter(channels, instruction_types) filters.extend(filter_funcs) return filter_instructions( self, filters=filters, negate=True, recurse_subroutines=check_subroutine ) def replace( self, old: "BlockComponent", new: "BlockComponent", inplace: bool = True, ) -> "ScheduleBlock": """Return a ``ScheduleBlock`` with the ``old`` component replaced with a ``new`` component. Args: old: Schedule block component to replace. new: Schedule block component to replace with. inplace: Replace instruction by mutably modifying this ``ScheduleBlock``. Returns: The modified schedule block with ``old`` replaced by ``new``. """ if not inplace: schedule = copy.deepcopy(self) return schedule.replace(old, new, inplace=True) if old not in self._blocks: # Avoid unnecessary update of reference and parameter manager return self # Temporarily copies references all_references = ReferenceManager() if isinstance(new, ScheduleBlock): new = copy.deepcopy(new) all_references.update(new.references) new._reference_manager.clear() new._parent = self for ref_key, subroutine in self.references.items(): if ref_key in all_references: warnings.warn( f"Reference {ref_key} conflicts with substituted program {new.name}. " "Existing reference has been replaced with new reference.", UserWarning, ) continue all_references[ref_key] = subroutine # Regenerate parameter table by regenerating elements. # Note that removal of parameters in old is not sufficient, # because corresponding parameters might be also used in another block element. self._parameter_manager.clear() self._parameter_manager.update_parameter_table(self._alignment_context) new_elms = [] for elm in self._blocks: if elm == old: elm = new self._parameter_manager.update_parameter_table(elm) new_elms.append(elm) self._blocks = new_elms # Regenerate reference table # Note that reference is attached to the outer schedule if nested. # Thus, this investigates all references within the scope. self.references.clear() root = self while root._parent is not None: root = root._parent for ref in _get_references(root._blocks): self.references[ref.ref_keys] = all_references[ref.ref_keys] return self def is_parameterized(self) -> bool: """Return True iff the instruction is parameterized.""" return any(self.parameters) def is_referenced(self) -> bool: """Return True iff the current schedule block contains reference to subroutine.""" return len(self.references) > 0 def assign_parameters( self, value_dict: Dict[ParameterExpression, ParameterValueType], inplace: bool = True, ) -> "ScheduleBlock": """Assign the parameters in this schedule according to the input. Args: value_dict: A mapping from Parameters to either numeric values or another Parameter expression. inplace: Set ``True`` to override this instance with new parameter. Returns: Schedule with updated parameters. Raises: PulseError: When the block is nested into another block. """ if not inplace: new_schedule = copy.deepcopy(self) return new_schedule.assign_parameters(value_dict, inplace=True) # Update parameters in the current scope self._parameter_manager.assign_parameters(pulse_program=self, value_dict=value_dict) for subroutine in self._reference_manager.values(): # Also assigning parameters to the references associated with self. # Note that references are always stored in the root program. # So calling assign_parameters from nested block doesn't update references. if subroutine is None: continue subroutine.assign_parameters(value_dict=value_dict, inplace=True) return self def assign_references( self, subroutine_dict: Dict[Union[str, Tuple[str, ...]], "ScheduleBlock"], inplace: bool = True, ) -> "ScheduleBlock": """Assign schedules to references. It is only capable of assigning a schedule block to immediate references which are directly referred within the current scope. Let's see following example: .. code-block:: python from qiskit import pulse with pulse.build() as subroutine: pulse.delay(10, pulse.DriveChannel(0)) with pulse.build() as sub_prog: pulse.reference("A") with pulse.build() as main_prog: pulse.reference("B") In above example, the ``main_prog`` can refer to the subroutine "root::B" and the reference of "B" to program "A", i.e., "B::A", is not defined in the root namespace. This prevents breaking the reference "root::B::A" by the assignment of "root::B". For example, if a user could indirectly assign "root::B::A" from the root program, one can later assign another program to "root::B" that doesn't contain "A" within it. In this situation, a reference "root::B::A" would still live in the reference manager of the root. However, the subroutine "root::B::A" would no longer be used in the actual pulse program. To assign subroutine "A" to ``nested_prog`` as a nested subprogram of ``main_prog``, you must first assign "A" of the ``sub_prog``, and then assign the ``sub_prog`` to the ``main_prog``. .. code-block:: python sub_prog.assign_references({("A", ): nested_prog}, inplace=True) main_prog.assign_references({("B", ): sub_prog}, inplace=True) Alternatively, you can also write .. code-block:: python main_prog.assign_references({("B", ): sub_prog}, inplace=True) main_prog.references[("B", )].assign_references({"A": nested_prog}, inplace=True) Here :attr:`.references` returns a dict-like object, and you can mutably update the nested reference of the particular subroutine. .. note:: Assigned programs are deep-copied to prevent an unexpected update. Args: subroutine_dict: A mapping from reference key to schedule block of the subroutine. inplace: Set ``True`` to override this instance with new subroutine. Returns: Schedule block with assigned subroutine. Raises: PulseError: When reference key is not defined in the current scope. """ if not inplace: new_schedule = copy.deepcopy(self) return new_schedule.assign_references(subroutine_dict, inplace=True) for key, subroutine in subroutine_dict.items(): if key not in self.references: unassigned_keys = ", ".join(map(repr, self.references.unassigned())) raise PulseError( f"Reference instruction with {key} doesn't exist " f"in the current scope: {unassigned_keys}" ) self.references[key] = copy.deepcopy(subroutine) return self def get_parameters(self, parameter_name: str) -> List[Parameter]: """Get parameter object bound to this schedule by string name. Note that we can define different parameter objects with the same name, because these different objects are identified by their unique uuid. For example, .. code-block:: python from qiskit import pulse, circuit amp1 = circuit.Parameter("amp") amp2 = circuit.Parameter("amp") with pulse.build() as sub_prog: pulse.play(pulse.Constant(100, amp1), pulse.DriveChannel(0)) with pulse.build() as main_prog: pulse.call(sub_prog, name="sub") pulse.play(pulse.Constant(100, amp2), pulse.DriveChannel(0)) main_prog.get_parameters("amp") This returns a list of two parameters ``amp1`` and ``amp2``. Args: parameter_name: Name of parameter. Returns: Parameter objects that have corresponding name. """ matched = [p for p in self.parameters if p.name == parameter_name] return matched def search_parameters(self, parameter_regex: str) -> List[Parameter]: """Search parameter with regular expression. This method looks for the scope-aware parameters. For example, .. code-block:: python from qiskit import pulse, circuit amp1 = circuit.Parameter("amp") amp2 = circuit.Parameter("amp") with pulse.build() as sub_prog: pulse.play(pulse.Constant(100, amp1), pulse.DriveChannel(0)) with pulse.build() as main_prog: pulse.call(sub_prog, name="sub") pulse.play(pulse.Constant(100, amp2), pulse.DriveChannel(0)) main_prog.search_parameters("root::sub::amp") This finds ``amp1`` with scoped name "root::sub::amp". Args: parameter_regex: Regular expression for scoped parameter name. Returns: Parameter objects that have corresponding name. """ pattern = re.compile(parameter_regex) return sorted( _collect_scoped_parameters(self, current_scope="root", filter_regex=pattern).values(), key=lambda p: p.name, ) def __len__(self) -> int: """Return number of instructions in the schedule.""" return len(self.blocks) def __eq__(self, other: "ScheduleBlock") -> bool: """Test if two ScheduleBlocks are equal. Equality is checked by verifying there is an equal instruction at every time in ``other`` for every instruction in this ``ScheduleBlock``. This check is performed by converting the instruction representation into directed acyclic graph, in which execution order of every instruction is evaluated correctly across all channels. Also ``self`` and ``other`` should have the same alignment context. .. warning:: This does not check for logical equivalency. Ie., ```python >>> Delay(10, DriveChannel(0)) + Delay(10, DriveChannel(0)) == Delay(20, DriveChannel(0)) False ``` """ # 0. type check if not isinstance(other, type(self)): return False # 1. transformation check if self.alignment_context != other.alignment_context: return False # 2. size check if len(self) != len(other): return False # 3. instruction check with alignment from qiskit.pulse.transforms.dag import block_to_dag as dag if not rx.is_isomorphic_node_match(dag(self), dag(other), lambda x, y: x == y): return False return True def __repr__(self) -> str: name = format(self._name) if self._name else "" blocks = ", ".join([repr(instr) for instr in self.blocks[:50]]) if len(self.blocks) > 25: blocks += ", ..." return '{}({}, name="{}", transform={})'.format( self.__class__.__name__, blocks, name, repr(self.alignment_context) ) def __add__(self, other: "BlockComponent") -> "ScheduleBlock": """Return a new schedule with ``other`` inserted within ``self`` at ``start_time``.""" return self.append(other) def _common_method(*classes): """A function decorator to attach the function to specified classes as a method. .. note:: For developer: A method attached through this decorator may hurt readability of the codebase, because the method may not be detected by a code editor. Thus, this decorator should be used to a limited extent, i.e. huge helper method. By using this decorator wisely, we can reduce code maintenance overhead without losing readability of the codebase. """ def decorator(method): @functools.wraps(method) def wrapper(*args, **kwargs): return method(*args, **kwargs) for cls in classes: setattr(cls, method.__name__, wrapper) return method return decorator @_common_method(Schedule, ScheduleBlock) def draw( self, style: Optional[Dict[str, Any]] = None, backend=None, # importing backend causes cyclic import time_range: Optional[Tuple[int, int]] = None, time_unit: str = "dt", disable_channels: Optional[List[Channel]] = None, show_snapshot: bool = True, show_framechange: bool = True, show_waveform_info: bool = True, show_barrier: bool = True, plotter: str = "mpl2d", axis: Optional[Any] = None, ): """Plot the schedule. Args: style: Stylesheet options. This can be dictionary or preset stylesheet classes. See :py:class:`~qiskit.visualization.pulse_v2.stylesheets.IQXStandard`, :py:class:`~qiskit.visualization.pulse_v2.stylesheets.IQXSimple`, and :py:class:`~qiskit.visualization.pulse_v2.stylesheets.IQXDebugging` for details of preset stylesheets. backend (Optional[BaseBackend]): Backend object to play the input pulse program. If provided, the plotter may use to make the visualization hardware aware. time_range: Set horizontal axis limit. Tuple `(tmin, tmax)`. time_unit: The unit of specified time range either `dt` or `ns`. The unit of `ns` is available only when `backend` object is provided. disable_channels: A control property to show specific pulse channel. Pulse channel instances provided as a list are not shown in the output image. show_snapshot: Show snapshot instructions. show_framechange: Show frame change instructions. The frame change represents instructions that modulate phase or frequency of pulse channels. show_waveform_info: Show additional information about waveforms such as their name. show_barrier: Show barrier lines. plotter: Name of plotter API to generate an output image. One of following APIs should be specified:: mpl2d: Matplotlib API for 2D image generation. Matplotlib API to generate 2D image. Charts are placed along y axis with vertical offset. This API takes matplotlib.axes.Axes as ``axis`` input. ``axis`` and ``style`` kwargs may depend on the plotter. axis: Arbitrary object passed to the plotter. If this object is provided, the plotters use a given ``axis`` instead of internally initializing a figure object. This object format depends on the plotter. See plotter argument for details. Returns: Visualization output data. The returned data type depends on the ``plotter``. If matplotlib family is specified, this will be a ``matplotlib.pyplot.Figure`` data. """ # pylint: disable=cyclic-import from qiskit.visualization import pulse_drawer return pulse_drawer( program=self, style=style, backend=backend, time_range=time_range, time_unit=time_unit, disable_channels=disable_channels, show_snapshot=show_snapshot, show_framechange=show_framechange, show_waveform_info=show_waveform_info, show_barrier=show_barrier, plotter=plotter, axis=axis, ) def _interval_index(intervals: List[Interval], interval: Interval) -> int: """Find the index of an interval. Args: intervals: A sorted list of non-overlapping Intervals. interval: The interval for which the index into intervals will be found. Returns: The index of the interval. Raises: PulseError: If the interval does not exist. """ index = _locate_interval_index(intervals, interval) found_interval = intervals[index] if found_interval != interval: raise PulseError(f"The interval: {interval} does not exist in intervals: {intervals}") return index def _locate_interval_index(intervals: List[Interval], interval: Interval, index: int = 0) -> int: """Using binary search on start times, find an interval. Args: intervals: A sorted list of non-overlapping Intervals. interval: The interval for which the index into intervals will be found. index: A running tally of the index, for recursion. The user should not pass a value. Returns: The index into intervals that new_interval would be inserted to maintain a sorted list of intervals. """ if not intervals or len(intervals) == 1: return index mid_idx = len(intervals) // 2 mid = intervals[mid_idx] if interval[1] <= mid[0] and (interval != mid): return _locate_interval_index(intervals[:mid_idx], interval, index=index) else: return _locate_interval_index(intervals[mid_idx:], interval, index=index + mid_idx) def _find_insertion_index(intervals: List[Interval], new_interval: Interval) -> int: """Using binary search on start times, return the index into `intervals` where the new interval belongs, or raise an error if the new interval overlaps with any existing ones. Args: intervals: A sorted list of non-overlapping Intervals. new_interval: The interval for which the index into intervals will be found. Returns: The index into intervals that new_interval should be inserted to maintain a sorted list of intervals. Raises: PulseError: If new_interval overlaps with the given intervals. """ index = _locate_interval_index(intervals, new_interval) if index < len(intervals): if _overlaps(intervals[index], new_interval): raise PulseError("New interval overlaps with existing.") return index if new_interval[1] <= intervals[index][0] else index + 1 return index def _overlaps(first: Interval, second: Interval) -> bool: """Return True iff first and second overlap. Note: first.stop may equal second.start, since Interval stop times are exclusive. """ if first[0] == second[0] == second[1]: # They fail to overlap if one of the intervals has duration 0 return False if first[0] > second[0]: first, second = second, first return second[0] < first[1] def _check_nonnegative_timeslot(timeslots: TimeSlots): """Test that a channel has no negative timeslots. Raises: PulseError: If a channel timeslot is negative. """ for chan, chan_timeslots in timeslots.items(): if chan_timeslots: if chan_timeslots[0][0] < 0: raise PulseError(f"An instruction on {chan} has a negative starting time.") def _get_timeslots(schedule: "ScheduleComponent") -> TimeSlots: """Generate timeslots from given schedule component. Args: schedule: Input schedule component. Raises: PulseError: When invalid schedule type is specified. """ if isinstance(schedule, Instruction): duration = schedule.duration instruction_duration_validation(duration) timeslots = {channel: [(0, duration)] for channel in schedule.channels} elif isinstance(schedule, Schedule): timeslots = schedule.timeslots else: raise PulseError(f"Invalid schedule type {type(schedule)} is specified.") return timeslots def _get_references(block_elms: List["BlockComponent"]) -> Set[Reference]: """Recursively get reference instructions in the current scope. Args: block_elms: List of schedule block elements to investigate. Returns: A set of unique reference instructions. """ references = set() for elm in block_elms: if isinstance(elm, ScheduleBlock): references |= _get_references(elm._blocks) elif isinstance(elm, Reference): references.add(elm) return references def _collect_scoped_parameters( schedule: ScheduleBlock, current_scope: str, filter_regex: Optional[re.Pattern] = None, ) -> Dict[Tuple[str, int], Parameter]: """A helper function to collect parameters from all references in scope-aware fashion. Parameter object is renamed with attached scope information but its UUID is remained. This means object is treated identically on the assignment logic. This function returns a dictionary of all parameters existing in the target program including its reference, which is keyed on the unique identifier consisting of scoped parameter name and parameter object UUID. This logic prevents parameter clash in the different scope. For example, when two parameter objects with the same UUID exist in different references, both of them appear in the output dictionary, even though they are technically the same object. This feature is particularly convenient to search parameter object with associated scope. Args: schedule: Schedule to get parameters. current_scope: Name of scope where schedule exist. filter_regex: Optional. Compiled regex to sort parameter by name. Returns: A dictionary of scoped parameter objects. """ parameters_out = {} for param in schedule._parameter_manager.parameters: new_name = f"{current_scope}{Reference.scope_delimiter}{param.name}" if filter_regex and not re.search(filter_regex, new_name): continue scoped_param = Parameter.__new__(Parameter, new_name, uuid=getattr(param, "_uuid")) scoped_param.__init__(new_name) unique_key = new_name, hash(param) parameters_out[unique_key] = scoped_param for sub_namespace, subroutine in schedule.references.items(): if subroutine is None: continue composite_key = Reference.key_delimiter.join(sub_namespace) full_path = f"{current_scope}{Reference.scope_delimiter}{composite_key}" sub_parameters = _collect_scoped_parameters( subroutine, current_scope=full_path, filter_regex=filter_regex ) parameters_out.update(sub_parameters) return parameters_out # These type aliases are defined at the bottom of the file, because as of 2022-01-18 they are # imported into other parts of Terra. Previously, the aliases were at the top of the file and used # forwards references within themselves. This was fine within the same file, but causes scoping # issues when the aliases are imported into different scopes, in which the `ForwardRef` instances # would no longer resolve. Instead, we only use forward references in the annotations of _this_ # file to reference the aliases, which are guaranteed to resolve in scope, so the aliases can all be # concrete. ScheduleComponent = Union[Schedule, Instruction] """An element that composes a pulse schedule.""" BlockComponent = Union[ScheduleBlock, Instruction] """An element that composes a pulse schedule block."""
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# 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. """Basic rescheduling functions which take schedule or instructions and return new schedules.""" import warnings from collections import defaultdict from typing import List, Optional, Iterable, Union, Type import numpy as np from qiskit.pulse import channels as chans, exceptions, instructions from qiskit.pulse.channels import ClassicalIOChannel from qiskit.pulse.exceptions import PulseError from qiskit.pulse.exceptions import UnassignedDurationError from qiskit.pulse.instruction_schedule_map import InstructionScheduleMap from qiskit.pulse.instructions import directives from qiskit.pulse.schedule import Schedule, ScheduleBlock, ScheduleComponent def block_to_schedule(block: ScheduleBlock) -> Schedule: """Convert ``ScheduleBlock`` to ``Schedule``. Args: block: A ``ScheduleBlock`` to convert. Returns: Scheduled pulse program. Raises: UnassignedDurationError: When any instruction duration is not assigned. PulseError: When the alignment context duration is shorter than the schedule duration. .. note:: This transform may insert barriers in between contexts. """ if not block.is_schedulable(): raise UnassignedDurationError( "All instruction durations should be assigned before creating `Schedule`." "Please check `.parameters` to find unassigned parameter objects." ) schedule = Schedule.initialize_from(block) for op_data in block.blocks: if isinstance(op_data, ScheduleBlock): context_schedule = block_to_schedule(op_data) if hasattr(op_data.alignment_context, "duration"): # context may have local scope duration, e.g. EquispacedAlignment for 1000 dt post_buffer = op_data.alignment_context.duration - context_schedule.duration if post_buffer < 0: raise PulseError( f"ScheduleBlock {op_data.name} has longer duration than " "the specified context duration " f"{context_schedule.duration} > {op_data.duration}." ) else: post_buffer = 0 schedule.append(context_schedule, inplace=True) # prevent interruption by following instructions. # padding with delay instructions is no longer necessary, thanks to alignment context. if post_buffer > 0: context_boundary = instructions.RelativeBarrier(*op_data.channels) schedule.append(context_boundary.shift(post_buffer), inplace=True) else: schedule.append(op_data, inplace=True) # transform with defined policy return block.alignment_context.align(schedule) def compress_pulses(schedules: List[Schedule]) -> List[Schedule]: """Optimization pass to replace identical pulses. Args: schedules: Schedules to compress. Returns: Compressed schedules. """ existing_pulses = [] new_schedules = [] for schedule in schedules: new_schedule = Schedule.initialize_from(schedule) for time, inst in schedule.instructions: if isinstance(inst, instructions.Play): if inst.pulse in existing_pulses: idx = existing_pulses.index(inst.pulse) identical_pulse = existing_pulses[idx] new_schedule.insert( time, instructions.Play(identical_pulse, inst.channel, inst.name), inplace=True, ) else: existing_pulses.append(inst.pulse) new_schedule.insert(time, inst, inplace=True) else: new_schedule.insert(time, inst, inplace=True) new_schedules.append(new_schedule) return new_schedules def flatten(program: Schedule) -> Schedule: """Flatten (inline) any called nodes into a Schedule tree with no nested children. Args: program: Pulse program to remove nested structure. Returns: Flatten pulse program. Raises: PulseError: When invalid data format is given. """ if isinstance(program, Schedule): flat_sched = Schedule.initialize_from(program) for time, inst in program.instructions: flat_sched.insert(time, inst, inplace=True) return flat_sched else: raise PulseError(f"Invalid input program {program.__class__.__name__} is specified.") def inline_subroutines(program: Union[Schedule, ScheduleBlock]) -> Union[Schedule, ScheduleBlock]: """Recursively remove call instructions and inline the respective subroutine instructions. Assigned parameter values, which are stored in the parameter table, are also applied. The subroutine is copied before the parameter assignment to avoid mutation problem. Args: program: A program which may contain the subroutine, i.e. ``Call`` instruction. Returns: A schedule without subroutine. Raises: PulseError: When input program is not valid data format. """ if isinstance(program, Schedule): return _inline_schedule(program) elif isinstance(program, ScheduleBlock): return _inline_block(program) else: raise PulseError(f"Invalid program {program.__class__.__name__} is specified.") def _inline_schedule(schedule: Schedule) -> Schedule: """A helper function to inline subroutine of schedule. .. note:: If subroutine is ``ScheduleBlock`` it is converted into Schedule to get ``t0``. """ ret_schedule = Schedule.initialize_from(schedule) for t0, inst in schedule.children: # note that schedule.instructions unintentionally flatten the nested schedule. # this should be performed by another transformer node. if isinstance(inst, instructions.Call): # bind parameter subroutine = inst.assigned_subroutine() # convert into schedule if block is given if isinstance(subroutine, ScheduleBlock): subroutine = block_to_schedule(subroutine) # recursively inline the program inline_schedule = _inline_schedule(subroutine) ret_schedule.insert(t0, inline_schedule, inplace=True) elif isinstance(inst, Schedule): # recursively inline the program inline_schedule = _inline_schedule(inst) ret_schedule.insert(t0, inline_schedule, inplace=True) else: ret_schedule.insert(t0, inst, inplace=True) return ret_schedule def _inline_block(block: ScheduleBlock) -> ScheduleBlock: """A helper function to inline subroutine of schedule block. .. note:: If subroutine is ``Schedule`` the function raises an error. """ ret_block = ScheduleBlock.initialize_from(block) for inst in block.blocks: if isinstance(inst, instructions.Call): # bind parameter subroutine = inst.assigned_subroutine() if isinstance(subroutine, Schedule): raise PulseError( f"A subroutine {subroutine.name} is a pulse Schedule. " "This program cannot be inserted into ScheduleBlock because " "t0 associated with instruction will be lost." ) # recursively inline the program inline_block = _inline_block(subroutine) ret_block.append(inline_block, inplace=True) elif isinstance(inst, ScheduleBlock): # recursively inline the program inline_block = _inline_block(inst) ret_block.append(inline_block, inplace=True) else: ret_block.append(inst, inplace=True) return ret_block def remove_directives(schedule: Schedule) -> Schedule: """Remove directives. Args: schedule: A schedule to remove compiler directives. Returns: A schedule without directives. """ return schedule.exclude(instruction_types=[directives.Directive]) def remove_trivial_barriers(schedule: Schedule) -> Schedule: """Remove trivial barriers with 0 or 1 channels. Args: schedule: A schedule to remove trivial barriers. Returns: schedule: A schedule without trivial barriers """ def filter_func(inst): return isinstance(inst[1], directives.RelativeBarrier) and len(inst[1].channels) < 2 return schedule.exclude(filter_func) def align_measures( schedules: Iterable[ScheduleComponent], inst_map: Optional[InstructionScheduleMap] = None, cal_gate: str = "u3", max_calibration_duration: Optional[int] = None, align_time: Optional[int] = None, align_all: Optional[bool] = True, ) -> List[Schedule]: """Return new schedules where measurements occur at the same physical time. This transformation will align the first :class:`.Acquire` on every channel to occur at the same time. Minimum measurement wait time (to allow for calibration pulses) is enforced and may be set with ``max_calibration_duration``. By default only instructions containing a :class:`.AcquireChannel` or :class:`.MeasureChannel` will be shifted. If you wish to keep the relative timing of all instructions in the schedule set ``align_all=True``. This method assumes that ``MeasureChannel(i)`` and ``AcquireChannel(i)`` correspond to the same qubit and the acquire/play instructions should be shifted together on these channels. .. code-block:: from qiskit import pulse from qiskit.pulse import transforms d0 = pulse.DriveChannel(0) m0 = pulse.MeasureChannel(0) a0 = pulse.AcquireChannel(0) mem0 = pulse.MemorySlot(0) sched = pulse.Schedule() sched.append(pulse.Play(pulse.Constant(10, 0.5), d0), inplace=True) sched.append(pulse.Play(pulse.Constant(10, 1.), m0).shift(sched.duration), inplace=True) sched.append(pulse.Acquire(20, a0, mem0).shift(sched.duration), inplace=True) sched_shifted = sched << 20 aligned_sched, aligned_sched_shifted = transforms.align_measures([sched, sched_shifted]) assert aligned_sched == aligned_sched_shifted If it is desired to only shift acquisition and measurement stimulus instructions set the flag ``align_all=False``: .. code-block:: aligned_sched, aligned_sched_shifted = transforms.align_measures( [sched, sched_shifted], align_all=False, ) assert aligned_sched != aligned_sched_shifted Args: schedules: Collection of schedules to be aligned together inst_map: Mapping of circuit operations to pulse schedules cal_gate: The name of the gate to inspect for the calibration time max_calibration_duration: If provided, inst_map and cal_gate will be ignored align_time: If provided, this will be used as final align time. align_all: Shift all instructions in the schedule such that they maintain their relative alignment with the shifted acquisition instruction. If ``False`` only the acquisition and measurement pulse instructions will be shifted. Returns: The input list of schedules transformed to have their measurements aligned. Raises: PulseError: If the provided alignment time is negative. """ def get_first_acquire_times(schedules): """Return a list of first acquire times for each schedule.""" acquire_times = [] for schedule in schedules: visited_channels = set() qubit_first_acquire_times = defaultdict(lambda: None) for time, inst in schedule.instructions: if isinstance(inst, instructions.Acquire) and inst.channel not in visited_channels: visited_channels.add(inst.channel) qubit_first_acquire_times[inst.channel.index] = time acquire_times.append(qubit_first_acquire_times) return acquire_times def get_max_calibration_duration(inst_map, cal_gate): """Return the time needed to allow for readout discrimination calibration pulses.""" # TODO (qiskit-terra #5472): fix behavior of this. max_calibration_duration = 0 for qubits in inst_map.qubits_with_instruction(cal_gate): cmd = inst_map.get(cal_gate, qubits, np.pi, 0, np.pi) max_calibration_duration = max(cmd.duration, max_calibration_duration) return max_calibration_duration if align_time is not None and align_time < 0: raise exceptions.PulseError("Align time cannot be negative.") first_acquire_times = get_first_acquire_times(schedules) # Extract the maximum acquire in every schedule across all acquires in the schedule. # If there are no acquires in the schedule default to 0. max_acquire_times = [max(0, *times.values()) for times in first_acquire_times] if align_time is None: if max_calibration_duration is None: if inst_map: max_calibration_duration = get_max_calibration_duration(inst_map, cal_gate) else: max_calibration_duration = 0 align_time = max(max_calibration_duration, *max_acquire_times) # Shift acquires according to the new scheduled time new_schedules = [] for sched_idx, schedule in enumerate(schedules): new_schedule = Schedule.initialize_from(schedule) stop_time = schedule.stop_time if align_all: if first_acquire_times[sched_idx]: shift = align_time - max_acquire_times[sched_idx] else: shift = align_time - stop_time else: shift = 0 for time, inst in schedule.instructions: measurement_channels = { chan.index for chan in inst.channels if isinstance(chan, (chans.MeasureChannel, chans.AcquireChannel)) } if measurement_channels: sched_first_acquire_times = first_acquire_times[sched_idx] max_start_time = max( sched_first_acquire_times[chan] for chan in measurement_channels if chan in sched_first_acquire_times ) shift = align_time - max_start_time if shift < 0: warnings.warn( "The provided alignment time is scheduling an acquire instruction " "earlier than it was scheduled for in the original Schedule. " "This may result in an instruction being scheduled before t=0 and " "an error being raised." ) new_schedule.insert(time + shift, inst, inplace=True) new_schedules.append(new_schedule) return new_schedules def add_implicit_acquires(schedule: ScheduleComponent, meas_map: List[List[int]]) -> Schedule: """Return a new schedule with implicit acquires from the measurement mapping replaced by explicit ones. .. warning:: Since new acquires are being added, Memory Slots will be set to match the qubit index. This may overwrite your specification. Args: schedule: Schedule to be aligned. meas_map: List of lists of qubits that are measured together. Returns: A ``Schedule`` with the additional acquisition instructions. """ new_schedule = Schedule.initialize_from(schedule) acquire_map = {} for time, inst in schedule.instructions: if isinstance(inst, instructions.Acquire): if inst.mem_slot and inst.mem_slot.index != inst.channel.index: warnings.warn( "One of your acquires was mapped to a memory slot which didn't match" " the qubit index. I'm relabeling them to match." ) # Get the label of all qubits that are measured with the qubit(s) in this instruction all_qubits = [] for sublist in meas_map: if inst.channel.index in sublist: all_qubits.extend(sublist) # Replace the old acquire instruction by a new one explicitly acquiring all qubits in # the measurement group. for i in all_qubits: explicit_inst = instructions.Acquire( inst.duration, chans.AcquireChannel(i), mem_slot=chans.MemorySlot(i), kernel=inst.kernel, discriminator=inst.discriminator, ) if time not in acquire_map: new_schedule.insert(time, explicit_inst, inplace=True) acquire_map = {time: {i}} elif i not in acquire_map[time]: new_schedule.insert(time, explicit_inst, inplace=True) acquire_map[time].add(i) else: new_schedule.insert(time, inst, inplace=True) return new_schedule def pad( schedule: Schedule, channels: Optional[Iterable[chans.Channel]] = None, until: Optional[int] = None, inplace: bool = False, pad_with: Optional[Type[instructions.Instruction]] = None, ) -> Schedule: """Pad the input Schedule with ``Delay``s on all unoccupied timeslots until ``schedule.duration`` or ``until`` if not ``None``. Args: schedule: Schedule to pad. channels: Channels to pad. Defaults to all channels in ``schedule`` if not provided. If the supplied channel is not a member of ``schedule`` it will be added. until: Time to pad until. Defaults to ``schedule.duration`` if not provided. inplace: Pad this schedule by mutating rather than returning a new schedule. pad_with: Pulse ``Instruction`` subclass to be used for padding. Default to :class:`~qiskit.pulse.instructions.Delay` instruction. Returns: The padded schedule. Raises: PulseError: When non pulse instruction is set to `pad_with`. """ until = until or schedule.duration channels = channels or schedule.channels if pad_with: if issubclass(pad_with, instructions.Instruction): pad_cls = pad_with else: raise PulseError( f"'{pad_with.__class__.__name__}' is not valid pulse instruction to pad with." ) else: pad_cls = instructions.Delay for channel in channels: if isinstance(channel, ClassicalIOChannel): continue if channel not in schedule.channels: schedule = schedule.insert(0, instructions.Delay(until, channel), inplace=inplace) continue prev_time = 0 timeslots = iter(schedule.timeslots[channel]) to_pad = [] while prev_time < until: try: t0, t1 = next(timeslots) except StopIteration: to_pad.append((prev_time, until - prev_time)) break if prev_time < t0: to_pad.append((prev_time, min(t0, until) - prev_time)) prev_time = t1 for t0, duration in to_pad: schedule = schedule.insert(t0, pad_cls(duration, channel), inplace=inplace) return schedule
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# Copyright 2022-2023 Ohad Lev. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0, # or in the root directory of this package("LICENSE.txt"). # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ `SATInterface` class. """ import os import json from typing import List, Tuple, Union, Optional, Dict, Any from sys import stdout from datetime import datetime from hashlib import sha256 from qiskit import transpile, QuantumCircuit, qpy from qiskit.result.counts import Counts from qiskit.visualization.circuit.text import TextDrawing from qiskit.providers.backend import Backend from qiskit.transpiler.passes import RemoveBarriers from IPython import display from matplotlib.figure import Figure from sat_circuits_engine.util import timer_dec, timestamp, flatten_circuit from sat_circuits_engine.util.settings import DATA_PATH, TRANSPILE_KWARGS from sat_circuits_engine.circuit import GroverConstraintsOperator, SATCircuit from sat_circuits_engine.constraints_parse import ParsedConstraints from sat_circuits_engine.interface.circuit_decomposition import decompose_operator from sat_circuits_engine.interface.counts_visualization import plot_histogram from sat_circuits_engine.interface.translator import ConstraintsTranslator from sat_circuits_engine.classical_processing import ( find_iterations_unknown, calc_iterations, ClassicalVerifier, ) from sat_circuits_engine.interface.interactive_inputs import ( interactive_operator_inputs, interactive_solutions_num_input, interactive_run_input, interactive_backend_input, interactive_shots_input, ) # Local globlas for visualization of charts and diagrams IFRAME_WIDTH = "100%" IFRAME_HEIGHT = "700" class SATInterface: """ An interface for building, running and mining data from n-SAT problems quantum circuits. There are 2 options to use this class: (1) Using an interactive interface (intuitive but somewhat limited) - for this just initiate a bare instance of this class: `SATInterface()`. (2) Using the API defined by this class, that includes the following methods: * The following descriptions are partial, for full annotations see the methods' docstrings. - `__init__`: an instance of `SATInterface must be initiated with exactly 1 combination: (a) (high_level_constraints_string + high_level_vars) - for constraints in a high-level format. (b) (num_input_qubits + constraints_string) - for constraints in a low-level foramt. * For formats annotations see `constriants_format.ipynb` in the main directory. - `obtain_grover_operator`: obtains the suitable grover operator for the constraints. - `save_display_grover_operator`: saves and displays data generated by the `obtain_grover_operator` method. - `obtain_overall_circuit`: obtains the suitable overall SAT circuit. - `save_display_overall_circuit: saves and displays data generated by the `obtain_overall_circuit` method. - `run_overall_circuit`: executes the overall SAT circuit. - `save_display_results`: saves and displays data generated by the `run_overall_circuit` method. It is very recommended to go through `demos.ipynb` that demonstrates the various optional uses of this class, in addition to reading `constraints_format.ipynb`, which is a must for using this package properly. Both notebooks are in ther main directory. """ def __init__( self, num_input_qubits: Optional[int] = None, constraints_string: Optional[str] = None, high_level_constraints_string: Optional[str] = None, high_level_vars: Optional[Dict[str, int]] = None, name: Optional[str] = None, save_data: Optional[bool] = True, ) -> None: """ Accepts the combination of paramters: (high_level_constraints_string + high_level_vars) or (num_input_qubits + constraints_string). Exactly one combination is accepted. In other cases either an iteractive user interface will be called to take user's inputs, or an exception will be raised due to misuse of the API. Args: num_input_qubits (Optional[int] = None): number of input qubits. constraints_string (Optional[str] = None): a string of constraints in a low-level format. high_level_constraints_string (Optional[str] = None): a string of constraints in a high-level format. high_level_vars (Optional[Dict[str, int]] = None): a dictionary that configures the high-level variables - keys are names and values are bits-lengths. name (Optional[str] = None): a name for this object, if None than the generic name "SAT" is given automatically. save_data (Optional[bool] = True): if True, saves all data and metadata generated by this class to a unique data folder (by using the `save_XXX` methods of this class). Raises: SyntaxError - if a forbidden combination of arguments has been provided. """ if name is None: name = "SAT" self.name = name # Creating a directory for data to be saved if save_data: self.time_created = timestamp(datetime.now()) self.dir_path = f"{DATA_PATH}{self.time_created}_{self.name}/" os.mkdir(self.dir_path) print(f"Data will be saved into '{self.dir_path}'.") # Initial metadata, more to be added by this class' `save_XXX` methods self.metadata = { "name": self.name, "datetime": self.time_created, "num_input_qubits": num_input_qubits, "constraints_string": constraints_string, "high_level_constraints_string": high_level_constraints_string, "high_level_vars": high_level_vars, } self.update_metadata() # Identifying user's platform, for visualization purposes self.identify_platform() # In the case of low-level constraints format, that is the default value self.high_to_low_map = None # Case A - interactive interface if (num_input_qubits is None or constraints_string is None) and ( high_level_constraints_string is None or high_level_vars is None ): self.interactive_interface() # Case B - API else: self.high_level_constraints_string = high_level_constraints_string self.high_level_vars = high_level_vars # Case B.1 - high-level format constraints inputs if num_input_qubits is None or constraints_string is None: self.num_input_qubits = sum(self.high_level_vars.values()) self.high_to_low_map, self.constraints_string = ConstraintsTranslator( self.high_level_constraints_string, self.high_level_vars ).translate() # Case B.2 - low-level format constraints inputs elif num_input_qubits is not None and constraints_string is not None: self.num_input_qubits = num_input_qubits self.constraints_string = constraints_string # Misuse else: raise SyntaxError( "SATInterface accepts the combination of paramters:" "(high_level_constraints_string + high_level_vars) or " "(num_input_qubits + constraints_string). " "Exactly one combination is accepted, not both." ) self.parsed_constraints = ParsedConstraints( self.constraints_string, self.high_level_constraints_string ) def update_metadata(self, update_metadata: Optional[Dict[str, Any]] = None) -> None: """ Updates the metadata file (in the unique data folder of a given `SATInterface` instance). Args: update_metadata (Optional[Dict[str, Any]] = None): - If None - just dumps `self.metadata` into the metadata JSON file. - If defined - updates the `self.metadata` attribute and then dumps it. """ if update_metadata is not None: self.metadata.update(update_metadata) with open(f"{self.dir_path}metadata.json", "w") as metadata_file: json.dump(self.metadata, metadata_file, indent=4) def identify_platform(self) -> None: """ Identifies user's platform. Writes True to `self.jupyter` for Jupyter notebook, False for terminal. """ # If True then the platform is a terminal/command line/shell if stdout.isatty(): self.jupyter = False # If False, we assume the platform is a Jupyter notebook else: self.jupyter = True def output_to_platform( self, *, title: str, output_terminal: Union[TextDrawing, str], output_jupyter: Union[Figure, str], display_both_on_jupyter: Optional[bool] = False, ) -> None: """ Displays output to user's platform. Args: title (str): a title for the output. output_terminal (Union[TextDrawing, str]): text to print for a terminal platform. output_jupyter: (Union[Figure, str]): objects to display for a Jupyter notebook platform. can handle `Figure` matplotlib objects or strings of paths to IFrame displayable file, e.g PDF files. display_both_on_jupyter (Optional[bool] = False): if True, displays both `output_terminal` and `output_jupyter` in a Jupyter notebook platform. Raises: TypeError - in the case of misusing the `output_jupyter` argument. """ print() print(title) if self.jupyter: if isinstance(output_jupyter, str): display.display(display.IFrame(output_jupyter, width=IFRAME_WIDTH, height=IFRAME_HEIGHT)) elif isinstance(output_jupyter, Figure): display.display(output_jupyter) else: raise TypeError("output_jupyter must be an str (path to image file) or a Figure object.") if display_both_on_jupyter: print(output_terminal) else: print(output_terminal) def interactive_interface(self) -> None: """ An interactive CLI that allows exploiting most (but not all) of the package's features. Uses functions of the form `interactive_XXX_inputs` from the `interactive_inputs.py` module. Divided into 3 main stages: 1. Obtaining Grover's operator for the SAT problem. 2. Obtaining the overall SAT cirucit. 3. Executing the circuit and parsing the results. The interface is built in a modular manner such that a user can halt at any stage. The defualt settings for the interactive user intreface are: 1. `name = "SAT"`. 2. `save_data = True`. 3. `display = True`. 4. `transpile_kwargs = {'basis_gates': ['u', 'cx'], 'optimization_level': 3}`. 5. Backends are limited to those defined in the global-constant-like function `BACKENDS`: - Those are the local `aer_simulator` and the remote `ibmq_qasm_simulator` for now. Due to these default settings the interactive CLI is somewhat restrictive, for full flexibility a user should use the API and not the CLI. """ # Handling operator part operator_inputs = interactive_operator_inputs() self.num_input_qubits = operator_inputs["num_input_qubits"] self.high_to_low_map = operator_inputs["high_to_low_map"] self.constraints_string = operator_inputs["constraints_string"] self.high_level_constraints_string = operator_inputs["high_level_constraints_string"] self.high_level_vars = operator_inputs["high_level_vars"] self.parsed_constraints = ParsedConstraints( self.constraints_string, self.high_level_constraints_string ) self.update_metadata( { "num_input_qubits": self.num_input_qubits, "constraints_string": self.constraints_string, "high_level_constraints_string": self.high_level_constraints_string, "high_level_vars": self.high_level_vars, } ) obtain_grover_operator_output = self.obtain_grover_operator() self.save_display_grover_operator(obtain_grover_operator_output) # Handling overall circuit part solutions_num = interactive_solutions_num_input() if solutions_num is not None: backend = None if solutions_num == -1: backend = interactive_backend_input() overall_circuit_data = self.obtain_overall_sat_circuit( obtain_grover_operator_output["operator"], solutions_num, backend ) self.save_display_overall_circuit(overall_circuit_data) # Handling circuit execution part if interactive_run_input(): if backend is None: backend = interactive_backend_input() shots = interactive_shots_input() counts_parsed = self.run_overall_sat_circuit( overall_circuit_data["circuit"], backend, shots ) self.save_display_results(counts_parsed) print() print(f"Done saving data into '{self.dir_path}'.") def obtain_grover_operator( self, transpile_kwargs: Optional[Dict[str, Any]] = None ) -> Dict[str, Union[GroverConstraintsOperator, QuantumCircuit]]: """ Obtains the suitable `GroverConstraintsOperator` object for the constraints, decomposes it using the `circuit_decomposition.py` module and transpiles it according to `transpile_kwargs`. Args: transpile_kwargs (Optional[Dict[str, Any]]): kwargs for Qiskit's transpile function. The defualt is set to the global constant `TRANSPILE_KWARGS`. Returns: (Dict[str, Union[GroverConstraintsOperator, QuantumCircuit, Dict[str, List[int]]]]): - 'operator' (GroverConstraintsOperator):the high-level blocks operator. - 'decomposed_operator' (QuantumCircuit): decomposed to building-blocks operator. * For annotations regarding the decomposition method see the `circuit_decomposition` module. - 'transpiled_operator' (QuantumCircuit): the transpiled operator. *** The high-level operator and the decomposed operator are generated with barriers between constraints as default for visualizations purposes. The barriers are stripped off before transpiling so the the transpiled operator object contains no barriers. *** - 'high_level_to_bit_indexes_map' (Optional[Dict[str, List[int]]] = None): A map of high-level variables with their allocated bit-indexes in the input register. """ print() print( "The system synthesizes and transpiles a Grover's " "operator for the given constraints. Please wait.." ) if transpile_kwargs is None: transpile_kwargs = TRANSPILE_KWARGS self.transpile_kwargs = transpile_kwargs operator = GroverConstraintsOperator( self.parsed_constraints, self.num_input_qubits, insert_barriers=True ) decomposed_operator = decompose_operator(operator) no_baerriers_operator = RemoveBarriers()(operator) transpiled_operator = transpile(no_baerriers_operator, **transpile_kwargs) print("Done.") return { "operator": operator, "decomposed_operator": decomposed_operator, "transpiled_operator": transpiled_operator, "high_level_to_bit_indexes_map": self.high_to_low_map, } def save_display_grover_operator( self, obtain_grover_operator_output: Dict[str, Union[GroverConstraintsOperator, QuantumCircuit]], display: Optional[bool] = True, ) -> None: """ Handles saving and displaying data generated by the `self.obtain_grover_operator` method. Args: obtain_grover_operator_output(Dict[str, Union[GroverConstraintsOperator, QuantumCircuit]]): the dictionary returned upon calling the `self.obtain_grover_operator` method. display (Optional[bool] = True) - If true, displays objects to user's platform. """ # Creating a directory to save operator's data operator_dir_path = f"{self.dir_path}grover_operator/" os.mkdir(operator_dir_path) # Titles for displaying objects, by order of `obtain_grover_operator_output` titles = [ "The operator diagram - high level blocks:", "The operator diagram - decomposed:", f"The transpiled operator diagram saved into '{operator_dir_path}'.\n" f"It's not presented here due to its complexity.\n" f"Please note that barriers appear in the high-level diagrams above only for convenient\n" f"visual separation between constraints.\n" f"Before transpilation all barriers are removed to avoid redundant inefficiencies.", ] for index, (op_name, op_obj) in enumerate(obtain_grover_operator_output.items()): # Generic path and name for files to be saved files_path = f"{operator_dir_path}{op_name}" # Generating a circuit diagrams figure figure_path = f"{files_path}.pdf" op_obj.draw("mpl", filename=figure_path, fold=-1) # Generating a QPY serialization file for the circuit object qpy_file_path = f"{files_path}.qpy" with open(qpy_file_path, "wb") as qpy_file: qpy.dump(op_obj, qpy_file) # Original high-level operator and decomposed operator if index < 2 and display: # Displaying to user self.output_to_platform( title=titles[index], output_terminal=op_obj.draw("text"), output_jupyter=figure_path ) # Transpiled operator elif index == 2: # Output to user, not including the circuit diagram print() print(titles[index]) print() print(f"The transpilation kwargs are: {self.transpile_kwargs}.") transpiled_operator_depth = op_obj.depth() transpiled_operator_gates_count = op_obj.count_ops() print(f"Transpiled operator depth: {transpiled_operator_depth}.") print(f"Transpiled operator gates count: {transpiled_operator_gates_count}.") print(f"Total number of qubits: {op_obj.num_qubits}.") # Generating QASM 2.0 file only for the (flattened = no registers) tranpsiled operator qasm_file_path = f"{files_path}.qasm" flatten_circuit(op_obj).qasm(filename=qasm_file_path) # Index 3 is 'high_level_to_bit_indexes_map' so it's time to break from the loop break # Mapping from high-level variables to bit-indexes will be displayed as well mapping = obtain_grover_operator_output["high_level_to_bit_indexes_map"] if mapping: print() print(f"The high-level variables mapping to bit-indexes:\n{mapping}") print() print( f"Saved into '{operator_dir_path}':\n", " Circuit diagrams for all levels.\n", " QPY serialization exports for all levels.\n", " QASM 2.0 export only for the transpiled level.", ) with open(f"{operator_dir_path}operator.qpy", "rb") as qpy_file: operator_qpy_sha256 = sha256(qpy_file.read()).hexdigest() self.update_metadata( { "high_level_to_bit_indexes_map": self.high_to_low_map, "transpile_kwargs": self.transpile_kwargs, "transpiled_operator_depth": transpiled_operator_depth, "transpiled_operator_gates_count": transpiled_operator_gates_count, "operator_qpy_sha256": operator_qpy_sha256, } ) def obtain_overall_sat_circuit( self, grover_operator: GroverConstraintsOperator, solutions_num: int, backend: Optional[Backend] = None, ) -> Dict[str, SATCircuit]: """ Obtains the suitable `SATCircuit` object (= the overall SAT circuit) for the SAT problem. Args: grover_operator (GroverConstraintsOperator): Grover's operator for the SAT problem. solutions_num (int): number of solutions for the SAT problem. In the case the number of solutions is unknown, specific negative values are accepted: * '-1' - for launching a classical iterative stochastic process that finds an adequate number of iterations - by calling the `find_iterations_unknown` function (see its docstrings for more information). * '-2' - for generating a dynamic circuit that iterates over Grover's iterator until a solution is obtained, using weak measurements. TODO - this feature isn't ready yet. backend (Optional[Backend] = None): in the case of a '-1' value given to `solutions_num`, a backend object to execute the depicted iterative prcess upon should be provided. Returns: (Dict[str, SATCircuit]): - 'circuit' key for the overall SAT circuit. - 'concise_circuit' key for the overall SAT circuit, with only 1 iteration over Grover's iterator (operator + diffuser). Useful for visualization purposes. *** The concise circuit is generated with barriers between segments as default for visualizations purposes. In the actual circuit there no barriers. *** """ # -1 = Unknown number of solutions - iterative stochastic process print() if solutions_num == -1: assert backend is not None, "Need to specify a backend if `solutions_num == -1`." print("Please wait while the system checks various solutions..") circuit, iterations = find_iterations_unknown( self.num_input_qubits, grover_operator, self.parsed_constraints, precision=10, backend=backend, ) print() print(f"An adequate number of iterations found = {iterations}.") # -2 = Unknown number of solutions - implement a dynamic circuit # TODO this feature isn't fully implemented yet elif solutions_num == -2: print("The system builds a dynamic circuit..") circuit = SATCircuit(self.num_input_qubits, grover_operator, iterations=None) circuit.add_input_reg_measurement() iterations = None # Known number of solutions else: print("The system builds the overall circuit..") iterations = calc_iterations(self.num_input_qubits, solutions_num) print(f"\nFor {solutions_num} solutions, {iterations} iterations needed.") circuit = SATCircuit( self.num_input_qubits, grover_operator, iterations, insert_barriers=False ) circuit.add_input_reg_measurement() self.iterations = iterations # Obtaining a SATCircuit object with one iteration for concise representation concise_circuit = SATCircuit( self.num_input_qubits, grover_operator, iterations=1, insert_barriers=True ) concise_circuit.add_input_reg_measurement() return {"circuit": circuit, "concise_circuit": concise_circuit} def save_display_overall_circuit( self, obtain_overall_sat_circuit_output: Dict[str, SATCircuit], display: Optional[bool] = True ) -> None: """ Handles saving and displaying data generated by the `self.obtain_overall_sat_circuit` method. Args: obtain_overall_sat_circuit_output(Dict[str, SATCircuit]): the dictionary returned upon calling the `self.obtain_overall_sat_circuit` method. display (Optional[bool] = True) - If true, displays objects to user's platform. """ circuit = obtain_overall_sat_circuit_output["circuit"] concise_circuit = obtain_overall_sat_circuit_output["concise_circuit"] # Creating a directory to save overall circuit's data overall_circuit_dir_path = f"{self.dir_path}overall_circuit/" os.mkdir(overall_circuit_dir_path) # Generating a figure of the overall SAT circuit with just 1 iteration (i.e "concise") concise_circuit_fig_path = f"{overall_circuit_dir_path}overall_circuit_1_iteration.pdf" concise_circuit.draw("mpl", filename=concise_circuit_fig_path, fold=-1) # Displaying the concise circuit to user if display: if self.iterations: self.output_to_platform( title=( f"The high level circuit contains {self.iterations}" f" iterations of the following form:" ), output_terminal=concise_circuit.draw("text"), output_jupyter=concise_circuit_fig_path, ) # Dynamic circuit case - TODO NOT FULLY IMPLEMENTED YET else: dynamic_circuit_fig_path = f"{overall_circuit_dir_path}overall_circuit_dynamic.pdf" circuit.draw("mpl", filename=dynamic_circuit_fig_path, fold=-1) self.output_to_platform( title="The dynamic circuit diagram:", output_terminal=circuit.draw("text"), output_jupyter=dynamic_circuit_fig_path, ) if self.iterations: transpiled_overall_circuit = transpile(flatten_circuit(circuit), **self.transpile_kwargs) print() print(f"The transpilation kwargs are: {self.transpile_kwargs}.") transpiled_overall_circuit_depth = transpiled_overall_circuit.depth() transpiled_overall_circuit_gates_count = transpiled_overall_circuit.count_ops() print(f"Transpiled overall-circuit depth: {transpiled_overall_circuit_depth}.") print(f"Transpiled overall-circuit gates count: {transpiled_overall_circuit_gates_count}.") print(f"Total number of qubits: {transpiled_overall_circuit.num_qubits}.") print() print("Exporting the full overall SAT circuit object..") export_files_path = f"{overall_circuit_dir_path}overall_circuit" with open(f"{export_files_path}.qpy", "wb") as qpy_file: qpy.dump(circuit, qpy_file) if self.iterations: transpiled_overall_circuit.qasm(filename=f"{export_files_path}.qasm") print() print( f"Saved into '{overall_circuit_dir_path}':\n", " A concised (1 iteration) circuit diagram of the high-level overall SAT circuit.\n", " QPY serialization export for the full overall SAT circuit object.", ) if self.iterations: print(" QASM 2.0 export for the transpiled full overall SAT circuit object.") metadata_update = { "num_total_qubits": circuit.num_qubits, "num_iterations": circuit.iterations, } if self.iterations: metadata_update["transpiled_overall_circuit_depth"] = (transpiled_overall_circuit_depth,) metadata_update[ "transpiled_overall_circuit_gates_count" ] = transpiled_overall_circuit_gates_count self.update_metadata(metadata_update) @timer_dec("Circuit simulation execution time = ") def run_overall_sat_circuit( self, circuit: QuantumCircuit, backend: Backend, shots: int ) -> Dict[str, Union[Counts, List[Tuple[Union[str, int]]], List[str], List[Dict[str, int]]]]: """ Executes a `circuit` on `backend` transpiled w.r.t backend, `shots` times. Args: circuit (QuantumCircuit): `QuantumCircuit` object or child-object (a.k.a `SATCircuit`) to execute. backend (Backend): backend to execute `circuit` upon. shots (int): number of execution shots. Returns: (Dict[str, Union[Counts, List[Tuple[Union[str, int]]], List[str], List[Dict[str, int]]]]): dict object returned by `self.parse_counts` - see this method's docstrings for annotations. """ # Defines also instance attributes to use in other methods self.backend = backend self.shots = shots print() print(f"The system is running the circuit {shots} times on {backend}, please wait..") print("This process might take a while.") job = backend.run(transpile(circuit, backend), shots=shots) counts = job.result().get_counts() print("Done.") parsed_counts = self.parse_counts(counts) return parsed_counts def parse_counts( self, counts: Counts ) -> Dict[str, Union[Counts, List[Tuple[Union[str, int]]], List[str], List[Dict[str, int]]]]: """ Parses a `Counts` object into several desired datas (see 'Returns' section). Args: counts (Counts): the `Counts` object to parse. Returns: (Dict[str, Union[Counts, List[Tuple[Union[str, int]]], List[str], List[Dict[str, int]]]]): 'counts' (Counts) - the original `Counts` object. 'counts_sorted' (List[Tuple[Union[str, int]]]) - results sorted in a descending order. 'distilled_solutions' (List[str]): list of solutions (bitstrings). 'high_level_vars_values' (List[Dict[str, int]]): list of solutions (each solution is a dictionary with variable-names as keys and their integer values as values). """ # Sorting results in an a descending order counts_sorted = sorted(counts.items(), key=lambda x: x[1], reverse=True) # Generating a set of distilled verified-only solutions verifier = ClassicalVerifier(self.parsed_constraints) distilled_solutions = set() for count_item in counts_sorted: if not verifier.verify(count_item[0]): break distilled_solutions.add(count_item[0]) # In the case of high-level format in use, translating `distilled_solutions` into integer values high_level_vars_values = None if self.high_level_constraints_string and self.high_level_vars: # Container for dictionaries with variables integer values high_level_vars_values = [] for solution in distilled_solutions: # Keys are variable-names and values are their integer values solution_vars = {} for var, bits_bundle in self.high_to_low_map.items(): reversed_solution = solution[::-1] var_bitstring = "" for bit_index in bits_bundle: var_bitstring += reversed_solution[bit_index] # Translating to integer value solution_vars[var] = int(var_bitstring, 2) high_level_vars_values.append(solution_vars) return { "counts": counts, "counts_sorted": counts_sorted, "distilled_solutions": distilled_solutions, "high_level_vars_values": high_level_vars_values, } def save_display_results( self, run_overall_sat_circuit_output: Dict[ str, Union[Counts, List[Tuple[Union[str, int]]], List[str], List[Dict[str, int]]] ], display: Optional[bool] = True, ) -> None: """ Handles saving and displaying data generated by the `self.run_overall_sat_circuit` method. Args: run_overall_sat_circuit_output (Dict[str, Union[Counts, List[Tuple[Union[str, int]]], List[str], List[Dict[str, int]]]]): the dictionary returned upon calling the `self.run_overall_sat_circuit` method. display (Optional[bool] = True) - If true, displays objects to user's platform. """ counts = run_overall_sat_circuit_output["counts"] counts_sorted = run_overall_sat_circuit_output["counts_sorted"] distilled_solutions = run_overall_sat_circuit_output["distilled_solutions"] high_level_vars_values = run_overall_sat_circuit_output["high_level_vars_values"] # Creating a directory to save results data results_dir_path = f"{self.dir_path}results/" os.mkdir(results_dir_path) # Defining custom dimensions for the custom `plot_histogram` of this package histogram_fig_width = max((len(counts) * self.num_input_qubits * (10 / 72)), 7) histogram_fig_height = 5 histogram_figsize = (histogram_fig_width, histogram_fig_height) histogram_path = f"{results_dir_path}histogram.pdf" plot_histogram(counts, figsize=histogram_figsize, sort="value_desc", filename=histogram_path) if display: # Basic output text output_text = ( f"All counts:\n{counts_sorted}\n" f"\nDistilled solutions ({len(distilled_solutions)} total):\n" f"{distilled_solutions}" ) # Additional outputs for a high-level constraints format if high_level_vars_values: # Mapping from high-level variables to bit-indexes will be displayed as well output_text += ( f"\n\nThe high-level variables mapping to bit-indexes:" f"\n{self.high_to_low_map}" ) # Actual integer solutions will be displayed as well additional_text = "" for solution_index, solution in enumerate(high_level_vars_values): additional_text += f"Solution {solution_index + 1}: " for var_index, (var, value) in enumerate(solution.items()): additional_text += f"{var} = {value}" if var_index != len(solution) - 1: additional_text += ", " else: additional_text += "\n" output_text += f"\n\nHigh-level format solutions: \n{additional_text}" self.output_to_platform( title=f"The results for {self.shots} shots are:", output_terminal=output_text, output_jupyter=histogram_path, display_both_on_jupyter=True, ) results_dict = { "high_level_to_bit_indexes_map": self.high_to_low_map, "solutions": list(distilled_solutions), "high_level_solutions": high_level_vars_values, "counts": counts_sorted, } with open(f"{results_dir_path}results.json", "w") as results_file: json.dump(results_dict, results_file, indent=4) self.update_metadata( { "num_solutions": len(distilled_solutions), "backend": str(self.backend), "shots": self.shots, } )
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
from qiskit import * from oracle_generation import generate_oracle get_bin = lambda x, n: format(x, 'b').zfill(n) def gen_circuits(min,max,size): circuits = [] secrets = [] ORACLE_SIZE = size for i in range(min,max+1): cur_str = get_bin(i,ORACLE_SIZE-1) (circuit, secret) = generate_oracle(ORACLE_SIZE,False,3,cur_str) circuits.append(circuit) secrets.append(secret) return (circuits, secrets)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# 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. """A collection of discrete probability metrics.""" from __future__ import annotations import numpy as np def hellinger_distance(dist_p: dict, dist_q: dict) -> float: """Computes the Hellinger distance between two counts distributions. Parameters: dist_p (dict): First dict of counts. dist_q (dict): Second dict of counts. Returns: float: Distance References: `Hellinger Distance @ wikipedia <https://en.wikipedia.org/wiki/Hellinger_distance>`_ """ p_sum = sum(dist_p.values()) q_sum = sum(dist_q.values()) p_normed = {} for key, val in dist_p.items(): p_normed[key] = val / p_sum q_normed = {} for key, val in dist_q.items(): q_normed[key] = val / q_sum total = 0 for key, val in p_normed.items(): if key in q_normed: total += (np.sqrt(val) - np.sqrt(q_normed[key])) ** 2 del q_normed[key] else: total += val total += sum(q_normed.values()) dist = np.sqrt(total) / np.sqrt(2) return dist def hellinger_fidelity(dist_p: dict, dist_q: dict) -> float: """Computes the Hellinger fidelity between two counts distributions. The fidelity is defined as :math:`\\left(1-H^{2}\\right)^{2}` where H is the Hellinger distance. This value is bounded in the range [0, 1]. This is equivalent to the standard classical fidelity :math:`F(Q,P)=\\left(\\sum_{i}\\sqrt{p_{i}q_{i}}\\right)^{2}` that in turn is equal to the quantum state fidelity for diagonal density matrices. Parameters: dist_p (dict): First dict of counts. dist_q (dict): Second dict of counts. Returns: float: Fidelity Example: .. code-block:: from qiskit import QuantumCircuit, execute, BasicAer from qiskit.quantum_info.analysis import hellinger_fidelity qc = QuantumCircuit(5, 5) qc.h(2) qc.cx(2, 1) qc.cx(2, 3) qc.cx(3, 4) qc.cx(1, 0) qc.measure(range(5), range(5)) sim = BasicAer.get_backend('qasm_simulator') res1 = execute(qc, sim).result() res2 = execute(qc, sim).result() hellinger_fidelity(res1.get_counts(), res2.get_counts()) References: `Quantum Fidelity @ wikipedia <https://en.wikipedia.org/wiki/Fidelity_of_quantum_states>`_ `Hellinger Distance @ wikipedia <https://en.wikipedia.org/wiki/Hellinger_distance>`_ """ dist = hellinger_distance(dist_p, dist_q) return (1 - dist**2) ** 2
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2019, 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. """ CNOTDihedral operator class. """ from __future__ import annotations import itertools import numpy as np from qiskit.exceptions import QiskitError from qiskit.quantum_info.operators.base_operator import BaseOperator from qiskit.quantum_info.operators.operator import Operator from qiskit.quantum_info.operators.symplectic.pauli import Pauli from qiskit.quantum_info.operators.scalar_op import ScalarOp from qiskit.quantum_info.operators.mixins import generate_apidocs, AdjointMixin from qiskit.circuit import QuantumCircuit, Instruction from .dihedral_circuits import _append_circuit from .polynomial import SpecialPolynomial class CNOTDihedral(BaseOperator, AdjointMixin): """An N-qubit operator from the CNOT-Dihedral group. The CNOT-Dihedral group is generated by the quantum gates, :class:`~qiskit.circuit.library.CXGate`, :class:`~qiskit.circuit.library.TGate`, and :class:`~qiskit.circuit.library.XGate`. **Representation** An :math:`N`-qubit CNOT-Dihedral operator is stored as an affine function and a phase polynomial, based on the convention in references [1, 2]. The affine function consists of an :math:`N \\times N` invertible binary matrix, and an :math:`N` binary vector. The phase polynomial is a polynomial of degree at most 3, in :math:`N` variables, whose coefficients are in the ring Z_8 with 8 elements. .. code-block:: from qiskit import QuantumCircuit from qiskit.quantum_info import CNOTDihedral circ = QuantumCircuit(3) circ.cx(0, 1) circ.x(2) circ.t(1) circ.t(1) circ.t(1) elem = CNOTDihedral(circ) # Print the CNOTDihedral element print(elem) .. parsed-literal:: phase polynomial = 0 + 3*x_0 + 3*x_1 + 2*x_0*x_1 affine function = (x_0,x_0 + x_1,x_2 + 1) **Circuit Conversion** CNOTDihedral operators can be initialized from circuits containing *only* the following gates: :class:`~qiskit.circuit.library.IGate`, :class:`~qiskit.circuit.library.XGate`, :class:`~qiskit.circuit.library.YGate`, :class:`~qiskit.circuit.library.ZGate`, :class:`~qiskit.circuit.library.TGate`, :class:`~qiskit.circuit.library.TdgGate` :class:`~qiskit.circuit.library.SGate`, :class:`~qiskit.circuit.library.SdgGate`, :class:`~qiskit.circuit.library.CXGate`, :class:`~qiskit.circuit.library.CZGate`, :class:`~qiskit.circuit.library.CSGate`, :class:`~qiskit.circuit.library.CSdgGate`, :class:`~qiskit.circuit.library.SwapGate`, :class:`~qiskit.circuit.library.CCZGate`. They can be converted back into a :class:`~qiskit.circuit.QuantumCircuit`, or :class:`~qiskit.circuit.Gate` object using the :meth:`~CNOTDihedral.to_circuit` or :meth:`~CNOTDihderal.to_instruction` methods respectively. Note that this decomposition is not necessarily optimal in terms of number of gates if the number of qubits is more than two. CNOTDihedral operators can also be converted to :class:`~qiskit.quantum_info.Operator` objects using the :meth:`to_operator` method. This is done via decomposing to a circuit, and then simulating the circuit as a unitary operator. References: 1. Shelly Garion and Andrew W. Cross, *Synthesis of CNOT-Dihedral circuits with optimal number of two qubit gates*, `Quantum 4(369), 2020 <https://quantum-journal.org/papers/q-2020-12-07-369/>`_ 2. Andrew W. Cross, Easwar Magesan, Lev S. Bishop, John A. Smolin and Jay M. Gambetta, *Scalable randomised benchmarking of non-Clifford gates*, npj Quantum Inf 2, 16012 (2016). """ def __init__( self, data: CNOTDihedral | QuantumCircuit | Instruction | None = None, num_qubits: int | None = None, validate: bool = True, ): """Initialize a CNOTDihedral operator object. Args: data (CNOTDihedral or QuantumCircuit or ~qiskit.circuit.Instruction): Optional, operator to initialize. num_qubits (int): Optional, initialize an empty CNOTDihedral operator. validate (bool): if True, validates the CNOTDihedral element. Raises: QiskitError: if the type is invalid. QiskitError: if validate=True and the CNOTDihedral element is invalid. """ if num_qubits: # initialize n-qubit identity self._num_qubits = num_qubits # phase polynomial self.poly = SpecialPolynomial(self._num_qubits) # n x n invertible matrix over Z_2 self.linear = np.eye(self._num_qubits, dtype=np.int8) # binary shift, n coefficients in Z_2 self.shift = np.zeros(self._num_qubits, dtype=np.int8) # Initialize from another CNOTDihedral by sharing the underlying # poly, linear and shift elif isinstance(data, CNOTDihedral): self.linear = data.linear self.shift = data.shift self.poly = data.poly # Initialize from ScalarOp as N-qubit identity discarding any global phase elif isinstance(data, ScalarOp): if not data.is_unitary() or set(data._input_dims) != {2} or data.num_qubits is None: raise QiskitError("Can only initialize from N-qubit identity ScalarOp.") self._num_qubits = data.num_qubits # phase polynomial self.poly = SpecialPolynomial(self._num_qubits) # n x n invertible matrix over Z_2 self.linear = np.eye(self._num_qubits, dtype=np.int8) # binary shift, n coefficients in Z_2 self.shift = np.zeros(self._num_qubits, dtype=np.int8) # Initialize from a QuantumCircuit or Instruction object elif isinstance(data, (QuantumCircuit, Instruction)): self._num_qubits = data.num_qubits elem = self._from_circuit(data) self.poly = elem.poly self.linear = elem.linear self.shift = elem.shift elif isinstance(data, Pauli): self._num_qubits = data.num_qubits elem = self._from_circuit(data.to_instruction()) self.poly = elem.poly self.linear = elem.linear self.shift = elem.shift else: raise QiskitError("Invalid input type for CNOTDihedral class.") # Initialize BaseOperator super().__init__(num_qubits=self._num_qubits) # Validate the CNOTDihedral element if validate and not self._is_valid(): raise QiskitError("Invalid CNOTDihedral element.") @property def name(self): """Unique string identifier for operation type.""" return "cnotdihedral" @property def num_clbits(self): """Number of classical bits.""" return 0 def _z2matmul(self, left, right): """Compute product of two n x n z2 matrices.""" prod = np.mod(np.dot(left, right), 2) return prod def _z2matvecmul(self, mat, vec): """Compute mat*vec of n x n z2 matrix and vector.""" prod = np.mod(np.dot(mat, vec), 2) return prod def _dot(self, other): """Left multiplication self * other.""" if self.num_qubits != other.num_qubits: raise QiskitError("Multiplication on different number of qubits.") result = CNOTDihedral(num_qubits=self.num_qubits) result.shift = [ (x[0] + x[1]) % 2 for x in zip(self._z2matvecmul(self.linear, other.shift), self.shift) ] result.linear = self._z2matmul(self.linear, other.linear) # Compute x' = B1*x + c1 using the p_j identity new_vars = [] for i in range(self.num_qubits): support = np.arange(self.num_qubits)[np.nonzero(other.linear[i])] poly = SpecialPolynomial(self.num_qubits) poly.set_pj(support) if other.shift[i] == 1: poly = -1 * poly poly.weight_0 = (poly.weight_0 + 1) % 8 new_vars.append(poly) # p' = p1 + p2(x') result.poly = other.poly + self.poly.evaluate(new_vars) return result def _compose(self, other): """Right multiplication other * self.""" if self.num_qubits != other.num_qubits: raise QiskitError("Multiplication on different number of qubits.") result = CNOTDihedral(num_qubits=self.num_qubits) result.shift = [ (x[0] + x[1]) % 2 for x in zip(self._z2matvecmul(other.linear, self.shift), other.shift) ] result.linear = self._z2matmul(other.linear, self.linear) # Compute x' = B1*x + c1 using the p_j identity new_vars = [] for i in range(self.num_qubits): support = np.arange(other.num_qubits)[np.nonzero(self.linear[i])] poly = SpecialPolynomial(self.num_qubits) poly.set_pj(support) if self.shift[i] == 1: poly = -1 * poly poly.weight_0 = (poly.weight_0 + 1) % 8 new_vars.append(poly) # p' = p1 + p2(x') result.poly = self.poly + other.poly.evaluate(new_vars) return result def __eq__(self, other): """Test equality.""" return ( isinstance(other, CNOTDihedral) and self.poly == other.poly and (self.linear == other.linear).all() and (self.shift == other.shift).all() ) def _append_cx(self, i, j): """Apply a CX gate to this element. Left multiply the element by CX(i, j). """ if not 0 <= i < self.num_qubits or not 0 <= j < self.num_qubits: raise QiskitError("CX qubits are out of bounds.") self.linear[j] = (self.linear[i] + self.linear[j]) % 2 self.shift[j] = (self.shift[i] + self.shift[j]) % 2 def _append_phase(self, k, i): """Apply an k-th power of T to this element. Left multiply the element by T_i^k. """ if not 0 <= i < self.num_qubits: raise QiskitError("phase qubit out of bounds.") # If the kth bit is flipped, conjugate this gate if self.shift[i] == 1: k = (7 * k) % 8 # Take all subsets \alpha of the support of row i # of weight up to 3 and add k*(-2)**(|\alpha| - 1) mod 8 # to the corresponding term. support = np.arange(self.num_qubits)[np.nonzero(self.linear[i])] subsets_2 = itertools.combinations(support, 2) subsets_3 = itertools.combinations(support, 3) for j in support: value = self.poly.get_term([j]) self.poly.set_term([j], (value + k) % 8) for j in subsets_2: value = self.poly.get_term(list(j)) self.poly.set_term(list(j), (value + -2 * k) % 8) for j in subsets_3: value = self.poly.get_term(list(j)) self.poly.set_term(list(j), (value + 4 * k) % 8) def _append_x(self, i): """Apply X to this element. Left multiply the element by X(i). """ if not 0 <= i < self.num_qubits: raise QiskitError("X qubit out of bounds.") self.shift[i] = (self.shift[i] + 1) % 2 def __str__(self): """Return formatted string representation.""" out = "phase polynomial = \n" out += str(self.poly) out += "\naffine function = \n" out += " (" for row in range(self.num_qubits): wrote = False for col in range(self.num_qubits): if self.linear[row][col] != 0: if wrote: out += " + x_" + str(col) else: out += "x_" + str(col) wrote = True if self.shift[row] != 0: out += " + 1" if row != self.num_qubits - 1: out += "," out += ")\n" return out def to_circuit(self): """Return a QuantumCircuit implementing the CNOT-Dihedral element. Return: QuantumCircuit: a circuit implementation of the CNOTDihedral object. References: 1. Shelly Garion and Andrew W. Cross, *Synthesis of CNOT-Dihedral circuits with optimal number of two qubit gates*, `Quantum 4(369), 2020 <https://quantum-journal.org/papers/q-2020-12-07-369/>`_ 2. Andrew W. Cross, Easwar Magesan, Lev S. Bishop, John A. Smolin and Jay M. Gambetta, *Scalable randomised benchmarking of non-Clifford gates*, npj Quantum Inf 2, 16012 (2016). """ from qiskit.synthesis.cnotdihedral import synth_cnotdihedral_full return synth_cnotdihedral_full(self) def to_instruction(self): """Return a Gate instruction implementing the CNOTDihedral object.""" return self.to_circuit().to_gate() def _from_circuit(self, circuit): """Initialize from a QuantumCircuit or Instruction. Args: circuit (QuantumCircuit or ~qiskit.circuit.Instruction): instruction to initialize. Returns: CNOTDihedral: the CNOTDihedral object for the circuit. Raises: QiskitError: if the input instruction is not CNOTDihedral or contains classical register instruction. """ if not isinstance(circuit, (QuantumCircuit, Instruction)): raise QiskitError("Input must be a QuantumCircuit or Instruction") # Initialize an identity CNOTDihedral object elem = CNOTDihedral(num_qubits=self._num_qubits) _append_circuit(elem, circuit) return elem def __array__(self, dtype=None): if dtype: return np.asarray(self.to_matrix(), dtype=dtype) return self.to_matrix() def to_matrix(self): """Convert operator to Numpy matrix.""" return self.to_operator().data def to_operator(self) -> Operator: """Convert to an Operator object.""" return Operator(self.to_instruction()) def compose( self, other: CNOTDihedral, qargs: list | None = None, front: bool = False ) -> CNOTDihedral: if qargs is not None: raise NotImplementedError("compose method does not support qargs.") if self.num_qubits != other.num_qubits: raise QiskitError("Incompatible dimension for composition") if front: other = self._dot(other) else: other = self._compose(other) other.poly.weight_0 = 0 # set global phase return other def _tensor(self, other, reverse=False): """Returns the tensor product operator.""" if not isinstance(other, CNOTDihedral): raise QiskitError("Tensored element is not a CNOTDihderal object.") if reverse: elem0 = self elem1 = other else: elem0 = other elem1 = self result = CNOTDihedral(num_qubits=elem0.num_qubits + elem1.num_qubits) linear = np.block( [ [elem0.linear, np.zeros((elem0.num_qubits, elem1.num_qubits), dtype=np.int8)], [np.zeros((elem1.num_qubits, elem0.num_qubits), dtype=np.int8), elem1.linear], ] ) result.linear = linear shift = np.block([elem0.shift, elem1.shift]) result.shift = shift for i in range(elem0.num_qubits): value = elem0.poly.get_term([i]) result.poly.set_term([i], value) for j in range(i): value = elem0.poly.get_term([j, i]) result.poly.set_term([j, i], value) for k in range(j): value = elem0.poly.get_term([k, j, i]) result.poly.set_term([k, j, i], value) for i in range(elem1.num_qubits): value = elem1.poly.get_term([i]) result.poly.set_term([i + elem0.num_qubits], value) for j in range(i): value = elem1.poly.get_term([j, i]) result.poly.set_term([j + elem0.num_qubits, i + elem0.num_qubits], value) for k in range(j): value = elem1.poly.get_term([k, j, i]) result.poly.set_term( [k + elem0.num_qubits, j + elem0.num_qubits, i + elem0.num_qubits], value ) return result def tensor(self, other: CNOTDihedral) -> CNOTDihedral: return self._tensor(other, reverse=True) def expand(self, other: CNOTDihedral) -> CNOTDihedral: return self._tensor(other, reverse=False) def adjoint(self): circ = self.to_instruction() result = self._from_circuit(circ.inverse()) return result def conjugate(self): circ = self.to_instruction() new_circ = QuantumCircuit(self.num_qubits) bit_indices = {bit: index for index, bit in enumerate(circ.definition.qubits)} for instruction in circ.definition: new_qubits = [bit_indices[tup] for tup in instruction.qubits] if instruction.operation.name == "p": params = 2 * np.pi - instruction.operation.params[0] instruction.operation.params[0] = params new_circ.append(instruction.operation, new_qubits) elif instruction.operation.name == "t": instruction.operation.name = "tdg" new_circ.append(instruction.operation, new_qubits) elif instruction.operation.name == "tdg": instruction.operation.name = "t" new_circ.append(instruction.operation, new_qubits) elif instruction.operation.name == "s": instruction.operation.name = "sdg" new_circ.append(instruction.operation, new_qubits) elif instruction.operation.name == "sdg": instruction.operation.name = "s" new_circ.append(instruction.operation, new_qubits) else: new_circ.append(instruction.operation, new_qubits) result = self._from_circuit(new_circ) return result def transpose(self): circ = self.to_instruction() result = self._from_circuit(circ.reverse_ops()) return result def _is_valid(self): """Return True if input is a CNOTDihedral element.""" if ( self.poly.weight_0 != 0 or len(self.poly.weight_1) != self.num_qubits or len(self.poly.weight_2) != int(self.num_qubits * (self.num_qubits - 1) / 2) or len(self.poly.weight_3) != int(self.num_qubits * (self.num_qubits - 1) * (self.num_qubits - 2) / 6) ): return False if ( (self.linear).shape != (self.num_qubits, self.num_qubits) or len(self.shift) != self.num_qubits or not np.allclose((np.linalg.det(self.linear) % 2), 1) ): return False if ( not (set(self.poly.weight_1.flatten())).issubset({0, 1, 2, 3, 4, 5, 6, 7}) or not (set(self.poly.weight_2.flatten())).issubset({0, 2, 4, 6}) or not (set(self.poly.weight_3.flatten())).issubset({0, 4}) ): return False if not (set(self.shift.flatten())).issubset({0, 1}) or not ( set(self.linear.flatten()) ).issubset({0, 1}): return False return True # Update docstrings for API docs generate_apidocs(CNOTDihedral)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017--2023 # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Clifford operator class. """ from __future__ import annotations import functools import itertools import re from typing import Literal import numpy as np from qiskit.circuit import Instruction, QuantumCircuit from qiskit.circuit.library.standard_gates import HGate, IGate, SGate, XGate, YGate, ZGate from qiskit.circuit.operation import Operation from qiskit.exceptions import QiskitError from qiskit.quantum_info.operators.base_operator import BaseOperator from qiskit.quantum_info.operators.mixins import AdjointMixin, generate_apidocs from qiskit.quantum_info.operators.operator import Operator from qiskit.quantum_info.operators.scalar_op import ScalarOp from qiskit.quantum_info.operators.symplectic.base_pauli import _count_y from qiskit.utils.deprecation import deprecate_func from qiskit.synthesis.linear import calc_inverse_matrix from .base_pauli import BasePauli from .clifford_circuits import _append_circuit, _append_operation from .stabilizer_table import StabilizerTable class Clifford(BaseOperator, AdjointMixin, Operation): """An N-qubit unitary operator from the Clifford group. **Representation** An *N*-qubit Clifford operator is stored as a length *2N × (2N+1)* boolean tableau using the convention from reference [1]. * Rows 0 to *N-1* are the *destabilizer* group generators * Rows *N* to *2N-1* are the *stabilizer* group generators. The internal boolean tableau for the Clifford can be accessed using the :attr:`tableau` attribute. The destabilizer or stabilizer rows can each be accessed as a length-N Stabilizer table using :attr:`destab` and :attr:`stab` attributes. A more easily human readable representation of the Clifford operator can be obtained by calling the :meth:`to_dict` method. This representation is also used if a Clifford object is printed as in the following example .. code-block:: from qiskit import QuantumCircuit from qiskit.quantum_info import Clifford # Bell state generation circuit qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) cliff = Clifford(qc) # Print the Clifford print(cliff) # Print the Clifford destabilizer rows print(cliff.to_labels(mode="D")) # Print the Clifford stabilizer rows print(cliff.to_labels(mode="S")) .. parsed-literal:: Clifford: Stabilizer = ['+XX', '+ZZ'], Destabilizer = ['+IZ', '+XI'] ['+IZ', '+XI'] ['+XX', '+ZZ'] **Circuit Conversion** Clifford operators can be initialized from circuits containing *only* the following Clifford gates: :class:`~qiskit.circuit.library.IGate`, :class:`~qiskit.circuit.library.XGate`, :class:`~qiskit.circuit.library.YGate`, :class:`~qiskit.circuit.library.ZGate`, :class:`~qiskit.circuit.library.HGate`, :class:`~qiskit.circuit.library.SGate`, :class:`~qiskit.circuit.library.SdgGate`, :class:`~qiskit.circuit.library.SXGate`, :class:`~qiskit.circuit.library.SXdgGate`, :class:`~qiskit.circuit.library.CXGate`, :class:`~qiskit.circuit.library.CZGate`, :class:`~qiskit.circuit.library.CYGate`, :class:`~qiskit.circuit.library.DXGate`, :class:`~qiskit.circuit.library.SwapGate`, :class:`~qiskit.circuit.library.iSwapGate`, :class:`~qiskit.circuit.library.ECRGate`, :class:`~qiskit.circuit.library.LinearFunction`, :class:`~qiskit.circuit.library.PermutationGate`. They can be converted back into a :class:`~qiskit.circuit.QuantumCircuit`, or :class:`~qiskit.circuit.Gate` object using the :meth:`~Clifford.to_circuit` or :meth:`~Clifford.to_instruction` methods respectively. Note that this decomposition is not necessarily optimal in terms of number of gates. .. note:: A minimally generating set of gates for Clifford circuits is the :class:`~qiskit.circuit.library.HGate` and :class:`~qiskit.circuit.library.SGate` gate and *either* the :class:`~qiskit.circuit.library.CXGate` or :class:`~qiskit.circuit.library.CZGate` two-qubit gate. Clifford operators can also be converted to :class:`~qiskit.quantum_info.Operator` objects using the :meth:`to_operator` method. This is done via decomposing to a circuit, and then simulating the circuit as a unitary operator. References: 1. S. Aaronson, D. Gottesman, *Improved Simulation of Stabilizer Circuits*, Phys. Rev. A 70, 052328 (2004). `arXiv:quant-ph/0406196 <https://arxiv.org/abs/quant-ph/0406196>`_ """ _COMPOSE_PHASE_LOOKUP = None _COMPOSE_1Q_LOOKUP = None def __array__(self, dtype=None): if dtype: return np.asarray(self.to_matrix(), dtype=dtype) return self.to_matrix() def __init__(self, data, validate=True, copy=True): """Initialize an operator object.""" # pylint: disable=cyclic-import from qiskit.circuit.library import LinearFunction, PermutationGate # Initialize from another Clifford if isinstance(data, Clifford): num_qubits = data.num_qubits self.tableau = data.tableau.copy() if copy else data.tableau # Initialize from ScalarOp as N-qubit identity discarding any global phase elif isinstance(data, ScalarOp): if not data.num_qubits or not data.is_unitary(): raise QiskitError("Can only initialize from N-qubit identity ScalarOp.") num_qubits = data.num_qubits self.tableau = np.fromfunction( lambda i, j: i == j, (2 * num_qubits, 2 * num_qubits + 1) ).astype(bool) # Initialize from LinearFunction elif isinstance(data, LinearFunction): num_qubits = len(data.linear) self.tableau = self.from_linear_function(data) # Initialize from PermutationGate elif isinstance(data, PermutationGate): num_qubits = len(data.pattern) self.tableau = self.from_permutation(data) # Initialize from a QuantumCircuit or Instruction object elif isinstance(data, (QuantumCircuit, Instruction)): num_qubits = data.num_qubits self.tableau = Clifford.from_circuit(data).tableau # DEPRECATED: data is StabilizerTable elif isinstance(data, StabilizerTable): self.tableau = self._stack_table_phase(data.array, data.phase) num_qubits = data.num_qubits # Initialize StabilizerTable directly from the data else: if isinstance(data, (list, np.ndarray)) and np.asarray(data, dtype=bool).ndim == 2: data = np.array(data, dtype=bool, copy=copy) if data.shape[0] == data.shape[1]: self.tableau = self._stack_table_phase( data, np.zeros(data.shape[0], dtype=bool) ) num_qubits = data.shape[0] // 2 elif data.shape[0] + 1 == data.shape[1]: self.tableau = data num_qubits = data.shape[0] // 2 else: raise QiskitError("") else: n_paulis = len(data) symp = self._from_label(data[0]) num_qubits = len(symp) // 2 tableau = np.zeros((n_paulis, len(symp)), dtype=bool) tableau[0] = symp for i in range(1, n_paulis): tableau[i] = self._from_label(data[i]) self.tableau = tableau # Validate table is a symplectic matrix if validate and not Clifford._is_symplectic(self.symplectic_matrix): raise QiskitError( "Invalid Clifford. Input StabilizerTable is not a valid symplectic matrix." ) # Initialize BaseOperator super().__init__(num_qubits=num_qubits) @property def name(self): """Unique string identifier for operation type.""" return "clifford" @property def num_clbits(self): """Number of classical bits.""" return 0 def __repr__(self): return f"Clifford({repr(self.tableau)})" def __str__(self): return ( f'Clifford: Stabilizer = {self.to_labels(mode="S")}, ' f'Destabilizer = {self.to_labels(mode="D")}' ) def __eq__(self, other): """Check if two Clifford tables are equal""" return super().__eq__(other) and (self.tableau == other.tableau).all() def copy(self): return type(self)(self, validate=False, copy=True) # --------------------------------------------------------------------- # Attributes # --------------------------------------------------------------------- # pylint: disable=bad-docstring-quotes @deprecate_func( since="0.24.0", additional_msg="Instead, index or iterate through the Clifford.tableau attribute.", ) def __getitem__(self, key): """Return a stabilizer Pauli row""" return self.table.__getitem__(key) @deprecate_func(since="0.24.0", additional_msg="Use Clifford.tableau property instead.") def __setitem__(self, key, value): """Set a stabilizer Pauli row""" self.tableau.__setitem__(key, self._stack_table_phase(value.array, value.phase)) @property @deprecate_func( since="0.24.0", additional_msg="Use Clifford.stab and Clifford.destab properties instead.", is_property=True, ) def table(self): """Return StabilizerTable""" return StabilizerTable(self.symplectic_matrix, phase=self.phase) @table.setter @deprecate_func( since="0.24.0", additional_msg="Use Clifford.stab and Clifford.destab properties instead.", is_property=True, ) def table(self, value): """Set the stabilizer table""" # Note this setter cannot change the size of the Clifford # It can only replace the contents of the StabilizerTable with # another StabilizerTable of the same size. if not isinstance(value, StabilizerTable): value = StabilizerTable(value) self.symplectic_matrix = value._table._array self.phase = value._table._phase @property @deprecate_func( since="0.24.0", additional_msg="Use Clifford.stab properties instead.", is_property=True, ) def stabilizer(self): """Return the stabilizer block of the StabilizerTable.""" array = self.tableau[self.num_qubits : 2 * self.num_qubits, :-1] phase = self.tableau[self.num_qubits : 2 * self.num_qubits, -1].reshape(self.num_qubits) return StabilizerTable(array, phase) @stabilizer.setter @deprecate_func( since="0.24.0", additional_msg="Use Clifford.stab properties instead.", is_property=True, ) def stabilizer(self, value): """Set the value of stabilizer block of the StabilizerTable""" if not isinstance(value, StabilizerTable): value = StabilizerTable(value) self.tableau[self.num_qubits : 2 * self.num_qubits, :-1] = value.array @property @deprecate_func( since="0.24.0", additional_msg="Use Clifford.destab properties instead.", is_property=True, ) def destabilizer(self): """Return the destabilizer block of the StabilizerTable.""" array = self.tableau[0 : self.num_qubits, :-1] phase = self.tableau[0 : self.num_qubits, -1].reshape(self.num_qubits) return StabilizerTable(array, phase) @destabilizer.setter @deprecate_func( since="0.24.0", additional_msg="Use Clifford.destab properties instead.", is_property=True, ) def destabilizer(self, value): """Set the value of destabilizer block of the StabilizerTable""" if not isinstance(value, StabilizerTable): value = StabilizerTable(value) self.tableau[: self.num_qubits, :-1] = value.array @property def symplectic_matrix(self): """Return boolean symplectic matrix.""" return self.tableau[:, :-1] @symplectic_matrix.setter def symplectic_matrix(self, value): self.tableau[:, :-1] = value @property def phase(self): """Return phase with boolean representation.""" return self.tableau[:, -1] @phase.setter def phase(self, value): self.tableau[:, -1] = value @property def x(self): """The x array for the symplectic representation.""" return self.tableau[:, 0 : self.num_qubits] @x.setter def x(self, value): self.tableau[:, 0 : self.num_qubits] = value @property def z(self): """The z array for the symplectic representation.""" return self.tableau[:, self.num_qubits : 2 * self.num_qubits] @z.setter def z(self, value): self.tableau[:, self.num_qubits : 2 * self.num_qubits] = value @property def destab(self): """The destabilizer array for the symplectic representation.""" return self.tableau[: self.num_qubits, :] @destab.setter def destab(self, value): self.tableau[: self.num_qubits, :] = value @property def destab_x(self): """The destabilizer x array for the symplectic representation.""" return self.tableau[: self.num_qubits, : self.num_qubits] @destab_x.setter def destab_x(self, value): self.tableau[: self.num_qubits, : self.num_qubits] = value @property def destab_z(self): """The destabilizer z array for the symplectic representation.""" return self.tableau[: self.num_qubits, self.num_qubits : 2 * self.num_qubits] @destab_z.setter def destab_z(self, value): self.tableau[: self.num_qubits, self.num_qubits : 2 * self.num_qubits] = value @property def destab_phase(self): """Return phase of destabilizer with boolean representation.""" return self.tableau[: self.num_qubits, -1] @destab_phase.setter def destab_phase(self, value): self.tableau[: self.num_qubits, -1] = value @property def stab(self): """The stabilizer array for the symplectic representation.""" return self.tableau[self.num_qubits :, :] @stab.setter def stab(self, value): self.tableau[self.num_qubits :, :] = value @property def stab_x(self): """The stabilizer x array for the symplectic representation.""" return self.tableau[self.num_qubits :, : self.num_qubits] @stab_x.setter def stab_x(self, value): self.tableau[self.num_qubits :, : self.num_qubits] = value @property def stab_z(self): """The stabilizer array for the symplectic representation.""" return self.tableau[self.num_qubits :, self.num_qubits : 2 * self.num_qubits] @stab_z.setter def stab_z(self, value): self.tableau[self.num_qubits :, self.num_qubits : 2 * self.num_qubits] = value @property def stab_phase(self): """Return phase of stabilizer with boolean representation.""" return self.tableau[self.num_qubits :, -1] @stab_phase.setter def stab_phase(self, value): self.tableau[self.num_qubits :, -1] = value # --------------------------------------------------------------------- # Utility Operator methods # --------------------------------------------------------------------- def is_unitary(self): """Return True if the Clifford table is valid.""" # A valid Clifford is always unitary, so this function is really # checking that the underlying Stabilizer table array is a valid # Clifford array. return Clifford._is_symplectic(self.symplectic_matrix) # --------------------------------------------------------------------- # BaseOperator Abstract Methods # --------------------------------------------------------------------- def conjugate(self): return Clifford._conjugate_transpose(self, "C") def adjoint(self): return Clifford._conjugate_transpose(self, "A") def transpose(self): return Clifford._conjugate_transpose(self, "T") def tensor(self, other: Clifford) -> Clifford: if not isinstance(other, Clifford): other = Clifford(other) return self._tensor(self, other) def expand(self, other: Clifford) -> Clifford: if not isinstance(other, Clifford): other = Clifford(other) return self._tensor(other, self) @classmethod def _tensor(cls, a, b): n = a.num_qubits + b.num_qubits tableau = np.zeros((2 * n, 2 * n + 1), dtype=bool) clifford = cls(tableau, validate=False) clifford.destab_x[: b.num_qubits, : b.num_qubits] = b.destab_x clifford.destab_x[b.num_qubits :, b.num_qubits :] = a.destab_x clifford.destab_z[: b.num_qubits, : b.num_qubits] = b.destab_z clifford.destab_z[b.num_qubits :, b.num_qubits :] = a.destab_z clifford.stab_x[: b.num_qubits, : b.num_qubits] = b.stab_x clifford.stab_x[b.num_qubits :, b.num_qubits :] = a.stab_x clifford.stab_z[: b.num_qubits, : b.num_qubits] = b.stab_z clifford.stab_z[b.num_qubits :, b.num_qubits :] = a.stab_z clifford.phase[: b.num_qubits] = b.destab_phase clifford.phase[b.num_qubits : n] = a.destab_phase clifford.phase[n : n + b.num_qubits] = b.stab_phase clifford.phase[n + b.num_qubits :] = a.stab_phase return clifford def compose( self, other: Clifford | QuantumCircuit | Instruction, qargs: list | None = None, front: bool = False, ) -> Clifford: if qargs is None: qargs = getattr(other, "qargs", None) # If other is a QuantumCircuit we can more efficiently compose # using the _append_circuit method to update each gate recursively # to the current Clifford, rather than converting to a Clifford first # and then doing the composition of tables. if not front: if isinstance(other, QuantumCircuit): return _append_circuit(self.copy(), other, qargs=qargs) if isinstance(other, Instruction): return _append_operation(self.copy(), other, qargs=qargs) if not isinstance(other, Clifford): # Not copying is safe since we're going to drop our only reference to `other` at the end # of the function. other = Clifford(other, copy=False) # Validate compose dimensions self._op_shape.compose(other._op_shape, qargs, front) # Pad other with identities if composing on subsystem other = self._pad_with_identity(other, qargs) left, right = (self, other) if front else (other, self) if self.num_qubits == 1: return self._compose_1q(left, right) return self._compose_general(left, right) @classmethod def _compose_general(cls, first, second): # Correcting for phase due to Pauli multiplication. Start with factors of -i from XZ = -iY # on individual qubits, and then handle multiplication between each qubitwise pair. ifacts = np.sum(second.x & second.z, axis=1, dtype=int) x1, z1 = first.x.astype(np.uint8), first.z.astype(np.uint8) lookup = cls._compose_lookup() # The loop is over 2*n_qubits entries, and the entire loop is cubic in the number of qubits. for k, row2 in enumerate(second.symplectic_matrix): x1_select = x1[row2] z1_select = z1[row2] x1_accum = np.logical_xor.accumulate(x1_select, axis=0).astype(np.uint8) z1_accum = np.logical_xor.accumulate(z1_select, axis=0).astype(np.uint8) indexer = (x1_select[1:], z1_select[1:], x1_accum[:-1], z1_accum[:-1]) ifacts[k] += np.sum(lookup[indexer]) p = np.mod(ifacts, 4) // 2 phase = ( (np.matmul(second.symplectic_matrix, first.phase, dtype=int) + second.phase + p) % 2 ).astype(bool) data = cls._stack_table_phase( (np.matmul(second.symplectic_matrix, first.symplectic_matrix, dtype=int) % 2).astype( bool ), phase, ) return Clifford(data, validate=False, copy=False) @classmethod def _compose_1q(cls, first, second): # 1-qubit composition can be done with a simple lookup table; there are 24 elements in the # 1q Clifford group, so 576 possible combinations, which is small enough to look up. if cls._COMPOSE_1Q_LOOKUP is None: # The valid tables for 1q Cliffords. tables_1q = np.array( [ [[False, True], [True, False]], [[False, True], [True, True]], [[True, False], [False, True]], [[True, False], [True, True]], [[True, True], [False, True]], [[True, True], [True, False]], ] ) phases_1q = np.array([[False, False], [False, True], [True, False], [True, True]]) # Build the lookup table. cliffords = [ cls(cls._stack_table_phase(table, phase), validate=False, copy=False) for table, phase in itertools.product(tables_1q, phases_1q) ] cls._COMPOSE_1Q_LOOKUP = { (cls._hash(left), cls._hash(right)): cls._compose_general(left, right) for left, right in itertools.product(cliffords, repeat=2) } return cls._COMPOSE_1Q_LOOKUP[cls._hash(first), cls._hash(second)].copy() @classmethod def _compose_lookup( cls, ): if cls._COMPOSE_PHASE_LOOKUP is None: # A lookup table for calculating phases. The indices are # current_x, current_z, running_x_count, running_z_count # where all counts taken modulo 2. lookup = np.zeros((2, 2, 2, 2), dtype=int) lookup[0, 1, 1, 0] = lookup[1, 0, 1, 1] = lookup[1, 1, 0, 1] = -1 lookup[0, 1, 1, 1] = lookup[1, 0, 0, 1] = lookup[1, 1, 1, 0] = 1 lookup.setflags(write=False) cls._COMPOSE_PHASE_LOOKUP = lookup return cls._COMPOSE_PHASE_LOOKUP # --------------------------------------------------------------------- # Representation conversions # --------------------------------------------------------------------- def to_dict(self): """Return dictionary representation of Clifford object.""" return { "stabilizer": self.to_labels(mode="S"), "destabilizer": self.to_labels(mode="D"), } @classmethod def from_dict(cls, obj): """Load a Clifford from a dictionary""" labels = obj.get("destabilizer") + obj.get("stabilizer") n_paulis = len(labels) symp = cls._from_label(labels[0]) tableau = np.zeros((n_paulis, len(symp)), dtype=bool) tableau[0] = symp for i in range(1, n_paulis): tableau[i] = cls._from_label(labels[i]) return cls(tableau) def to_matrix(self): """Convert operator to Numpy matrix.""" return self.to_operator().data @classmethod def from_matrix(cls, matrix: np.ndarray) -> Clifford: """Create a Clifford from a unitary matrix. Note that this function takes exponentially long time w.r.t. the number of qubits. Args: matrix (np.array): A unitary matrix representing a Clifford to be converted. Returns: Clifford: the Clifford object for the unitary matrix. Raises: QiskitError: if the input is not a Clifford matrix. """ tableau = cls._unitary_matrix_to_tableau(matrix) if tableau is None: raise QiskitError("Non-Clifford matrix is not convertible") return cls(tableau) @classmethod def from_linear_function(cls, linear_function): """Create a Clifford from a Linear Function. If the linear function is represented by a nxn binary invertible matrix A, then the corresponding Clifford has symplectic matrix [[A^t, 0], [0, A^{-1}]]. Args: linear_function (LinearFunction): A linear function to be converted. Returns: Clifford: the Clifford object for this linear function. """ mat = linear_function.linear mat_t = np.transpose(mat) mat_i = calc_inverse_matrix(mat) dim = len(mat) zero = np.zeros((dim, dim), dtype=int) symplectic_mat = np.block([[mat_t, zero], [zero, mat_i]]) phase = np.zeros(2 * dim, dtype=int) tableau = cls._stack_table_phase(symplectic_mat, phase) return tableau @classmethod def from_permutation(cls, permutation_gate): """Create a Clifford from a PermutationGate. Args: permutation_gate (PermutationGate): A permutation to be converted. Returns: Clifford: the Clifford object for this permutation. """ pat = permutation_gate.pattern dim = len(pat) symplectic_mat = np.zeros((2 * dim, 2 * dim), dtype=int) for i, j in enumerate(pat): symplectic_mat[j, i] = True symplectic_mat[j + dim, i + dim] = True phase = np.zeros(2 * dim, dtype=bool) tableau = cls._stack_table_phase(symplectic_mat, phase) return tableau def to_operator(self) -> Operator: """Convert to an Operator object.""" return Operator(self.to_instruction()) @classmethod def from_operator(cls, operator: Operator) -> Clifford: """Create a Clifford from a operator. Note that this function takes exponentially long time w.r.t. the number of qubits. Args: operator (Operator): An operator representing a Clifford to be converted. Returns: Clifford: the Clifford object for the operator. Raises: QiskitError: if the input is not a Clifford operator. """ tableau = cls._unitary_matrix_to_tableau(operator.to_matrix()) if tableau is None: raise QiskitError("Non-Clifford operator is not convertible") return cls(tableau) def to_circuit(self): """Return a QuantumCircuit implementing the Clifford. For N <= 3 qubits this is based on optimal CX cost decomposition from reference [1]. For N > 3 qubits this is done using the general non-optimal compilation routine from reference [2]. Return: QuantumCircuit: a circuit implementation of the Clifford. References: 1. S. Bravyi, D. Maslov, *Hadamard-free circuits expose the structure of the Clifford group*, `arXiv:2003.09412 [quant-ph] <https://arxiv.org/abs/2003.09412>`_ 2. S. Aaronson, D. Gottesman, *Improved Simulation of Stabilizer Circuits*, Phys. Rev. A 70, 052328 (2004). `arXiv:quant-ph/0406196 <https://arxiv.org/abs/quant-ph/0406196>`_ """ from qiskit.synthesis.clifford import synth_clifford_full return synth_clifford_full(self) def to_instruction(self): """Return a Gate instruction implementing the Clifford.""" return self.to_circuit().to_gate() @staticmethod def from_circuit(circuit: QuantumCircuit | Instruction) -> Clifford: """Initialize from a QuantumCircuit or Instruction. Args: circuit (QuantumCircuit or ~qiskit.circuit.Instruction): instruction to initialize. Returns: Clifford: the Clifford object for the instruction. Raises: QiskitError: if the input instruction is non-Clifford or contains classical register instruction. """ if not isinstance(circuit, (QuantumCircuit, Instruction)): raise QiskitError("Input must be a QuantumCircuit or Instruction") # Initialize an identity Clifford clifford = Clifford(np.eye(2 * circuit.num_qubits), validate=False) if isinstance(circuit, QuantumCircuit): clifford = _append_circuit(clifford, circuit) else: clifford = _append_operation(clifford, circuit) return clifford @staticmethod def from_label(label: str) -> Clifford: """Return a tensor product of single-qubit Clifford gates. Args: label (string): single-qubit operator string. Returns: Clifford: The N-qubit Clifford operator. Raises: QiskitError: if the label contains invalid characters. Additional Information: The labels correspond to the single-qubit Cliffords are * - Label - Stabilizer - Destabilizer * - ``"I"`` - +Z - +X * - ``"X"`` - -Z - +X * - ``"Y"`` - -Z - -X * - ``"Z"`` - +Z - -X * - ``"H"`` - +X - +Z * - ``"S"`` - +Z - +Y """ # Check label is valid label_gates = { "I": IGate(), "X": XGate(), "Y": YGate(), "Z": ZGate(), "H": HGate(), "S": SGate(), } if re.match(r"^[IXYZHS\-+]+$", label) is None: raise QiskitError("Label contains invalid characters.") # Initialize an identity matrix and apply each gate num_qubits = len(label) op = Clifford(np.eye(2 * num_qubits, dtype=bool)) for qubit, char in enumerate(reversed(label)): op = _append_operation(op, label_gates[char], qargs=[qubit]) return op def to_labels(self, array: bool = False, mode: Literal["S", "D", "B"] = "B"): r"""Convert a Clifford to a list Pauli (de)stabilizer string labels. For large Clifford converting using the ``array=True`` kwarg will be more efficient since it allocates memory for the full Numpy array of labels in advance. .. list-table:: Stabilizer Representations :header-rows: 1 * - Label - Phase - Symplectic - Matrix - Pauli * - ``"+I"`` - 0 - :math:`[0, 0]` - :math:`\begin{bmatrix} 1 & 0 \\ 0 & 1 \end{bmatrix}` - :math:`I` * - ``"-I"`` - 1 - :math:`[0, 0]` - :math:`\begin{bmatrix} -1 & 0 \\ 0 & -1 \end{bmatrix}` - :math:`-I` * - ``"X"`` - 0 - :math:`[1, 0]` - :math:`\begin{bmatrix} 0 & 1 \\ 1 & 0 \end{bmatrix}` - :math:`X` * - ``"-X"`` - 1 - :math:`[1, 0]` - :math:`\begin{bmatrix} 0 & -1 \\ -1 & 0 \end{bmatrix}` - :math:`-X` * - ``"Y"`` - 0 - :math:`[1, 1]` - :math:`\begin{bmatrix} 0 & 1 \\ -1 & 0 \end{bmatrix}` - :math:`iY` * - ``"-Y"`` - 1 - :math:`[1, 1]` - :math:`\begin{bmatrix} 0 & -1 \\ 1 & 0 \end{bmatrix}` - :math:`-iY` * - ``"Z"`` - 0 - :math:`[0, 1]` - :math:`\begin{bmatrix} 1 & 0 \\ 0 & -1 \end{bmatrix}` - :math:`Z` * - ``"-Z"`` - 1 - :math:`[0, 1]` - :math:`\begin{bmatrix} -1 & 0 \\ 0 & 1 \end{bmatrix}` - :math:`-Z` Args: array (bool): return a Numpy array if True, otherwise return a list (Default: False). mode (Literal["S", "D", "B"]): return both stabilizer and destabilizer if "B", return only stabilizer if "S" and return only destabilizer if "D". Returns: list or array: The rows of the StabilizerTable in label form. Raises: QiskitError: if stabilizer and destabilizer are both False. """ if mode not in ("S", "B", "D"): raise QiskitError("mode must be B, S, or D.") size = 2 * self.num_qubits if mode == "B" else self.num_qubits offset = self.num_qubits if mode == "S" else 0 ret = np.zeros(size, dtype=f"<U{1 + self.num_qubits}") for i in range(size): z = self.tableau[i + offset, self.num_qubits : 2 * self.num_qubits] x = self.tableau[i + offset, 0 : self.num_qubits] phase = int(self.tableau[i + offset, -1]) * 2 label = BasePauli._to_label(z, x, phase, group_phase=True) if label[0] != "-": label = "+" + label ret[i] = label if array: return ret return ret.tolist() # --------------------------------------------------------------------- # Internal helper functions # --------------------------------------------------------------------- def _hash(self): """Produce a hashable value that is unique for each different Clifford. This should only be used internally when the classes being hashed are under our control, because classes of this type are mutable.""" return np.packbits(self.tableau).tobytes() @staticmethod def _is_symplectic(mat): """Return True if input is symplectic matrix.""" # Condition is # table.T * [[0, 1], [1, 0]] * table = [[0, 1], [1, 0]] # where we are block matrix multiplying using symplectic product dim = len(mat) // 2 if mat.shape != (2 * dim, 2 * dim): return False one = np.eye(dim, dtype=int) zero = np.zeros((dim, dim), dtype=int) seye = np.block([[zero, one], [one, zero]]) arr = mat.astype(int) return np.array_equal(np.mod(arr.T.dot(seye).dot(arr), 2), seye) @staticmethod def _conjugate_transpose(clifford, method): """Return the adjoint, conjugate, or transpose of the Clifford. Args: clifford (Clifford): a clifford object. method (str): what function to apply 'A', 'C', or 'T'. Returns: Clifford: the modified clifford. """ ret = clifford.copy() if method in ["A", "T"]: # Apply inverse # Update table tmp = ret.destab_x.copy() ret.destab_x = ret.stab_z.T ret.destab_z = ret.destab_z.T ret.stab_x = ret.stab_x.T ret.stab_z = tmp.T # Update phase ret.phase ^= clifford.dot(ret).phase if method in ["C", "T"]: # Apply conjugate ret.phase ^= np.mod(_count_y(ret.x, ret.z), 2).astype(bool) return ret def _pad_with_identity(self, clifford, qargs): """Pad Clifford with identities on other subsystems.""" if qargs is None: return clifford padded = Clifford(np.eye(2 * self.num_qubits, dtype=bool), validate=False, copy=False) inds = list(qargs) + [self.num_qubits + i for i in qargs] # Pad Pauli array for i, pos in enumerate(qargs): padded.tableau[inds, pos] = clifford.tableau[:, i] padded.tableau[inds, self.num_qubits + pos] = clifford.tableau[ :, clifford.num_qubits + i ] # Pad phase padded.phase[inds] = clifford.phase return padded @staticmethod def _stack_table_phase(table, phase): return np.hstack((table, phase.reshape(len(phase), 1))) @staticmethod def _from_label(label): phase = False if label[0] in ("-", "+"): phase = label[0] == "-" label = label[1:] num_qubits = len(label) symp = np.zeros(2 * num_qubits + 1, dtype=bool) xs = symp[0:num_qubits] zs = symp[num_qubits : 2 * num_qubits] for i, char in enumerate(label): if char not in ["I", "X", "Y", "Z"]: raise QiskitError( f"Pauli string contains invalid character: {char} not in ['I', 'X', 'Y', 'Z']." ) if char in ("X", "Y"): xs[num_qubits - 1 - i] = True if char in ("Z", "Y"): zs[num_qubits - 1 - i] = True symp[-1] = phase return symp @staticmethod def _pauli_matrix_to_row(mat, num_qubits): """Generate a binary vector (a row of tableau representation) from a Pauli matrix. Return None if the non-Pauli matrix is supplied.""" # pylint: disable=too-many-return-statements def find_one_index(x, decimals=6): indices = np.where(np.round(np.abs(x), decimals) == 1) return indices[0][0] if len(indices[0]) == 1 else None def bitvector(n, num_bits): return np.array([int(digit) for digit in format(n, f"0{num_bits}b")], dtype=bool)[::-1] # compute x-bits xint = find_one_index(mat[0, :]) if xint is None: return None xbits = bitvector(xint, num_qubits) # extract non-zero elements from matrix (rounded to 1, -1, 1j or -1j) entries = np.empty(len(mat), dtype=complex) for i, row in enumerate(mat): index = find_one_index(row) if index is None: return None expected = xint ^ i if index != expected: return None entries[i] = np.round(mat[i, index]) # compute z-bits zbits = np.empty(num_qubits, dtype=bool) for k in range(num_qubits): sign = np.round(entries[2**k] / entries[0]) if sign == 1: zbits[k] = False elif sign == -1: zbits[k] = True else: return None # compute phase phase = None num_y = sum(xbits & zbits) positive_phase = (-1j) ** num_y if entries[0] == positive_phase: phase = False elif entries[0] == -1 * positive_phase: phase = True if phase is None: return None # validate all non-zero elements coef = ((-1) ** phase) * positive_phase ivec, zvec = np.ones(2), np.array([1, -1]) expected = coef * functools.reduce(np.kron, [zvec if z else ivec for z in zbits[::-1]]) if not np.allclose(entries, expected): return None return np.hstack([xbits, zbits, phase]) @staticmethod def _unitary_matrix_to_tableau(matrix): # pylint: disable=invalid-name num_qubits = int(np.log2(len(matrix))) stab = np.empty((num_qubits, 2 * num_qubits + 1), dtype=bool) for i in range(num_qubits): label = "I" * (num_qubits - i - 1) + "X" + "I" * i Xi = Operator.from_label(label).to_matrix() target = matrix @ Xi @ np.conj(matrix).T row = Clifford._pauli_matrix_to_row(target, num_qubits) if row is None: return None stab[i] = row destab = np.empty((num_qubits, 2 * num_qubits + 1), dtype=bool) for i in range(num_qubits): label = "I" * (num_qubits - i - 1) + "Z" + "I" * i Zi = Operator.from_label(label).to_matrix() target = matrix @ Zi @ np.conj(matrix).T row = Clifford._pauli_matrix_to_row(target, num_qubits) if row is None: return None destab[i] = row tableau = np.vstack([stab, destab]) return tableau # Update docstrings for API docs generate_apidocs(Clifford)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# 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. """ Stabilizer state class. """ from __future__ import annotations import numpy as np from qiskit.exceptions import QiskitError from qiskit.quantum_info.operators.op_shape import OpShape from qiskit.quantum_info.operators.operator import Operator from qiskit.quantum_info.operators.symplectic import Clifford, Pauli, PauliList from qiskit.quantum_info.operators.symplectic.clifford_circuits import _append_x from qiskit.quantum_info.states.quantum_state import QuantumState from qiskit.circuit import QuantumCircuit, Instruction class StabilizerState(QuantumState): """StabilizerState class. Stabilizer simulator using the convention from reference [1]. Based on the internal class :class:`~qiskit.quantum_info.Clifford`. .. code-block:: from qiskit import QuantumCircuit from qiskit.quantum_info import StabilizerState, Pauli # Bell state generation circuit qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) stab = StabilizerState(qc) # Print the StabilizerState print(stab) # Calculate the StabilizerState measurement probabilities dictionary print (stab.probabilities_dict()) # Calculate expectation value of the StabilizerState print (stab.expectation_value(Pauli('ZZ'))) .. parsed-literal:: StabilizerState(StabilizerTable: ['+XX', '+ZZ']) {'00': 0.5, '11': 0.5} 1 References: 1. S. Aaronson, D. Gottesman, *Improved Simulation of Stabilizer Circuits*, Phys. Rev. A 70, 052328 (2004). `arXiv:quant-ph/0406196 <https://arxiv.org/abs/quant-ph/0406196>`_ """ def __init__( self, data: StabilizerState | Clifford | Pauli | QuantumCircuit | Instruction, validate: bool = True, ): """Initialize a StabilizerState object. Args: data (StabilizerState or Clifford or Pauli or QuantumCircuit or qiskit.circuit.Instruction): Data from which the stabilizer state can be constructed. validate (boolean): validate that the stabilizer state data is a valid Clifford. """ # Initialize from another StabilizerState if isinstance(data, StabilizerState): self._data = data._data # Initialize from a Pauli elif isinstance(data, Pauli): self._data = Clifford(data.to_instruction()) # Initialize from a Clifford, QuantumCircuit or Instruction else: self._data = Clifford(data, validate) # Initialize super().__init__(op_shape=OpShape.auto(num_qubits_r=self._data.num_qubits, num_qubits_l=0)) def __eq__(self, other): return (self._data.stab == other._data.stab).all() def __repr__(self): return f"StabilizerState({self._data.stabilizer})" @property def clifford(self): """Return StabilizerState Clifford data""" return self._data def is_valid(self, atol=None, rtol=None): """Return True if a valid StabilizerState.""" return self._data.is_unitary() def _add(self, other): raise NotImplementedError(f"{type(self)} does not support addition") def _multiply(self, other): raise NotImplementedError(f"{type(self)} does not support scalar multiplication") def trace(self) -> float: """Return the trace of the stabilizer state as a density matrix, which equals to 1, since it is always a pure state. Returns: float: the trace (should equal 1). Raises: QiskitError: if input is not a StabilizerState. """ if not self.is_valid(): raise QiskitError("StabilizerState is not a valid quantum state.") return 1.0 def purity(self) -> float: """Return the purity of the quantum state, which equals to 1, since it is always a pure state. Returns: float: the purity (should equal 1). Raises: QiskitError: if input is not a StabilizerState. """ if not self.is_valid(): raise QiskitError("StabilizerState is not a valid quantum state.") return 1.0 def to_operator(self) -> Operator: """Convert state to matrix operator class""" return Clifford(self.clifford).to_operator() def conjugate(self): """Return the conjugate of the operator.""" ret = self.copy() ret._data = ret._data.conjugate() return ret def tensor(self, other: StabilizerState) -> StabilizerState: """Return the tensor product stabilizer state self ⊗ other. Args: other (StabilizerState): a stabilizer state object. Returns: StabilizerState: the tensor product operator self ⊗ other. Raises: QiskitError: if other is not a StabilizerState. """ if not isinstance(other, StabilizerState): other = StabilizerState(other) ret = self.copy() ret._data = self.clifford.tensor(other.clifford) return ret def expand(self, other: StabilizerState) -> StabilizerState: """Return the tensor product stabilizer state other ⊗ self. Args: other (StabilizerState): a stabilizer state object. Returns: StabilizerState: the tensor product operator other ⊗ self. Raises: QiskitError: if other is not a StabilizerState. """ if not isinstance(other, StabilizerState): other = StabilizerState(other) ret = self.copy() ret._data = self.clifford.expand(other.clifford) return ret def evolve( self, other: Clifford | QuantumCircuit | Instruction, qargs: list | None = None ) -> StabilizerState: """Evolve a stabilizer state by a Clifford operator. Args: other (Clifford or QuantumCircuit or qiskit.circuit.Instruction): The Clifford operator to evolve by. qargs (list): a list of stabilizer subsystem positions to apply the operator on. Returns: StabilizerState: the output stabilizer state. Raises: QiskitError: if other is not a StabilizerState. QiskitError: if the operator dimension does not match the specified StabilizerState subsystem dimensions. """ if not isinstance(other, StabilizerState): other = StabilizerState(other) ret = self.copy() ret._data = self.clifford.compose(other.clifford, qargs=qargs) return ret def expectation_value(self, oper: Pauli, qargs: None | list = None) -> complex: """Compute the expectation value of a Pauli operator. Args: oper (Pauli): a Pauli operator to evaluate expval. qargs (None or list): subsystems to apply the operator on. Returns: complex: the expectation value (only 0 or 1 or -1 or i or -i). Raises: QiskitError: if oper is not a Pauli operator. """ if not isinstance(oper, Pauli): raise QiskitError("Operator for expectation value is not a Pauli operator.") num_qubits = self.clifford.num_qubits if qargs is None: qubits = range(num_qubits) else: qubits = qargs # Construct Pauli on num_qubits pauli = Pauli(num_qubits * "I") phase = 0 pauli_phase = (-1j) ** oper.phase if oper.phase else 1 for pos, qubit in enumerate(qubits): pauli.x[qubit] = oper.x[pos] pauli.z[qubit] = oper.z[pos] phase += pauli.x[qubit] & pauli.z[qubit] # Check if there is a stabilizer that anti-commutes with an odd number of qubits # If so the expectation value is 0 for p in range(num_qubits): num_anti = 0 num_anti += np.count_nonzero(pauli.z & self.clifford.stab_x[p]) num_anti += np.count_nonzero(pauli.x & self.clifford.stab_z[p]) if num_anti % 2 == 1: return 0 # Otherwise pauli is (-1)^a prod_j S_j^b_j for Clifford stabilizers # If pauli anti-commutes with D_j then b_j = 1. # Multiply pauli by stabilizers with anti-commuting destabilizers pauli_z = (pauli.z).copy() # Make a copy of pauli.z for p in range(num_qubits): # Check if destabilizer anti-commutes num_anti = 0 num_anti += np.count_nonzero(pauli.z & self.clifford.destab_x[p]) num_anti += np.count_nonzero(pauli.x & self.clifford.destab_z[p]) if num_anti % 2 == 0: continue # If anti-commutes multiply Pauli by stabilizer phase += 2 * self.clifford.stab_phase[p] phase += np.count_nonzero(self.clifford.stab_z[p] & self.clifford.stab_x[p]) phase += 2 * np.count_nonzero(pauli_z & self.clifford.stab_x[p]) pauli_z = pauli_z ^ self.clifford.stab_z[p] # For valid stabilizers, `phase` can only be 0 (= 1) or 2 (= -1) at this point. if phase % 4 != 0: return -pauli_phase return pauli_phase def equiv(self, other: StabilizerState) -> bool: """Return True if the two generating sets generate the same stabilizer group. Args: other (StabilizerState): another StabilizerState. Returns: bool: True if other has a generating set that generates the same StabilizerState. """ if not isinstance(other, StabilizerState): try: other = StabilizerState(other) except QiskitError: return False num_qubits = self.num_qubits if other.num_qubits != num_qubits: return False pauli_orig = PauliList.from_symplectic( self._data.stab_z, self._data.stab_x, 2 * self._data.stab_phase ) pauli_other = PauliList.from_symplectic( other._data.stab_z, other._data.stab_x, 2 * other._data.stab_phase ) # Check that each stabilizer from the original set commutes with each stabilizer # from the other set if not np.all([pauli.commutes(pauli_other) for pauli in pauli_orig]): return False # Compute the expected value of each stabilizer from the original set on the stabilizer state # determined by the other set. The two stabilizer states coincide if and only if the # expected value is +1 for each stabilizer for i in range(num_qubits): exp_val = self.expectation_value(pauli_other[i]) if exp_val != 1: return False return True def probabilities(self, qargs: None | list = None, decimals: None | int = None) -> np.ndarray: """Return the subsystem measurement probability vector. Measurement probabilities are with respect to measurement in the computation (diagonal) basis. Args: qargs (None or list): subsystems to return probabilities for, if None return for all subsystems (Default: None). decimals (None or int): the number of decimal places to round values. If None no rounding is done (Default: None). Returns: np.array: The Numpy vector array of probabilities. """ probs_dict = self.probabilities_dict(qargs, decimals) if qargs is None: qargs = range(self.clifford.num_qubits) probs = np.zeros(2 ** len(qargs)) for key, value in probs_dict.items(): place = int(key, 2) probs[place] = value return probs def probabilities_dict(self, qargs: None | list = None, decimals: None | int = None) -> dict: """Return the subsystem measurement probability dictionary. Measurement probabilities are with respect to measurement in the computation (diagonal) basis. This dictionary representation uses a Ket-like notation where the dictionary keys are qudit strings for the subsystem basis vectors. If any subsystem has a dimension greater than 10 comma delimiters are inserted between integers so that subsystems can be distinguished. Args: qargs (None or list): subsystems to return probabilities for, if None return for all subsystems (Default: None). decimals (None or int): the number of decimal places to round values. If None no rounding is done (Default: None). Returns: dict: The measurement probabilities in dict (ket) form. """ if qargs is None: qubits = range(self.clifford.num_qubits) else: qubits = qargs outcome = ["X"] * len(qubits) outcome_prob = 1.0 probs = {} # probabilities dictionary self._get_probablities(qubits, outcome, outcome_prob, probs) if decimals is not None: for key, value in probs.items(): probs[key] = round(value, decimals) return probs def reset(self, qargs: list | None = None) -> StabilizerState: """Reset state or subsystems to the 0-state. Args: qargs (list or None): subsystems to reset, if None all subsystems will be reset to their 0-state (Default: None). Returns: StabilizerState: the reset state. Additional Information: If all subsystems are reset this will return the ground state on all subsystems. If only some subsystems are reset this function will perform a measurement on those subsystems and evolve the subsystems so that the collapsed post-measurement states are rotated to the 0-state. The RNG seed for this sampling can be set using the :meth:`seed` method. """ # Resetting all qubits does not require sampling or RNG if qargs is None: return StabilizerState(Clifford(np.eye(2 * self.clifford.num_qubits))) randbits = self._rng.integers(2, size=len(qargs)) ret = self.copy() for bit, qubit in enumerate(qargs): # Apply measurement and get classical outcome outcome = ret._measure_and_update(qubit, randbits[bit]) # Use the outcome to apply X gate to any qubits left in the # |1> state after measure, then discard outcome. if outcome == 1: _append_x(ret.clifford, qubit) return ret def measure(self, qargs: list | None = None) -> tuple: """Measure subsystems and return outcome and post-measure state. Note that this function uses the QuantumStates internal random number generator for sampling the measurement outcome. The RNG seed can be set using the :meth:`seed` method. Args: qargs (list or None): subsystems to sample measurements for, if None sample measurement of all subsystems (Default: None). Returns: tuple: the pair ``(outcome, state)`` where ``outcome`` is the measurement outcome string label, and ``state`` is the collapsed post-measurement stabilizer state for the corresponding outcome. """ if qargs is None: qargs = range(self.clifford.num_qubits) randbits = self._rng.integers(2, size=len(qargs)) ret = self.copy() outcome = "" for bit, qubit in enumerate(qargs): outcome = str(ret._measure_and_update(qubit, randbits[bit])) + outcome return outcome, ret def sample_memory(self, shots: int, qargs: None | list = None) -> np.ndarray: """Sample a list of qubit measurement outcomes in the computational basis. Args: shots (int): number of samples to generate. qargs (None or list): subsystems to sample measurements for, if None sample measurement of all subsystems (Default: None). Returns: np.array: list of sampled counts if the order sampled. Additional Information: This function implements the measurement :meth:`measure` method. The seed for random number generator used for sampling can be set to a fixed value by using the stats :meth:`seed` method. """ memory = [] for _ in range(shots): # copy the StabilizerState since measure updates it stab = self.copy() memory.append(stab.measure(qargs)[0]) return memory # ----------------------------------------------------------------------- # Helper functions for calculating the measurement # ----------------------------------------------------------------------- def _measure_and_update(self, qubit, randbit): """Measure a single qubit and return outcome and post-measure state. Note that this function uses the QuantumStates internal random number generator for sampling the measurement outcome. The RNG seed can be set using the :meth:`seed` method. Note that stabilizer state measurements only have three probabilities: (p0, p1) = (0.5, 0.5), (1, 0), or (0, 1) The random case happens if there is a row anti-commuting with Z[qubit] """ num_qubits = self.clifford.num_qubits clifford = self.clifford stab_x = self.clifford.stab_x # Check if there exists stabilizer anticommuting with Z[qubit] # in this case the measurement outcome is random z_anticommuting = np.any(stab_x[:, qubit]) if z_anticommuting == 0: # Deterministic outcome - measuring it will not change the StabilizerState aux_pauli = Pauli(num_qubits * "I") for i in range(num_qubits): if clifford.x[i][qubit]: aux_pauli = self._rowsum_deterministic(clifford, aux_pauli, i + num_qubits) outcome = aux_pauli.phase return outcome else: # Non-deterministic outcome outcome = randbit p_qubit = np.min(np.nonzero(stab_x[:, qubit])) p_qubit += num_qubits # Updating the StabilizerState for i in range(2 * num_qubits): # the last condition is not in the AG paper but we seem to need it if (clifford.x[i][qubit]) and (i != p_qubit) and (i != (p_qubit - num_qubits)): self._rowsum_nondeterministic(clifford, i, p_qubit) clifford.destab[p_qubit - num_qubits] = clifford.stab[p_qubit - num_qubits].copy() clifford.x[p_qubit] = np.zeros(num_qubits) clifford.z[p_qubit] = np.zeros(num_qubits) clifford.z[p_qubit][qubit] = True clifford.phase[p_qubit] = outcome return outcome @staticmethod def _phase_exponent(x1, z1, x2, z2): """Exponent g of i such that Pauli(x1,z1) * Pauli(x2,z2) = i^g Pauli(x1+x2,z1+z2)""" # pylint: disable=invalid-name phase = (x2 * z1 * (1 + 2 * z2 + 2 * x1) - x1 * z2 * (1 + 2 * z1 + 2 * x2)) % 4 if phase < 0: phase += 4 # now phase in {0, 1, 3} if phase == 2: raise QiskitError("Invalid rowsum phase exponent in measurement calculation.") return phase @staticmethod def _rowsum(accum_pauli, accum_phase, row_pauli, row_phase): """Aaronson-Gottesman rowsum helper function""" newr = 2 * row_phase + 2 * accum_phase for qubit in range(row_pauli.num_qubits): newr += StabilizerState._phase_exponent( row_pauli.x[qubit], row_pauli.z[qubit], accum_pauli.x[qubit], accum_pauli.z[qubit] ) newr %= 4 if (newr != 0) & (newr != 2): raise QiskitError("Invalid rowsum in measurement calculation.") accum_phase = int(newr == 2) accum_pauli.x ^= row_pauli.x accum_pauli.z ^= row_pauli.z return accum_pauli, accum_phase @staticmethod def _rowsum_nondeterministic(clifford, accum, row): """Updating StabilizerState Clifford in the non-deterministic rowsum calculation. row and accum are rows in the StabilizerState Clifford.""" row_phase = clifford.phase[row] accum_phase = clifford.phase[accum] z = clifford.z x = clifford.x row_pauli = Pauli((z[row], x[row])) accum_pauli = Pauli((z[accum], x[accum])) accum_pauli, accum_phase = StabilizerState._rowsum( accum_pauli, accum_phase, row_pauli, row_phase ) clifford.phase[accum] = accum_phase x[accum] = accum_pauli.x z[accum] = accum_pauli.z @staticmethod def _rowsum_deterministic(clifford, aux_pauli, row): """Updating an auxilary Pauli aux_pauli in the deterministic rowsum calculation. The StabilizerState itself is not updated.""" row_phase = clifford.phase[row] accum_phase = aux_pauli.phase accum_pauli = aux_pauli row_pauli = Pauli((clifford.z[row], clifford.x[row])) accum_pauli, accum_phase = StabilizerState._rowsum( accum_pauli, accum_phase, row_pauli, row_phase ) aux_pauli = accum_pauli aux_pauli.phase = accum_phase return aux_pauli # ----------------------------------------------------------------------- # Helper functions for calculating the probabilities # ----------------------------------------------------------------------- def _get_probablities(self, qubits, outcome, outcome_prob, probs): """Recursive helper function for calculating the probabilities""" qubit_for_branching = -1 ret = self.copy() for i in range(len(qubits)): qubit = qubits[len(qubits) - i - 1] if outcome[i] == "X": is_deterministic = not any(ret.clifford.stab_x[:, qubit]) if is_deterministic: single_qubit_outcome = ret._measure_and_update(qubit, 0) if single_qubit_outcome: outcome[i] = "1" else: outcome[i] = "0" else: qubit_for_branching = i if qubit_for_branching == -1: str_outcome = "".join(outcome) probs[str_outcome] = outcome_prob return for single_qubit_outcome in range(0, 2): new_outcome = outcome.copy() if single_qubit_outcome: new_outcome[qubit_for_branching] = "1" else: new_outcome[qubit_for_branching] = "0" stab_cpy = ret.copy() stab_cpy._measure_and_update( qubits[len(qubits) - qubit_for_branching - 1], single_qubit_outcome ) stab_cpy._get_probablities(qubits, new_outcome, 0.5 * outcome_prob, probs)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# 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. """ Quantum Shannon Decomposition. Method is described in arXiv:quant-ph/0406176. """ from __future__ import annotations import scipy import numpy as np from qiskit.circuit import QuantumCircuit, QuantumRegister from qiskit.quantum_info.synthesis import two_qubit_decompose, one_qubit_decompose from qiskit.quantum_info.operators.predicates import is_hermitian_matrix from qiskit.extensions.quantum_initializer.uc_pauli_rot import UCPauliRotGate, _EPS def qs_decomposition( mat: np.ndarray, opt_a1: bool = True, opt_a2: bool = True, decomposer_1q=None, decomposer_2q=None, *, _depth=0, ): """ Decomposes unitary matrix into one and two qubit gates using Quantum Shannon Decomposition. ┌───┐ ┌───┐ ┌───┐ ┌───┐ ─┤ ├─ ───────┤ Rz├─────┤ Ry├─────┤ Rz├───── │ │ ≃ ┌───┐└─┬─┘┌───┐└─┬─┘┌───┐└─┬─┘┌───┐ /─┤ ├─ /─┤ ├──□──┤ ├──□──┤ ├──□──┤ ├ └───┘ └───┘ └───┘ └───┘ └───┘ The number of CX gates generated with the decomposition without optimizations is, .. math:: \frac{9}{16} 4^n - frac{3}{2} 2^n If opt_a1 = True, the default, the CX count is reduced by, .. math:: \frac{1}{3} 4^{n - 2} - 1. If opt_a2 = True, the default, the CX count is reduced by, .. math:: 4^{n-2} - 1. This decomposition is described in arXiv:quant-ph/0406176. Arguments: mat (ndarray): unitary matrix to decompose opt_a1 (bool): whether to try optimization A.1 from Shende. This should eliminate 1 cnot per call. If True CZ gates are left in the output. If desired these can be further decomposed to CX. opt_a2 (bool): whether to try optimization A.2 from Shende. This decomposes two qubit unitaries into a diagonal gate and a two cx unitary and reduces overal cx count by 4^(n-2) - 1. decomposer_1q (None or Object): optional 1Q decomposer. If None, uses :class:`~qiskit.quantum_info.synthesis.one_qubit_decomposer.OneQubitEulerDecomser` decomposer_2q (None or Object): optional 2Q decomposer. If None, uses :class:`~qiskit.quantum_info.synthesis.two_qubit_decomposer.two_qubit_cnot_decompose Return: QuantumCircuit: Decomposed quantum circuit. """ # _depth (int): Internal use parameter to track recursion depth. dim = mat.shape[0] nqubits = int(np.log2(dim)) if np.allclose(np.identity(dim), mat): return QuantumCircuit(nqubits) if dim == 2: if decomposer_1q is None: decomposer_1q = one_qubit_decompose.OneQubitEulerDecomposer() circ = decomposer_1q(mat) elif dim == 4: if decomposer_2q is None: if opt_a2 and _depth > 0: from qiskit.extensions.unitary import UnitaryGate # pylint: disable=cyclic-import def decomp_2q(mat): ugate = UnitaryGate(mat) qc = QuantumCircuit(2, name="qsd2q") qc.append(ugate, [0, 1]) return qc decomposer_2q = decomp_2q else: decomposer_2q = two_qubit_decompose.two_qubit_cnot_decompose circ = decomposer_2q(mat) else: qr = QuantumRegister(nqubits) circ = QuantumCircuit(qr) dim_o2 = dim // 2 # perform cosine-sine decomposition (u1, u2), vtheta, (v1h, v2h) = scipy.linalg.cossin(mat, separate=True, p=dim_o2, q=dim_o2) # left circ left_circ = _demultiplex(v1h, v2h, opt_a1=opt_a1, opt_a2=opt_a2, _depth=_depth) circ.append(left_circ.to_instruction(), qr) # middle circ if opt_a1: nangles = len(vtheta) half_size = nangles // 2 # get UCG in terms of CZ circ_cz = _get_ucry_cz(nqubits, (2 * vtheta).tolist()) circ.append(circ_cz.to_instruction(), range(nqubits)) # merge final cz with right-side generic multiplexer u2[:, half_size:] = np.negative(u2[:, half_size:]) else: circ.ucry((2 * vtheta).tolist(), qr[:-1], qr[-1]) # right circ right_circ = _demultiplex(u1, u2, opt_a1=opt_a1, opt_a2=opt_a2, _depth=_depth) circ.append(right_circ.to_instruction(), qr) if opt_a2 and _depth == 0 and dim > 4: return _apply_a2(circ) return circ def _demultiplex(um0, um1, opt_a1=False, opt_a2=False, *, _depth=0): """Decompose a generic multiplexer. ────□──── ┌──┴──┐ /─┤ ├─ └─────┘ represented by the block diagonal matrix ┏ ┓ ┃ um0 ┃ ┃ um1 ┃ ┗ ┛ to ┌───┐ ───────┤ Rz├────── ┌───┐└─┬─┘┌───┐ /─┤ w ├──□──┤ v ├─ └───┘ └───┘ where v and w are general unitaries determined from decomposition. Args: um0 (ndarray): applied if MSB is 0 um1 (ndarray): applied if MSB is 1 opt_a1 (bool): whether to try optimization A.1 from Shende. This should elliminate 1 cnot per call. If True CZ gates are left in the output. If desired these can be further decomposed opt_a2 (bool): whether to try optimization A.2 from Shende. This decomposes two qubit unitaries into a diagonal gate and a two cx unitary and reduces overal cx count by 4^(n-2) - 1. _depth (int): This is an internal variable to track the recursion depth. Returns: QuantumCircuit: decomposed circuit """ dim = um0.shape[0] + um1.shape[0] # these should be same dimension nqubits = int(np.log2(dim)) um0um1 = um0 @ um1.T.conjugate() if is_hermitian_matrix(um0um1): eigvals, vmat = scipy.linalg.eigh(um0um1) else: evals, vmat = scipy.linalg.schur(um0um1, output="complex") eigvals = evals.diagonal() dvals = np.lib.scimath.sqrt(eigvals) dmat = np.diag(dvals) wmat = dmat @ vmat.T.conjugate() @ um1 circ = QuantumCircuit(nqubits) # left gate left_gate = qs_decomposition( wmat, opt_a1=opt_a1, opt_a2=opt_a2, _depth=_depth + 1 ).to_instruction() circ.append(left_gate, range(nqubits - 1)) # multiplexed Rz angles = 2 * np.angle(np.conj(dvals)) circ.ucrz(angles.tolist(), list(range(nqubits - 1)), [nqubits - 1]) # right gate right_gate = qs_decomposition( vmat, opt_a1=opt_a1, opt_a2=opt_a2, _depth=_depth + 1 ).to_instruction() circ.append(right_gate, range(nqubits - 1)) return circ def _get_ucry_cz(nqubits, angles): """ Get uniformly controlled Ry gate in in CZ-Ry as in UCPauliRotGate. """ nangles = len(angles) qc = QuantumCircuit(nqubits) q_controls = qc.qubits[:-1] q_target = qc.qubits[-1] if not q_controls: if np.abs(angles[0]) > _EPS: qc.ry(angles[0], q_target) else: angles = angles.copy() UCPauliRotGate._dec_uc_rotations(angles, 0, len(angles), False) for (i, angle) in enumerate(angles): if np.abs(angle) > _EPS: qc.ry(angle, q_target) if not i == len(angles) - 1: binary_rep = np.binary_repr(i + 1) q_contr_index = len(binary_rep) - len(binary_rep.rstrip("0")) else: # Handle special case: q_contr_index = len(q_controls) - 1 # leave off last CZ for merging with adjacent UCG if i < nangles - 1: qc.cz(q_controls[q_contr_index], q_target) return qc def _apply_a2(circ): from qiskit import transpile from qiskit.quantum_info import Operator # from qiskit.extensions.unitary import UnitaryGate import qiskit.extensions.unitary decomposer = two_qubit_decompose.TwoQubitDecomposeUpToDiagonal() ccirc = transpile(circ, basis_gates=["u", "cx", "qsd2q"], optimization_level=0) ind2q = [] # collect 2q instrs for i, instruction in enumerate(ccirc.data): if instruction.operation.name == "qsd2q": ind2q.append(i) if not ind2q: return ccirc # rolling over diagonals ind2 = None # lint for ind1, ind2 in zip(ind2q[0:-1:], ind2q[1::]): # get neigboring 2q gates separated by controls instr1 = ccirc.data[ind1] mat1 = Operator(instr1.operation).data instr2 = ccirc.data[ind2] mat2 = Operator(instr2.operation).data # rollover dmat, qc2cx = decomposer(mat1) ccirc.data[ind1] = instr1.replace(operation=qc2cx.to_gate()) mat2 = mat2 @ dmat ccirc.data[ind2] = instr2.replace(qiskit.extensions.unitary.UnitaryGate(mat2)) qc3 = two_qubit_decompose.two_qubit_cnot_decompose(mat2) ccirc.data[ind2] = ccirc.data[ind2].replace(operation=qc3.to_gate()) return ccirc
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# 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. """A container class for counts from a circuit execution.""" import re from qiskit.result import postprocess from qiskit import exceptions # NOTE: A dict subclass should not overload any dunder methods like __getitem__ # this can cause unexpected behavior and issues as the cPython dict # implementation has many standard methods in C for performance and the dunder # methods are not always used as expected. For example, update() doesn't call # __setitem__ so overloading __setitem__ would not always provide the expected # result class Counts(dict): """A class to store a counts result from a circuit execution.""" bitstring_regex = re.compile(r"^[01\s]+$") def __init__(self, data, time_taken=None, creg_sizes=None, memory_slots=None): """Build a counts object Args: data (dict): The dictionary input for the counts. Where the keys represent a measured classical value and the value is an integer the number of shots with that result. The keys can be one of several formats: * A hexadecimal string of the form ``'0x4a'`` * A bit string prefixed with ``0b`` for example ``'0b1011'`` * A bit string formatted across register and memory slots. For example, ``'00 10'``. * A dit string, for example ``'02'``. Note for objects created with dit strings the ``creg_sizes`` and ``memory_slots`` kwargs don't work and :meth:`hex_outcomes` and :meth:`int_outcomes` also do not work. time_taken (float): The duration of the experiment that generated the counts in seconds. creg_sizes (list): a nested list where the inner element is a list of tuples containing both the classical register name and classical register size. For example, ``[('c_reg', 2), ('my_creg', 4)]``. memory_slots (int): The number of total ``memory_slots`` in the experiment. Raises: TypeError: If the input key type is not an ``int`` or ``str``. QiskitError: If a dit string key is input with ``creg_sizes`` and/or ``memory_slots``. """ bin_data = None data = dict(data) if not data: self.int_raw = {} self.hex_raw = {} bin_data = {} else: first_key = next(iter(data.keys())) if isinstance(first_key, int): self.int_raw = data self.hex_raw = {hex(key): value for key, value in self.int_raw.items()} elif isinstance(first_key, str): if first_key.startswith("0x"): self.hex_raw = data self.int_raw = {int(key, 0): value for key, value in self.hex_raw.items()} elif first_key.startswith("0b"): self.int_raw = {int(key, 0): value for key, value in data.items()} self.hex_raw = {hex(key): value for key, value in self.int_raw.items()} else: if not creg_sizes and not memory_slots: self.hex_raw = None self.int_raw = None bin_data = data else: hex_dict = {} int_dict = {} for bitstring, value in data.items(): if not self.bitstring_regex.search(bitstring): raise exceptions.QiskitError( "Counts objects with dit strings do not " "currently support dit string formatting parameters " "creg_sizes or memory_slots" ) int_key = self._remove_space_underscore(bitstring) int_dict[int_key] = value hex_dict[hex(int_key)] = value self.hex_raw = hex_dict self.int_raw = int_dict else: raise TypeError( "Invalid input key type %s, must be either an int " "key or string key with hexademical value or bit string" ) header = {} self.creg_sizes = creg_sizes if self.creg_sizes: header["creg_sizes"] = self.creg_sizes self.memory_slots = memory_slots if self.memory_slots: header["memory_slots"] = self.memory_slots if not bin_data: bin_data = postprocess.format_counts(self.hex_raw, header=header) super().__init__(bin_data) self.time_taken = time_taken def most_frequent(self): """Return the most frequent count Returns: str: The bit string for the most frequent result Raises: QiskitError: when there is >1 count with the same max counts, or an empty object. """ if not self: raise exceptions.QiskitError("Can not return a most frequent count on an empty object") max_value = max(self.values()) max_values_counts = [x[0] for x in self.items() if x[1] == max_value] if len(max_values_counts) != 1: raise exceptions.QiskitError( "Multiple values have the same maximum counts: %s" % ",".join(max_values_counts) ) return max_values_counts[0] def hex_outcomes(self): """Return a counts dictionary with hexadecimal string keys Returns: dict: A dictionary with the keys as hexadecimal strings instead of bitstrings Raises: QiskitError: If the Counts object contains counts for dit strings """ if self.hex_raw: return {key.lower(): value for key, value in self.hex_raw.items()} else: out_dict = {} for bitstring, value in self.items(): if not self.bitstring_regex.search(bitstring): raise exceptions.QiskitError( "Counts objects with dit strings do not " "currently support conversion to hexadecimal" ) int_key = self._remove_space_underscore(bitstring) out_dict[hex(int_key)] = value return out_dict def int_outcomes(self): """Build a counts dictionary with integer keys instead of count strings Returns: dict: A dictionary with the keys as integers instead of bitstrings Raises: QiskitError: If the Counts object contains counts for dit strings """ if self.int_raw: return self.int_raw else: out_dict = {} for bitstring, value in self.items(): if not self.bitstring_regex.search(bitstring): raise exceptions.QiskitError( "Counts objects with dit strings do not " "currently support conversion to integer" ) int_key = self._remove_space_underscore(bitstring) out_dict[int_key] = value return out_dict @staticmethod def _remove_space_underscore(bitstring): """Removes all spaces and underscores from bitstring""" return int(bitstring.replace(" ", "").replace("_", ""), 2) def shots(self): """Return the number of shots""" return sum(self.values())
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 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. """Functions to generate the basic approximations of single qubit gates for Solovay-Kitaev.""" from __future__ import annotations import warnings import collections import numpy as np import qiskit.circuit.library.standard_gates as gates from qiskit.circuit import Gate from qiskit.quantum_info.operators.predicates import matrix_equal from qiskit.utils import optionals from .gate_sequence import GateSequence Node = collections.namedtuple("Node", ("labels", "sequence", "children")) _1q_inverses = { "i": "i", "x": "x", "y": "y", "z": "z", "h": "h", "t": "tdg", "tdg": "t", "s": "sdg", "sdg": "s", } _1q_gates = { "i": gates.IGate(), "x": gates.XGate(), "y": gates.YGate(), "z": gates.ZGate(), "h": gates.HGate(), "t": gates.TGate(), "tdg": gates.TdgGate(), "s": gates.SGate(), "sdg": gates.SdgGate(), "sx": gates.SXGate(), "sxdg": gates.SXdgGate(), } def _check_candidate(candidate, existing_sequences, tol=1e-10): if optionals.HAS_SKLEARN: return _check_candidate_kdtree(candidate, existing_sequences, tol) warnings.warn( "The SolovayKitaev algorithm relies on scikit-learn's KDTree for a " "fast search over the basis approximations. Without this, we fallback onto a " "greedy search with is significantly slower. We highly suggest to install " "scikit-learn to use this feature.", category=RuntimeWarning, ) return _check_candidate_greedy(candidate, existing_sequences, tol) def _check_candidate_greedy(candidate, existing_sequences, tol=1e-10): # do a quick, string-based check if the same sequence already exists if any(candidate.name == existing.name for existing in existing_sequences): return False for existing in existing_sequences: if matrix_equal(existing.product_su2, candidate.product_su2, ignore_phase=True, atol=tol): # is the new sequence less or more efficient? return len(candidate.gates) < len(existing.gates) return True @optionals.HAS_SKLEARN.require_in_call def _check_candidate_kdtree(candidate, existing_sequences, tol=1e-10): """Check if there's a candidate implementing the same matrix up to ``tol``. This uses a k-d tree search and is much faster than the greedy, list-based search. """ from sklearn.neighbors import KDTree # do a quick, string-based check if the same sequence already exists if any(candidate.name == existing.name for existing in existing_sequences): return False points = np.array([sequence.product.flatten() for sequence in existing_sequences]) candidate = np.array([candidate.product.flatten()]) kdtree = KDTree(points) dist, _ = kdtree.query(candidate) return dist[0][0] > tol def _process_node(node: Node, basis: list[str], sequences: list[GateSequence]): inverse_last = _1q_inverses[node.labels[-1]] if node.labels else None for label in basis: if label == inverse_last: continue sequence = node.sequence.copy() sequence.append(_1q_gates[label]) if _check_candidate(sequence, sequences): sequences.append(sequence) node.children.append(Node(node.labels + (label,), sequence, [])) return node.children def generate_basic_approximations( basis_gates: list[str | Gate], depth: int, filename: str | None = None ) -> list[GateSequence]: """Generates a list of ``GateSequence``s with the gates in ``basic_gates``. Args: basis_gates: The gates from which to create the sequences of gates. depth: The maximum depth of the approximations. filename: If provided, the basic approximations are stored in this file. Returns: List of ``GateSequences`` using the gates in ``basic_gates``. Raises: ValueError: If ``basis_gates`` contains an invalid gate identifier. """ basis = [] for gate in basis_gates: if isinstance(gate, str): if gate not in _1q_gates.keys(): raise ValueError(f"Invalid gate identifier: {gate}") basis.append(gate) else: # gate is a qiskit.circuit.Gate basis.append(gate.name) tree = Node((), GateSequence(), []) cur_level = [tree] sequences = [tree.sequence] for _ in [None] * depth: next_level = [] for node in cur_level: next_level.extend(_process_node(node, basis, sequences)) cur_level = next_level if filename is not None: data = {} for sequence in sequences: gatestring = sequence.name data[gatestring] = sequence.product np.save(filename, data) return sequences
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2022. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Utility functions for handling linear reversible circuits.""" import copy from typing import Callable import numpy as np from qiskit import QuantumCircuit from qiskit.exceptions import QiskitError from qiskit.circuit.exceptions import CircuitError from . import calc_inverse_matrix, check_invertible_binary_matrix def transpose_cx_circ(qc: QuantumCircuit): """Takes a circuit having only CX gates, and calculates its transpose. This is done by recursively replacing CX(i, j) with CX(j, i) in all instructions. Args: qc: a QuantumCircuit containing only CX gates. Returns: QuantumCircuit: the transposed circuit. Raises: CircuitError: if qc has a non-CX gate. """ transposed_circ = QuantumCircuit(qc.qubits, qc.clbits, name=qc.name + "_transpose") for instruction in reversed(qc.data): if instruction.operation.name != "cx": raise CircuitError("The circuit contains non-CX gates.") transposed_circ._append(instruction.replace(qubits=reversed(instruction.qubits))) return transposed_circ def optimize_cx_4_options(function: Callable, mat: np.ndarray, optimize_count: bool = True): """Get the best implementation of a circuit implementing a binary invertible matrix M, by considering all four options: M,M^(-1),M^T,M^(-1)^T. Optimizing either the CX count or the depth. Args: function: the synthesis function. mat: a binary invertible matrix. optimize_count: True if the number of CX gates in optimize, False if the depth is optimized. Returns: QuantumCircuit: an optimized QuantumCircuit, has the best depth or CX count of the four options. Raises: QiskitError: if mat is not an invertible matrix. """ if not check_invertible_binary_matrix(mat): raise QiskitError("The matrix is not invertible.") qc = function(mat) best_qc = qc best_depth = qc.depth() best_count = qc.count_ops()["cx"] for i in range(1, 4): mat_cpy = copy.deepcopy(mat) # i=1 inverse, i=2 transpose, i=3 transpose and inverse if i == 1: mat_cpy = calc_inverse_matrix(mat_cpy) qc = function(mat_cpy) qc = qc.inverse() elif i == 2: mat_cpy = np.transpose(mat_cpy) qc = function(mat_cpy) qc = transpose_cx_circ(qc) elif i == 3: mat_cpy = calc_inverse_matrix(np.transpose(mat_cpy)) qc = function(mat_cpy) qc = transpose_cx_circ(qc) qc = qc.inverse() new_depth = qc.depth() new_count = qc.count_ops()["cx"] # Prioritize count, and if it has the same count, then also consider depth better_count = (optimize_count and best_count > new_count) or ( not optimize_count and best_depth == new_depth and best_count > new_count ) # Prioritize depth, and if it has the same depth, then also consider count better_depth = (not optimize_count and best_depth > new_depth) or ( optimize_count and best_count == new_count and best_depth > new_depth ) if better_count or better_depth: best_count = new_count best_depth = new_depth best_qc = qc return best_qc def check_lnn_connectivity(qc: QuantumCircuit) -> bool: """Check that the synthesized circuit qc fits linear nearest neighbor connectivity. Args: qc: a QuantumCircuit containing only CX and single qubit gates. Returns: bool: True if the circuit has linear nearest neighbor connectivity. Raises: CircuitError: if qc has a non-CX two-qubit gate. """ for instruction in qc.data: if instruction.operation.num_qubits > 1: if instruction.operation.name == "cx": q0 = qc.find_bit(instruction.qubits[0]).index q1 = qc.find_bit(instruction.qubits[1]).index dist = abs(q0 - q1) if dist != 1: return False else: raise CircuitError("The circuit has two-qubits gates different than CX.") return True
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Decorator for using with Qiskit unit tests.""" import functools import os import sys import unittest from .utils import Path from .http_recorder import http_recorder from .testing_options import get_test_options def is_aer_provider_available(): """Check if the C++ simulator can be instantiated. Returns: bool: True if simulator executable is available """ # TODO: HACK FROM THE DEPTHS OF DESPAIR AS AER DOES NOT WORK ON MAC if sys.platform == 'darwin': return False try: import qiskit.providers.aer # pylint: disable=unused-import except ImportError: return False return True def requires_aer_provider(test_item): """Decorator that skips test if qiskit aer provider is not available Args: test_item (callable): function or class to be decorated. Returns: callable: the decorated function. """ reason = 'Aer provider not found, skipping test' return unittest.skipIf(not is_aer_provider_available(), reason)(test_item) def slow_test(func): """Decorator that signals that the test takes minutes to run. Args: func (callable): test function to be decorated. Returns: callable: the decorated function. """ @functools.wraps(func) def _wrapper(*args, **kwargs): skip_slow = not TEST_OPTIONS['run_slow'] if skip_slow: raise unittest.SkipTest('Skipping slow tests') return func(*args, **kwargs) return _wrapper def _get_credentials(test_object, test_options): """Finds the credentials for a specific test and options. Args: test_object (QiskitTestCase): The test object asking for credentials test_options (dict): Options after QISKIT_TESTS was parsed by get_test_options. Returns: Credentials: set of credentials Raises: ImportError: if the Exception: when the credential could not be set and they are needed for that set of options """ try: from qiskit.providers.ibmq.credentials import (Credentials, discover_credentials) except ImportError: raise ImportError('qiskit-ibmq-provider could not be found, and is ' 'required for mocking or executing online tests.') dummy_credentials = Credentials( 'dummyapiusersloginWithTokenid01', 'https://quantumexperience.ng.bluemix.net/api') if test_options['mock_online']: return dummy_credentials if os.getenv('USE_ALTERNATE_ENV_CREDENTIALS', ''): # Special case: instead of using the standard credentials mechanism, # load them from different environment variables. This assumes they # will always be in place, as is used by the Travis setup. return Credentials(os.getenv('IBMQ_TOKEN'), os.getenv('IBMQ_URL')) else: # Attempt to read the standard credentials. discovered_credentials = discover_credentials() if discovered_credentials: # Decide which credentials to use for testing. if len(discovered_credentials) > 1: try: # Attempt to use QE credentials. return discovered_credentials[dummy_credentials.unique_id()] except KeyError: pass # Use the first available credentials. return list(discovered_credentials.values())[0] # No user credentials were found. if test_options['rec']: raise Exception('Could not locate valid credentials. You need them for ' 'recording tests against the remote API.') test_object.log.warning('No user credentials were detected. ' 'Running with mocked data.') test_options['mock_online'] = True return dummy_credentials def requires_qe_access(func): """Decorator that signals that the test uses the online API: It involves: * determines if the test should be skipped by checking environment variables. * if the `USE_ALTERNATE_ENV_CREDENTIALS` environment variable is set, it reads the credentials from an alternative set of environment variables. * if the test is not skipped, it reads `qe_token` and `qe_url` from `Qconfig.py`, environment variables or qiskitrc. * if the test is not skipped, it appends `qe_token` and `qe_url` as arguments to the test function. Args: func (callable): test function to be decorated. Returns: callable: the decorated function. """ @functools.wraps(func) def _wrapper(self, *args, **kwargs): if TEST_OPTIONS['skip_online']: raise unittest.SkipTest('Skipping online tests') credentials = _get_credentials(self, TEST_OPTIONS) self.using_ibmq_credentials = credentials.is_ibmq() kwargs.update({'qe_token': credentials.token, 'qe_url': credentials.url}) decorated_func = func if TEST_OPTIONS['rec'] or TEST_OPTIONS['mock_online']: # For recording or for replaying existing cassettes, the test # should be decorated with @use_cassette. vcr_mode = 'new_episodes' if TEST_OPTIONS['rec'] else 'none' decorated_func = http_recorder( vcr_mode, Path.CASSETTES.value).use_cassette()(decorated_func) return decorated_func(self, *args, **kwargs) return _wrapper TEST_OPTIONS = get_test_options()
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# 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. """Mock functions for qiskit.IBMQ.""" from unittest.mock import MagicMock import qiskit from qiskit.providers import fake_provider as backend_mocks def mock_get_backend(backend): """Replace qiskit.IBMQ with a mock that returns a single backend. Note this will set the value of qiskit.IBMQ to a MagicMock object. It is intended to be run as part of docstrings with jupyter-example in a hidden cell so that later examples which rely on ibmq devices so that the docs can be built without requiring configured credentials. If used outside of this context be aware that you will have to manually restore qiskit.IBMQ the value to qiskit.providers.ibmq.IBMQ after you finish using your mock. Args: backend (str): The class name as a string for the fake device to return from the mock IBMQ object. For example, FakeVigo. Raises: NameError: If the specified value of backend """ mock_ibmq = MagicMock() mock_provider = MagicMock() if not hasattr(backend_mocks, backend): raise NameError( "The specified backend name is not a valid mock from qiskit.providers.fake_provider." ) fake_backend = getattr(backend_mocks, backend)() mock_provider.get_backend.return_value = fake_backend mock_ibmq.get_provider.return_value = mock_provider qiskit.IBMQ = mock_ibmq
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Utils for using with Qiskit unit tests.""" import logging import os import unittest from enum import Enum from qiskit import __path__ as qiskit_path class Path(Enum): """Helper with paths commonly used during the tests.""" # Main SDK path: qiskit/ SDK = qiskit_path[0] # test.python path: qiskit/test/python/ TEST = os.path.normpath(os.path.join(SDK, '..', 'test', 'python')) # Examples path: examples/ EXAMPLES = os.path.normpath(os.path.join(SDK, '..', 'examples')) # Schemas path: qiskit/schemas SCHEMAS = os.path.normpath(os.path.join(SDK, 'schemas')) # VCR cassettes path: qiskit/test/cassettes/ CASSETTES = os.path.normpath(os.path.join(TEST, '..', 'cassettes')) # Sample QASMs path: qiskit/test/python/qasm QASMS = os.path.normpath(os.path.join(TEST, 'qasm')) def setup_test_logging(logger, log_level, filename): """Set logging to file and stdout for a logger. Args: logger (Logger): logger object to be updated. log_level (str): logging level. filename (str): name of the output file. """ # Set up formatter. log_fmt = ('{}.%(funcName)s:%(levelname)s:%(asctime)s:' ' %(message)s'.format(logger.name)) formatter = logging.Formatter(log_fmt) # Set up the file handler. file_handler = logging.FileHandler(filename) file_handler.setFormatter(formatter) logger.addHandler(file_handler) # Set the logging level from the environment variable, defaulting # to INFO if it is not a valid level. level = logging._nameToLevel.get(log_level, logging.INFO) logger.setLevel(level) class _AssertNoLogsContext(unittest.case._AssertLogsContext): """A context manager used to implement TestCase.assertNoLogs().""" # pylint: disable=inconsistent-return-statements def __exit__(self, exc_type, exc_value, tb): """ This is a modified version of TestCase._AssertLogsContext.__exit__(...) """ self.logger.handlers = self.old_handlers self.logger.propagate = self.old_propagate self.logger.setLevel(self.old_level) if exc_type is not None: # let unexpected exceptions pass through return False if self.watcher.records: msg = 'logs of level {} or higher triggered on {}:\n'.format( logging.getLevelName(self.level), self.logger.name) for record in self.watcher.records: msg += 'logger %s %s:%i: %s\n' % (record.name, record.pathname, record.lineno, record.getMessage()) self._raiseFailure(msg)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
from qiskit import Aer, IBMQ, execute from qiskit import transpile, assemble from qiskit.tools.monitor import job_monitor from qiskit.tools.monitor import job_monitor import matplotlib.pyplot as plt from qiskit.visualization import plot_histogram, plot_state_city """ Qiskit backends to execute the quantum circuit """ def simulator(qc): """ Run on local simulator :param qc: quantum circuit :return: """ backend = Aer.get_backend("qasm_simulator") shots = 2048 tqc = transpile(qc, backend) qobj = assemble(tqc, shots=shots) job_sim = backend.run(qobj) qc_results = job_sim.result() return qc_results, shots def simulator_state_vector(qc): """ Select the StatevectorSimulator from the Aer provider :param qc: quantum circuit :return: statevector """ simulator = Aer.get_backend('statevector_simulator') # Execute and get counts result = execute(qc, simulator).result() state_vector = result.get_statevector(qc) return state_vector def real_quantum_device(qc): """ Use the IBMQ essex device :param qc: quantum circuit :return: """ provider = IBMQ.load_account() backend = provider.get_backend('ibmq_santiago') shots = 2048 TQC = transpile(qc, backend) qobj = assemble(TQC, shots=shots) job_exp = backend.run(qobj) job_monitor(job_exp) QC_results = job_exp.result() return QC_results, shots def counts(qc_results): """ Get counts representing the wave-function amplitudes :param qc_results: :return: dict keys are bit_strings and their counting values """ return qc_results.get_counts() def plot_results(qc_results): """ Visualizing wave-function amplitudes in a histogram :param qc_results: quantum circuit :return: """ plt.show(plot_histogram(qc_results.get_counts(), figsize=(8, 6), bar_labels=False)) def plot_state_vector(state_vector): """Visualizing state vector in the density matrix representation""" plt.show(plot_state_city(state_vector))
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# 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. # This file is part of QuTiP: Quantum Toolbox in Python. # # Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names # of its contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ############################################################################### """ Routines for running Python functions in parallel using process pools from the multiprocessing library. """ import os from concurrent.futures import ProcessPoolExecutor import sys from qiskit.exceptions import QiskitError from qiskit.utils.multiprocessing import local_hardware_info from qiskit.tools.events.pubsub import Publisher from qiskit import user_config def get_platform_parallel_default(): """ Returns the default parallelism flag value for the current platform. Returns: parallel_default: The default parallelism flag value for the current platform. """ # Default False on Windows if sys.platform == "win32": parallel_default = False # On macOS default false on Python >=3.8 elif sys.platform == "darwin": parallel_default = False # On linux (and other OSes) default to True else: parallel_default = True return parallel_default CONFIG = user_config.get_config() if os.getenv("QISKIT_PARALLEL", None) is not None: PARALLEL_DEFAULT = os.getenv("QISKIT_PARALLEL", None).lower() == "true" else: PARALLEL_DEFAULT = get_platform_parallel_default() # Set parallel flag if os.getenv("QISKIT_IN_PARALLEL") is None: os.environ["QISKIT_IN_PARALLEL"] = "FALSE" if os.getenv("QISKIT_NUM_PROCS") is not None: CPU_COUNT = int(os.getenv("QISKIT_NUM_PROCS")) else: CPU_COUNT = CONFIG.get("num_process", local_hardware_info()["cpus"]) def _task_wrapper(param): (task, value, task_args, task_kwargs) = param return task(value, *task_args, **task_kwargs) def parallel_map( # pylint: disable=dangerous-default-value task, values, task_args=(), task_kwargs={}, num_processes=CPU_COUNT ): """ Parallel execution of a mapping of `values` to the function `task`. This is functionally equivalent to:: result = [task(value, *task_args, **task_kwargs) for value in values] On Windows this function defaults to a serial implementation to avoid the overhead from spawning processes in Windows. Args: task (func): Function that is to be called for each value in ``values``. values (array_like): List or array of values for which the ``task`` function is to be evaluated. task_args (list): Optional additional arguments to the ``task`` function. task_kwargs (dict): Optional additional keyword argument to the ``task`` function. num_processes (int): Number of processes to spawn. Returns: result: The result list contains the value of ``task(value, *task_args, **task_kwargs)`` for each value in ``values``. Raises: QiskitError: If user interrupts via keyboard. Events: terra.parallel.start: The collection of parallel tasks are about to start. terra.parallel.update: One of the parallel task has finished. terra.parallel.finish: All the parallel tasks have finished. Examples: .. code-block:: python import time from qiskit.tools.parallel import parallel_map def func(_): time.sleep(0.1) return 0 parallel_map(func, list(range(10))); """ if len(values) == 0: return [] if len(values) == 1: return [task(values[0], *task_args, **task_kwargs)] Publisher().publish("terra.parallel.start", len(values)) nfinished = [0] def _callback(_): nfinished[0] += 1 Publisher().publish("terra.parallel.done", nfinished[0]) # Run in parallel if not Win and not in parallel already if ( num_processes > 1 and os.getenv("QISKIT_IN_PARALLEL") == "FALSE" and CONFIG.get("parallel_enabled", PARALLEL_DEFAULT) ): os.environ["QISKIT_IN_PARALLEL"] = "TRUE" try: results = [] with ProcessPoolExecutor(max_workers=num_processes) as executor: param = ((task, value, task_args, task_kwargs) for value in values) future = executor.map(_task_wrapper, param) results = list(future) Publisher().publish("terra.parallel.done", len(results)) except (KeyboardInterrupt, Exception) as error: if isinstance(error, KeyboardInterrupt): Publisher().publish("terra.parallel.finish") os.environ["QISKIT_IN_PARALLEL"] = "FALSE" raise QiskitError("Keyboard interrupt in parallel_map.") from error # Otherwise just reset parallel flag and error os.environ["QISKIT_IN_PARALLEL"] = "FALSE" raise error Publisher().publish("terra.parallel.finish") os.environ["QISKIT_IN_PARALLEL"] = "FALSE" return results # Cannot do parallel on Windows , if another parallel_map is running in parallel, # or len(values) == 1. results = [] for _, value in enumerate(values): result = task(value, *task_args, **task_kwargs) results.append(result) _callback(0) Publisher().publish("terra.parallel.finish") return results
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# 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. # This file is part of QuTiP: Quantum Toolbox in Python. # # Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names # of its contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ############################################################################### """Progress bars module""" import time import datetime import sys from qiskit.tools.events.pubsub import Subscriber class BaseProgressBar(Subscriber): """An abstract progress bar with some shared functionality.""" def __init__(self): super().__init__() self.type = "progressbar" self.touched = False self.iter = None self.t_start = None self.t_done = None def start(self, iterations): """Start the progress bar. Parameters: iterations (int): Number of iterations. """ self.touched = True self.iter = int(iterations) self.t_start = time.time() def update(self, n): """Update status of progress bar.""" pass def time_elapsed(self): """Return the time elapsed since start. Returns: elapsed_time: Time since progress bar started. """ return "%6.2fs" % (time.time() - self.t_start) def time_remaining_est(self, completed_iter): """Estimate the remaining time left. Parameters: completed_iter (int): Number of iterations completed. Returns: est_time: Estimated time remaining. """ if completed_iter: t_r_est = (time.time() - self.t_start) / completed_iter * (self.iter - completed_iter) else: t_r_est = 0 date_time = datetime.datetime(1, 1, 1) + datetime.timedelta(seconds=t_r_est) time_string = "%02d:%02d:%02d:%02d" % ( date_time.day - 1, date_time.hour, date_time.minute, date_time.second, ) return time_string def finished(self): """Run when progress bar has completed.""" pass class TextProgressBar(BaseProgressBar): """ A simple text-based progress bar. output_handler : the handler the progress bar should be written to, default is sys.stdout, another option is sys.stderr Examples: The progress bar can be used to track the progress of a `parallel_map`. .. code-block:: python import numpy as np import qiskit.tools.jupyter from qiskit.tools.parallel import parallel_map from qiskit.tools.events import TextProgressBar TextProgressBar() %qiskit_progress_bar -t text parallel_map(np.sin, np.linspace(0,10,100)); And it can also be used individually. .. code-block:: python from qiskit.tools.events import TextProgressBar iterations = 100 t = TextProgressBar() t.start(iterations=iterations) for i in range(iterations): # step i of heavy calculation ... t.update(i + 1) # update progress bar """ def __init__(self, output_handler=None): super().__init__() self._init_subscriber() self.output_handler = output_handler if output_handler else sys.stdout def _init_subscriber(self): def _initialize_progress_bar(num_tasks): self.start(num_tasks) self.subscribe("terra.parallel.start", _initialize_progress_bar) def _update_progress_bar(progress): self.update(progress) self.subscribe("terra.parallel.done", _update_progress_bar) def _finish_progress_bar(): self.unsubscribe("terra.parallel.start", _initialize_progress_bar) self.unsubscribe("terra.parallel.done", _update_progress_bar) self.unsubscribe("terra.parallel.finish", _finish_progress_bar) self.finished() self.subscribe("terra.parallel.finish", _finish_progress_bar) def start(self, iterations): self.touched = True self.iter = int(iterations) self.t_start = time.time() pbar = "-" * 50 self.output_handler.write("\r|{}| {}{}{} [{}]".format(pbar, 0, "/", self.iter, "")) def update(self, n): # Don't update if we are not initialized or # the update iteration number is greater than the total iterations set on start. if not self.touched or n > self.iter: return filled_length = int(round(50 * n / self.iter)) pbar = "█" * filled_length + "-" * (50 - filled_length) time_left = self.time_remaining_est(n) self.output_handler.write("\r|{}| {}{}{} [{}]".format(pbar, n, "/", self.iter, time_left)) if n == self.iter: self.output_handler.write("\n") self.output_handler.flush()
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """A module of magic functions""" import time import threading from IPython.display import display # pylint: disable=import-error from IPython.core import magic_arguments # pylint: disable=import-error from IPython.core.magic import cell_magic, Magics, magics_class # pylint: disable=import-error try: import ipywidgets as widgets # pylint: disable=import-error except ImportError: raise ImportError('These functions need ipywidgets. ' 'Run "pip install ipywidgets" before.') import qiskit from qiskit.tools.events.progressbar import TextProgressBar from .progressbar import HTMLProgressBar def _html_checker(job_var, interval, status, header, _interval_set=False): """Internal function that updates the status of a HTML job monitor. Args: job_var (BaseJob): The job to keep track of. interval (int): The status check interval status (widget): HTML ipywidget for output ot screen header (str): String representing HTML code for status. _interval_set (bool): Was interval set by user? """ job_status = job_var.status() job_status_name = job_status.name job_status_msg = job_status.value status.value = header % (job_status_msg) while job_status_name not in ['DONE', 'CANCELLED']: time.sleep(interval) job_status = job_var.status() job_status_name = job_status.name job_status_msg = job_status.value if job_status_name == 'ERROR': break else: if job_status_name == 'QUEUED': job_status_msg += ' (%s)' % job_var.queue_position() if not _interval_set: interval = max(job_var.queue_position(), 2) else: if not _interval_set: interval = 2 status.value = header % (job_status_msg) status.value = header % (job_status_msg) @magics_class class StatusMagic(Magics): """A class of status magic functions. """ @cell_magic @magic_arguments.magic_arguments() @magic_arguments.argument( '-i', '--interval', type=float, default=None, help='Interval for status check.' ) def qiskit_job_status(self, line='', cell=None): """A Jupyter magic function to check the status of a Qiskit job instance. """ args = magic_arguments.parse_argstring(self.qiskit_job_status, line) if args.interval is None: args.interval = 2 _interval_set = False else: _interval_set = True # Split cell lines to get LHS variables cell_lines = cell.split('\n') line_vars = [] for cline in cell_lines: if '=' in cline and '==' not in cline: line_vars.append(cline.replace(' ', '').split('=')[0]) elif '.append(' in cline: line_vars.append(cline.replace(' ', '').split('(')[0]) # Execute the cell self.shell.ex(cell) # Look for all vars that are BaseJob instances jobs = [] for var in line_vars: iter_var = False if '#' not in var: # The line var is a list or array, but we cannot parse the index # so just iterate over the whole array for jobs. if '[' in var: var = var.split('[')[0] iter_var = True elif '.append' in var: var = var.split('.append')[0] iter_var = True if iter_var: for item in self.shell.user_ns[var]: if isinstance(item, qiskit.providers.basejob.BaseJob): jobs.append(item) else: if isinstance(self.shell.user_ns[var], qiskit.providers.basejob.BaseJob): jobs.append(self.shell.user_ns[var]) # Must have one job class if not any(jobs): raise Exception( "Cell must contain at least one variable of BaseJob type.") # List index of job if checking status of multiple jobs. multi_job = False if len(jobs) > 1: multi_job = True job_checkers = [] # Loop over every BaseJob that was found. for idx, job_var in enumerate(jobs): style = "font-size:16px;" if multi_job: idx_str = '[%s]' % idx else: idx_str = '' header = "<p style='{style}'>Job Status {id}: %s </p>".format(id=idx_str, style=style) status = widgets.HTML( value=header % job_var.status().value) thread = threading.Thread(target=_html_checker, args=(job_var, args.interval, status, header, _interval_set)) thread.start() job_checkers.append(status) # Group all HTML widgets into single vertical layout box = widgets.VBox(job_checkers) display(box) @magics_class class ProgressBarMagic(Magics): """A class of progress bar magic functions. """ @cell_magic @magic_arguments.magic_arguments() @magic_arguments.argument( '-t', '--type', type=str, default='html', help="Type of progress bar, 'html' or 'text'." ) def qiskit_progress_bar(self, line='', cell=None): # pylint: disable=W0613 """A Jupyter magic function to generate progressbar. """ args = magic_arguments.parse_argstring(self.qiskit_progress_bar, line) if args.type == 'html': HTMLProgressBar() elif args.type == 'text': TextProgressBar() else: raise qiskit.QiskitError('Invalid progress bar type.') self.shell.ex(cell)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=invalid-name,no-name-in-module,ungrouped-imports """A circuit library widget module""" import ipywidgets as wid from IPython.display import display from qiskit import QuantumCircuit from qiskit.utils import optionals as _optionals from qiskit.utils.deprecation import deprecate_func @_optionals.HAS_MATPLOTLIB.require_in_call def _generate_circuit_library_visualization(circuit: QuantumCircuit): import matplotlib.pyplot as plt circuit = circuit.decompose() ops = circuit.count_ops() num_nl = circuit.num_nonlocal_gates() _fig, (ax0, ax1) = plt.subplots(2, 1) circuit.draw("mpl", ax=ax0) ax1.axis("off") ax1.grid(visible=None) ax1.table( [[circuit.name], [circuit.width()], [circuit.depth()], [sum(ops.values())], [num_nl]], rowLabels=["Circuit Name", "Width", "Depth", "Total Gates", "Non-local Gates"], ) plt.tight_layout() plt.show() @deprecate_func( since="0.25.0", additional_msg="This is unused by Qiskit, and no replacement will be publicly provided.", ) def circuit_data_table(circuit: QuantumCircuit) -> wid.HTML: """Create a HTML table widget for a given quantum circuit. Args: circuit: Input quantum circuit. Returns: Output widget. """ circuit = circuit.decompose() ops = circuit.count_ops() num_nl = circuit.num_nonlocal_gates() html = "<table>" html += """<style> table { font-family: "IBM Plex Sans", Arial, Helvetica, sans-serif; border-collapse: collapse; width: 100%; border-left: 2px solid #212121; } th { text-align: left; padding: 5px 5px 5px 5px; width: 100%; background-color: #988AFC; color: #fff; font-size: 14px; border-left: 2px solid #988AFC; } td { text-align: left; padding: 5px 5px 5px 5px; width: 100%; font-size: 12px; font-weight: medium; } tr:nth-child(even) {background-color: #f6f6f6;} </style>""" html += f"<tr><th>{circuit.name}</th><th></tr>" html += f"<tr><td>Width</td><td>{circuit.width()}</td></tr>" html += f"<tr><td>Depth</td><td>{circuit.depth()}</td></tr>" html += f"<tr><td>Total Gates</td><td>{sum(ops.values())}</td></tr>" html += f"<tr><td>Non-local Gates</td><td>{num_nl}</td></tr>" html += "</table>" out_wid = wid.HTML(html) return out_wid head_style = ( "font-family: IBM Plex Sans, Arial, Helvetica, sans-serif;" " font-size: 20px; font-weight: medium;" ) property_label = wid.HTML( f"<p style='{head_style}'>Circuit Properties</p>", layout=wid.Layout(margin="0px 0px 10px 0px"), ) @deprecate_func( since="0.25.0", additional_msg="This is unused by Qiskit, and no replacement will be publicly provided.", ) def properties_widget(circuit: QuantumCircuit) -> wid.VBox: """Create a HTML table widget with header for a given quantum circuit. Args: circuit: Input quantum circuit. Returns: Output widget. """ properties = wid.VBox( children=[property_label, circuit_data_table(circuit)], layout=wid.Layout(width="40%", height="auto"), ) return properties @_optionals.HAS_PYGMENTS.require_in_call @deprecate_func( since="0.25.0", additional_msg="This is unused by Qiskit, and no replacement will be publicly provided.", ) def qasm_widget(circuit: QuantumCircuit) -> wid.VBox: """Generate a QASM widget with header for a quantum circuit. Args: circuit: Input quantum circuit. Returns: Output widget. """ import pygments from pygments.formatters import HtmlFormatter from qiskit.qasm.pygments import QasmHTMLStyle, OpenQASMLexer qasm_code = circuit.qasm() code = pygments.highlight(qasm_code, OpenQASMLexer(), HtmlFormatter()) html_style = HtmlFormatter(style=QasmHTMLStyle).get_style_defs(".highlight") code_style = ( """ <style> .highlight { font-family: monospace; font-size: 14px; line-height: 1.7em; } .highlight .err { color: #000000; background-color: #FFFFFF } %s </style> """ % html_style ) out = wid.HTML( code_style + code, layout=wid.Layout(max_height="500px", height="auto", overflow="scroll scroll"), ) out_label = wid.HTML( f"<p style='{head_style}'>OpenQASM</p>", layout=wid.Layout(margin="0px 0px 10px 0px"), ) qasm = wid.VBox( children=[out_label, out], layout=wid.Layout( height="auto", max_height="500px", width="60%", margin="0px 0px 0px 20px" ), ) qasm._code_length = len(qasm_code.split("\n")) return qasm @deprecate_func( since="0.25.0", additional_msg="This is unused by Qiskit, and no replacement will be publicly provided.", ) def circuit_diagram_widget() -> wid.Box: """Create a circuit diagram widget. Returns: Output widget. """ # The max circuit height corresponds to a 20Q circuit with flat # classical register. top_out = wid.Output( layout=wid.Layout( width="100%", height="auto", max_height="1000px", overflow="hidden scroll", ) ) top = wid.Box(children=[top_out], layout=wid.Layout(width="100%", height="auto")) return top @deprecate_func( since="0.25.0", additional_msg="This is unused by Qiskit, and no replacement will be publicly provided.", ) def circuit_library_widget(circuit: QuantumCircuit) -> None: """Create a circuit library widget. Args: circuit: Input quantum circuit. """ qasm_wid = qasm_widget(circuit) sep_length = str(min(20 * qasm_wid._code_length, 495)) # The separator widget sep = wid.HTML( f"<div style='border-left: 3px solid #212121;height: {sep_length}px;'></div>", layout=wid.Layout(height="auto", max_height="495px", margin="40px 0px 0px 20px"), ) bottom = wid.HBox( children=[properties_widget(circuit), sep, qasm_widget(circuit)], layout=wid.Layout(max_height="550px", height="auto"), ) top = circuit_diagram_widget() with top.children[0]: display(circuit.decompose().draw(output="mpl")) display(wid.VBox(children=[top, bottom], layout=wid.Layout(width="100%", height="auto")))
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# 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. # pylint: disable=unused-argument """A module for monitoring backends.""" import time from sys import modules from IPython.display import HTML, display from IPython.core.magic import line_magic, Magics, magics_class import qiskit from qiskit.utils import local_hardware_info @magics_class class VersionTable(Magics): """A class of status magic functions.""" @line_magic def qiskit_version_table(self, line="", cell=None): """ Print an HTML-formatted table with version numbers for Qiskit and its dependencies. This should make it possible to reproduce the environment and the calculation later on. """ html = "<h3>Version Information</h3>" html += "<table>" html += "<tr><th>Software</th><th>Version</th></tr>" packages = {"qiskit": None} packages["qiskit-terra"] = qiskit.__version__ qiskit_modules = {module.split(".")[0] for module in modules.keys() if "qiskit" in module} for qiskit_module in qiskit_modules: packages[qiskit_module] = getattr(modules[qiskit_module], "__version__", None) from importlib.metadata import metadata, PackageNotFoundError try: packages["qiskit"] = metadata("qiskit")["Version"] except PackageNotFoundError: packages["qiskit"] = None for name, version in packages.items(): if name == "qiskit" or version: html += f"<tr><td><code>{name}</code></td><td>{version}</td></tr>" html += "<tr><th colspan='2'>System information</th></tr>" local_hw_info = local_hardware_info() sys_info = [ ("Python version", local_hw_info["python_version"]), ("Python compiler", local_hw_info["python_compiler"]), ("Python build", local_hw_info["python_build"]), ("OS", "%s" % local_hw_info["os"]), ("CPUs", "%s" % local_hw_info["cpus"]), ("Memory (Gb)", "%s" % local_hw_info["memory"]), ] for name, version in sys_info: html += f"<tr><td>{name}</td><td>{version}</td></tr>" html += "<tr><td colspan='2'>%s</td></tr>" % time.strftime("%a %b %d %H:%M:%S %Y %Z") html += "</table>" return display(HTML(html))
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# 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. """A module for monitoring various qiskit functionality""" import sys import time def _text_checker( job, interval, _interval_set=False, quiet=False, output=sys.stdout, line_discipline="\r" ): """A text-based job status checker Args: job (BaseJob): The job to check. interval (int): The interval at which to check. _interval_set (bool): Was interval time set by user? quiet (bool): If True, do not print status messages. output (file): The file like object to write status messages to. By default this is sys.stdout. line_discipline (string): character emitted at start of a line of job monitor output, This defaults to \\r. """ status = job.status() msg = status.value prev_msg = msg msg_len = len(msg) if not quiet: print("{}{}: {}".format(line_discipline, "Job Status", msg), end="", file=output) while status.name not in ["DONE", "CANCELLED", "ERROR"]: time.sleep(interval) status = job.status() msg = status.value if status.name == "QUEUED": msg += " (%s)" % job.queue_position() if job.queue_position() is None: interval = 2 elif not _interval_set: interval = max(job.queue_position(), 2) else: if not _interval_set: interval = 2 # Adjust length of message so there are no artifacts if len(msg) < msg_len: msg += " " * (msg_len - len(msg)) elif len(msg) > msg_len: msg_len = len(msg) if msg != prev_msg and not quiet: print("{}{}: {}".format(line_discipline, "Job Status", msg), end="", file=output) prev_msg = msg if not quiet: print("", file=output) def job_monitor(job, interval=None, quiet=False, output=sys.stdout, line_discipline="\r"): """Monitor the status of a IBMQJob instance. Args: job (BaseJob): Job to monitor. interval (int): Time interval between status queries. quiet (bool): If True, do not print status messages. output (file): The file like object to write status messages to. By default this is sys.stdout. line_discipline (string): character emitted at start of a line of job monitor output, This defaults to \\r. Examples: .. code-block:: python from qiskit import BasicAer, transpile from qiskit.circuit import QuantumCircuit from qiskit.tools.monitor import job_monitor sim_backend = BasicAer.get_backend("qasm_simulator") qc = QuantumCircuit(2, 2) qc.h(0) qc.cx(0, 1) qc.measure_all() tqc = transpile(qc, sim_backend) job_sim = sim_backend.run(tqc) job_monitor(job_sim) """ if interval is None: _interval_set = False interval = 5 else: _interval_set = True _text_checker( job, interval, _interval_set, quiet=quiet, output=output, line_discipline=line_discipline )
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# 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. """Durations of instructions, one of transpiler configurations.""" from __future__ import annotations from typing import Optional, List, Tuple, Union, Iterable import qiskit.circuit from qiskit.circuit import Barrier, Delay from qiskit.circuit import Instruction, Qubit, ParameterExpression from qiskit.circuit.duration import duration_in_dt from qiskit.providers import Backend from qiskit.transpiler.exceptions import TranspilerError from qiskit.utils.deprecation import deprecate_arg from qiskit.utils.units import apply_prefix def _is_deprecated_qubits_argument(qubits: Union[int, list[int], Qubit, list[Qubit]]) -> bool: if isinstance(qubits, (int, Qubit)): qubits = [qubits] return isinstance(qubits[0], Qubit) class InstructionDurations: """Helper class to provide durations of instructions for scheduling. It stores durations (gate lengths) and dt to be used at the scheduling stage of transpiling. It can be constructed from ``backend`` or ``instruction_durations``, which is an argument of :func:`transpile`. The duration of an instruction depends on the instruction (given by name), the qubits, and optionally the parameters of the instruction. Note that these fields are used as keys in dictionaries that are used to retrieve the instruction durations. Therefore, users must use the exact same parameter value to retrieve an instruction duration as the value with which it was added. """ def __init__( self, instruction_durations: "InstructionDurationsType" | None = None, dt: float = None ): self.duration_by_name: dict[str, tuple[float, str]] = {} self.duration_by_name_qubits: dict[tuple[str, tuple[int, ...]], tuple[float, str]] = {} self.duration_by_name_qubits_params: dict[ tuple[str, tuple[int, ...], tuple[float, ...]], tuple[float, str] ] = {} self.dt = dt if instruction_durations: self.update(instruction_durations) def __str__(self): """Return a string representation of all stored durations.""" string = "" for k, v in self.duration_by_name.items(): string += k string += ": " string += str(v[0]) + " " + v[1] string += "\n" for k, v in self.duration_by_name_qubits.items(): string += k[0] + str(k[1]) string += ": " string += str(v[0]) + " " + v[1] string += "\n" return string @classmethod def from_backend(cls, backend: Backend): """Construct an :class:`InstructionDurations` object from the backend. Args: backend: backend from which durations (gate lengths) and dt are extracted. Returns: InstructionDurations: The InstructionDurations constructed from backend. Raises: TranspilerError: If dt and dtm is different in the backend. """ # All durations in seconds in gate_length instruction_durations = [] backend_properties = backend.properties() if hasattr(backend_properties, "_gates"): for gate, insts in backend_properties._gates.items(): for qubits, props in insts.items(): if "gate_length" in props: gate_length = props["gate_length"][0] # Throw away datetime at index 1 instruction_durations.append((gate, qubits, gate_length, "s")) for q, props in backend.properties()._qubits.items(): if "readout_length" in props: readout_length = props["readout_length"][0] # Throw away datetime at index 1 instruction_durations.append(("measure", [q], readout_length, "s")) try: dt = backend.configuration().dt except AttributeError: dt = None return InstructionDurations(instruction_durations, dt=dt) def update(self, inst_durations: "InstructionDurationsType" | None, dt: float = None): """Update self with inst_durations (inst_durations overwrite self). Args: inst_durations: Instruction durations to be merged into self (overwriting self). dt: Sampling duration in seconds of the target backend. Returns: InstructionDurations: The updated InstructionDurations. Raises: TranspilerError: If the format of instruction_durations is invalid. """ if dt: self.dt = dt if inst_durations is None: return self if isinstance(inst_durations, InstructionDurations): self.duration_by_name.update(inst_durations.duration_by_name) self.duration_by_name_qubits.update(inst_durations.duration_by_name_qubits) self.duration_by_name_qubits_params.update( inst_durations.duration_by_name_qubits_params ) else: for i, items in enumerate(inst_durations): if not isinstance(items[-1], str): items = (*items, "dt") # set default unit if len(items) == 4: # (inst_name, qubits, duration, unit) inst_durations[i] = (*items[:3], None, items[3]) else: inst_durations[i] = items # assert (inst_name, qubits, duration, parameters, unit) if len(inst_durations[i]) != 5: raise TranspilerError( "Each entry of inst_durations dictionary must be " "(inst_name, qubits, duration) or " "(inst_name, qubits, duration, unit) or" "(inst_name, qubits, duration, parameters) or" "(inst_name, qubits, duration, parameters, unit) " f"received {inst_durations[i]}." ) if inst_durations[i][2] is None: raise TranspilerError(f"None duration for {inst_durations[i]}.") for name, qubits, duration, parameters, unit in inst_durations: if isinstance(qubits, int): qubits = [qubits] if isinstance(parameters, (int, float)): parameters = [parameters] if qubits is None: self.duration_by_name[name] = duration, unit elif parameters is None: self.duration_by_name_qubits[(name, tuple(qubits))] = duration, unit else: key = (name, tuple(qubits), tuple(parameters)) self.duration_by_name_qubits_params[key] = duration, unit return self @deprecate_arg( "qubits", deprecation_description=( "Using a Qubit or List[Qubit] for the ``qubits`` argument to InstructionDurations.get()" ), additional_msg="Instead, use an integer for the qubit index.", since="0.19.0", predicate=_is_deprecated_qubits_argument, ) def get( self, inst: str | qiskit.circuit.Instruction, qubits: int | list[int] | Qubit | list[Qubit] | list[int | Qubit], unit: str = "dt", parameters: list[float] | None = None, ) -> float: """Get the duration of the instruction with the name, qubits, and parameters. Some instructions may have a parameter dependent duration. Args: inst: An instruction or its name to be queried. qubits: Qubits or its indices that the instruction acts on. unit: The unit of duration to be returned. It must be 's' or 'dt'. parameters: The value of the parameters of the desired instruction. Returns: float|int: The duration of the instruction on the qubits. Raises: TranspilerError: No duration is defined for the instruction. """ if isinstance(inst, Barrier): return 0 elif isinstance(inst, Delay): return self._convert_unit(inst.duration, inst.unit, unit) if isinstance(inst, Instruction): inst_name = inst.name else: inst_name = inst if isinstance(qubits, (int, Qubit)): qubits = [qubits] if isinstance(qubits[0], Qubit): qubits = [q.index for q in qubits] try: return self._get(inst_name, qubits, unit, parameters) except TranspilerError as ex: raise TranspilerError( f"Duration of {inst_name} on qubits {qubits} is not found." ) from ex def _get( self, name: str, qubits: list[int], to_unit: str, parameters: Iterable[float] | None = None, ) -> float: """Get the duration of the instruction with the name, qubits, and parameters.""" if name == "barrier": return 0 if parameters is not None: key = (name, tuple(qubits), tuple(parameters)) else: key = (name, tuple(qubits)) if key in self.duration_by_name_qubits_params: duration, unit = self.duration_by_name_qubits_params[key] elif key in self.duration_by_name_qubits: duration, unit = self.duration_by_name_qubits[key] elif name in self.duration_by_name: duration, unit = self.duration_by_name[name] else: raise TranspilerError(f"No value is found for key={key}") return self._convert_unit(duration, unit, to_unit) def _convert_unit(self, duration: float, from_unit: str, to_unit: str) -> float: if from_unit.endswith("s") and from_unit != "s": duration = apply_prefix(duration, from_unit) from_unit = "s" # assert both from_unit and to_unit in {'s', 'dt'} if from_unit == to_unit: return duration if self.dt is None: raise TranspilerError( f"dt is necessary to convert durations from '{from_unit}' to '{to_unit}'" ) if from_unit == "s" and to_unit == "dt": if isinstance(duration, ParameterExpression): return duration / self.dt return duration_in_dt(duration, self.dt) elif from_unit == "dt" and to_unit == "s": return duration * self.dt else: raise TranspilerError(f"Conversion from '{from_unit}' to '{to_unit}' is not supported") def units_used(self) -> set[str]: """Get the set of all units used in this instruction durations. Returns: Set of units used in this instruction durations. """ units_used = set() for _, unit in self.duration_by_name_qubits.values(): units_used.add(unit) for _, unit in self.duration_by_name.values(): units_used.add(unit) return units_used InstructionDurationsType = Union[ List[Tuple[str, Optional[Iterable[int]], float, Optional[Iterable[float]], str]], List[Tuple[str, Optional[Iterable[int]], float, Optional[Iterable[float]]]], List[Tuple[str, Optional[Iterable[int]], float, str]], List[Tuple[str, Optional[Iterable[int]], float]], InstructionDurations, ] """List of tuples representing (instruction name, qubits indices, parameters, duration)."""
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# 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. """A swap strategy pass for blocks of commuting gates.""" from __future__ import annotations from collections import defaultdict from qiskit.circuit import Gate, QuantumCircuit, Qubit from qiskit.converters import circuit_to_dag from qiskit.dagcircuit import DAGCircuit, DAGOpNode from qiskit.transpiler import TransformationPass, Layout, TranspilerError from qiskit.transpiler.passes.routing.commuting_2q_gate_routing.swap_strategy import SwapStrategy from qiskit.transpiler.passes.routing.commuting_2q_gate_routing.commuting_2q_block import ( Commuting2qBlock, ) class Commuting2qGateRouter(TransformationPass): """A class to swap route one or more commuting gates to the coupling map. This pass routes blocks of commuting two-qubit gates encapsulated as :class:`.Commuting2qBlock` instructions. This pass will not apply to other instructions. The mapping to the coupling map is done using swap strategies, see :class:`.SwapStrategy`. The swap strategy should suit the problem and the coupling map. This transpiler pass should ideally be executed before the quantum circuit is enlarged with any idle ancilla qubits. Otherwise we may swap qubits outside of the portion of the chip we want to use. Therefore, the swap strategy and its associated coupling map do not represent physical qubits. Instead, they represent an intermediate mapping that corresponds to the physical qubits once the initial layout is applied. The example below shows how to map a four qubit :class:`.PauliEvolutionGate` to qubits 0, 1, 3, and 4 of the five qubit device with the coupling map .. parsed-literal:: 0 -- 1 -- 2 | 3 | 4 To do this we use a line swap strategy for qubits 0, 1, 3, and 4 defined it in terms of virtual qubits 0, 1, 2, and 3. .. code-block:: python from qiskit import QuantumCircuit from qiskit.opflow import PauliSumOp from qiskit.circuit.library import PauliEvolutionGate from qiskit.transpiler import Layout, CouplingMap, PassManager from qiskit.transpiler.passes import FullAncillaAllocation from qiskit.transpiler.passes import EnlargeWithAncilla from qiskit.transpiler.passes import ApplyLayout from qiskit.transpiler.passes import SetLayout from qiskit.transpiler.passes.routing.commuting_2q_gate_routing import ( SwapStrategy, FindCommutingPauliEvolutions, Commuting2qGateRouter, ) # Define the circuit on virtual qubits op = PauliSumOp.from_list([("IZZI", 1), ("ZIIZ", 2), ("ZIZI", 3)]) circ = QuantumCircuit(4) circ.append(PauliEvolutionGate(op, 1), range(4)) # Define the swap strategy on qubits before the initial_layout is applied. swap_strat = SwapStrategy.from_line([0, 1, 2, 3]) # Chose qubits 0, 1, 3, and 4 from the backend coupling map shown above. backend_cmap = CouplingMap(couplinglist=[(0, 1), (1, 2), (1, 3), (3, 4)]) initial_layout = Layout.from_intlist([0, 1, 3, 4], *circ.qregs) pm_pre = PassManager( [ FindCommutingPauliEvolutions(), Commuting2qGateRouter(swap_strat), SetLayout(initial_layout), FullAncillaAllocation(backend_cmap), EnlargeWithAncilla(), ApplyLayout(), ] ) # Insert swap gates, map to initial_layout and finally enlarge with ancilla. pm_pre.run(circ).draw("mpl") This pass manager relies on the ``current_layout`` which corresponds to the qubit layout as swap gates are applied. The pass will traverse all nodes in the dag. If a node should be routed using a swap strategy then it will be decomposed into sub-instructions with swap layers in between and the ``current_layout`` will be modified. Nodes that should not be routed using swap strategies will be added back to the dag taking the ``current_layout`` into account. """ def __init__( self, swap_strategy: SwapStrategy | None = None, edge_coloring: dict[tuple[int, int], int] | None = None, ) -> None: r""" Args: swap_strategy: An instance of a :class:`.SwapStrategy` that holds the swap layers that are used, and the order in which to apply them, to map the instruction to the hardware. If this field is not given if should be contained in the property set of the pass. This allows other passes to determine the most appropriate swap strategy at run-time. edge_coloring: An optional edge coloring of the coupling map (I.e. no two edges that share a node have the same color). If the edge coloring is given then the commuting gates that can be simultaneously applied given the current qubit permutation are grouped according to the edge coloring and applied according to this edge coloring. Here, a color is an int which is used as the index to define and access the groups of commuting gates that can be applied simultaneously. If the edge coloring is not given then the sets will be built-up using a greedy algorithm. The edge coloring is useful to position gates such as ``RZZGate``\s next to swap gates to exploit CX cancellations. """ super().__init__() self._swap_strategy = swap_strategy self._bit_indices: dict[Qubit, int] | None = None self._edge_coloring = edge_coloring def run(self, dag: DAGCircuit) -> DAGCircuit: """Run the pass by decomposing the nodes it applies on. Args: dag: The dag to which we will add swaps. Returns: A dag where swaps have been added for the intended gate type. Raises: TranspilerError: If the swap strategy was not given at init time and there is no swap strategy in the property set. TranspilerError: If the quantum circuit contains more than one qubit register. TranspilerError: If there are qubits that are not contained in the quantum register. """ if self._swap_strategy is None: swap_strategy = self.property_set["swap_strategy"] if swap_strategy is None: raise TranspilerError("No swap strategy given at init or in the property set.") else: swap_strategy = self._swap_strategy if len(dag.qregs) != 1: raise TranspilerError( f"{self.__class__.__name__} runs on circuits with one quantum register." ) if len(dag.qubits) != next(iter(dag.qregs.values())).size: raise TranspilerError("Circuit has qubits not contained in the qubit register.") new_dag = dag.copy_empty_like() current_layout = Layout.generate_trivial_layout(*dag.qregs.values()) # Used to keep track of nodes that do not decompose using swap strategies. accumulator = new_dag.copy_empty_like() for node in dag.topological_op_nodes(): if isinstance(node.op, Commuting2qBlock): # Check that the swap strategy creates enough connectivity for the node. self._check_edges(dag, node, swap_strategy) # Compose any accumulated non-swap strategy gates to the dag accumulator = self._compose_non_swap_nodes(accumulator, current_layout, new_dag) # Decompose the swap-strategy node and add to the dag. new_dag.compose(self.swap_decompose(dag, node, current_layout, swap_strategy)) else: accumulator.apply_operation_back(node.op, node.qargs, node.cargs) self._compose_non_swap_nodes(accumulator, current_layout, new_dag) return new_dag def _compose_non_swap_nodes( self, accumulator: DAGCircuit, layout: Layout, new_dag: DAGCircuit ) -> DAGCircuit: """Add all the non-swap strategy nodes that we have accumulated up to now. This method also resets the node accumulator to an empty dag. Args: layout: The current layout that keeps track of the swaps. new_dag: The new dag that we are building up. accumulator: A DAG to keep track of nodes that do not decompose using swap strategies. Returns: A new accumulator with the same registers as ``new_dag``. """ # Add all the non-swap strategy nodes that we have accumulated up to now. order = layout.reorder_bits(new_dag.qubits) order_bits: list[int | None] = [None] * len(layout) for idx, val in enumerate(order): order_bits[val] = idx new_dag.compose(accumulator, qubits=order_bits) # Re-initialize the node accumulator return new_dag.copy_empty_like() def _position_in_cmap(self, dag: DAGCircuit, j: int, k: int, layout: Layout) -> tuple[int, ...]: """A helper function to track the movement of virtual qubits through the swaps. Args: j: The index of decision variable j (i.e. virtual qubit). k: The index of decision variable k (i.e. virtual qubit). layout: The current layout that takes into account previous swap gates. Returns: The position in the coupling map of the virtual qubits j and k as a tuple. """ bit0 = dag.find_bit(layout.get_physical_bits()[j]).index bit1 = dag.find_bit(layout.get_physical_bits()[k]).index return bit0, bit1 def _build_sub_layers( self, current_layer: dict[tuple[int, int], Gate] ) -> list[dict[tuple[int, int], Gate]]: """A helper method to build-up sets of gates to simultaneously apply. This is done with an edge coloring if the ``edge_coloring`` init argument was given or with a greedy algorithm if not. With an edge coloring all gates on edges with the same color will be applied simultaneously. These sublayers are applied in the order of their color, which is an int, in increasing color order. Args: current_layer: All gates in the current layer can be applied given the qubit ordering of the current layout. However, not all gates in the current layer can be applied simultaneously. This function creates sub-layers by building up sub-layers of gates. All gates in a sub-layer can simultaneously be applied given the coupling map and current qubit configuration. Returns: A list of gate dicts that can be applied. The gates a position 0 are applied first. A gate dict has the qubit tuple as key and the gate to apply as value. """ if self._edge_coloring is not None: return self._edge_coloring_build_sub_layers(current_layer) else: return self._greedy_build_sub_layers(current_layer) def _edge_coloring_build_sub_layers( self, current_layer: dict[tuple[int, int], Gate] ) -> list[dict[tuple[int, int], Gate]]: """The edge coloring method of building sub-layers of commuting gates.""" sub_layers: list[dict[tuple[int, int], Gate]] = [ {} for _ in set(self._edge_coloring.values()) ] for edge, gate in current_layer.items(): color = self._edge_coloring[edge] sub_layers[color][edge] = gate return sub_layers @staticmethod def _greedy_build_sub_layers( current_layer: dict[tuple[int, int], Gate] ) -> list[dict[tuple[int, int], Gate]]: """The greedy method of building sub-layers of commuting gates.""" sub_layers = [] while len(current_layer) > 0: current_sub_layer, remaining_gates = {}, {} blocked_vertices: set[tuple] = set() for edge, evo_gate in current_layer.items(): if blocked_vertices.isdisjoint(edge): current_sub_layer[edge] = evo_gate # A vertex becomes blocked once a gate is applied to it. blocked_vertices = blocked_vertices.union(edge) else: remaining_gates[edge] = evo_gate current_layer = remaining_gates sub_layers.append(current_sub_layer) return sub_layers def swap_decompose( self, dag: DAGCircuit, node: DAGOpNode, current_layout: Layout, swap_strategy: SwapStrategy ) -> DAGCircuit: """Take an instance of :class:`.Commuting2qBlock` and map it to the coupling map. The mapping is done with the swap strategy. Args: dag: The dag which contains the :class:`.Commuting2qBlock` we route. node: A node whose operation is a :class:`.Commuting2qBlock`. current_layout: The layout before the swaps are applied. This function will modify the layout so that subsequent gates can be properly composed on the dag. swap_strategy: The swap strategy used to decompose the node. Returns: A dag that is compatible with the coupling map where swap gates have been added to map the gates in the :class:`.Commuting2qBlock` to the hardware. """ trivial_layout = Layout.generate_trivial_layout(*dag.qregs.values()) gate_layers = self._make_op_layers(dag, node.op, current_layout, swap_strategy) # Iterate over and apply gate layers max_distance = max(gate_layers.keys()) circuit_with_swap = QuantumCircuit(len(dag.qubits)) for i in range(max_distance + 1): # Get current layer and replace the problem indices j,k by the corresponding # positions in the coupling map. The current layer corresponds # to all the gates that can be applied at the ith swap layer. current_layer = {} for (j, k), local_gate in gate_layers.get(i, {}).items(): current_layer[self._position_in_cmap(dag, j, k, current_layout)] = local_gate # Not all gates that are applied at the ith swap layer can be applied at the same # time. We therefore greedily build sub-layers. sub_layers = self._build_sub_layers(current_layer) # Apply sub-layers for sublayer in sub_layers: for edge, local_gate in sublayer.items(): circuit_with_swap.append(local_gate, edge) # Apply SWAP gates if i < max_distance: for swap in swap_strategy.swap_layer(i): (j, k) = [trivial_layout.get_physical_bits()[vertex] for vertex in swap] circuit_with_swap.swap(j, k) current_layout.swap(j, k) return circuit_to_dag(circuit_with_swap) def _make_op_layers( self, dag: DAGCircuit, op: Commuting2qBlock, layout: Layout, swap_strategy: SwapStrategy ) -> dict[int, dict[tuple, Gate]]: """Creates layers of two-qubit gates based on the distance in the swap strategy.""" gate_layers: dict[int, dict[tuple, Gate]] = defaultdict(dict) for node in op.node_block: edge = (dag.find_bit(node.qargs[0]).index, dag.find_bit(node.qargs[1]).index) bit0 = layout.get_virtual_bits()[dag.qubits[edge[0]]] bit1 = layout.get_virtual_bits()[dag.qubits[edge[1]]] distance = swap_strategy.distance_matrix[bit0, bit1] gate_layers[distance][edge] = node.op return gate_layers def _check_edges(self, dag: DAGCircuit, node: DAGOpNode, swap_strategy: SwapStrategy): """Check if the swap strategy can create the required connectivity. Args: node: The dag node for which to check if the swap strategy provides enough connectivity. swap_strategy: The swap strategy that is being used. Raises: TranspilerError: If there is an edge that the swap strategy cannot accommodate and if the pass has been configured to raise on such issues. """ required_edges = set() for sub_node in node.op: edge = (dag.find_bit(sub_node.qargs[0]).index, dag.find_bit(sub_node.qargs[1]).index) required_edges.add(edge) # Check that the swap strategy supports all required edges if not required_edges.issubset(swap_strategy.possible_edges): raise TranspilerError( f"{swap_strategy} cannot implement all edges in {required_edges}." )
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# 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. """Remove all barriers in a circuit""" from qiskit.dagcircuit import DAGCircuit from qiskit.transpiler.basepasses import TransformationPass from qiskit.transpiler.passes.utils import control_flow class RemoveBarriers(TransformationPass): """Return a circuit with any barrier removed. This transformation is not semantics preserving. Example: .. plot:: :include-source: from qiskit import QuantumCircuit from qiskit.transpiler.passes import RemoveBarriers circuit = QuantumCircuit(1) circuit.x(0) circuit.barrier() circuit.h(0) circuit = RemoveBarriers()(circuit) circuit.draw('mpl') """ @control_flow.trivial_recurse def run(self, dag: DAGCircuit) -> DAGCircuit: """Run the RemoveBarriers pass on `dag`.""" dag.remove_all_ops_named("barrier") return dag
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# 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. """Base classes for an approximate circuit definition.""" from __future__ import annotations from abc import ABC, abstractmethod from typing import Optional, SupportsFloat import numpy as np from qiskit import QuantumCircuit class ApproximateCircuit(QuantumCircuit, ABC): """A base class that represents an approximate circuit.""" def __init__(self, num_qubits: int, name: Optional[str] = None) -> None: """ Args: num_qubits: number of qubit this circuit will span. name: a name of the circuit. """ super().__init__(num_qubits, name=name) @property @abstractmethod def thetas(self) -> np.ndarray: """ The property is not implemented and raises a ``NotImplementedException`` exception. Returns: a vector of parameters of this circuit. """ raise NotImplementedError @abstractmethod def build(self, thetas: np.ndarray) -> None: """ Constructs this circuit out of the parameters(thetas). Parameter values must be set before constructing the circuit. Args: thetas: a vector of parameters to be set in this circuit. """ raise NotImplementedError class ApproximatingObjective(ABC): """ A base class for an optimization problem definition. An implementing class must provide at least an implementation of the ``objective`` method. In such case only gradient free optimizers can be used. Both method, ``objective`` and ``gradient``, preferable to have in an implementation. """ def __init__(self) -> None: # must be set before optimization self._target_matrix: np.ndarray | None = None @abstractmethod def objective(self, param_values: np.ndarray) -> SupportsFloat: """ Computes a value of the objective function given a vector of parameter values. Args: param_values: a vector of parameter values for the optimization problem. Returns: a float value of the objective function. """ raise NotImplementedError @abstractmethod def gradient(self, param_values: np.ndarray) -> np.ndarray: """ Computes a gradient with respect to parameters given a vector of parameter values. Args: param_values: a vector of parameter values for the optimization problem. Returns: an array of gradient values. """ raise NotImplementedError @property def target_matrix(self) -> np.ndarray: """ Returns: a matrix being approximated """ return self._target_matrix @target_matrix.setter def target_matrix(self, target_matrix: np.ndarray) -> None: """ Args: target_matrix: a matrix to approximate in the optimization procedure. """ self._target_matrix = target_matrix @property @abstractmethod def num_thetas(self) -> int: """ Returns: the number of parameters in this optimization problem. """ raise NotImplementedError