text
stringlengths
4
4.46M
id
stringlengths
13
126
metadata
dict
__index_level_0__
int64
0
415
# 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. """Parameter Vector Class to simplify management of parameter lists.""" from uuid import uuid4, UUID from .parameter import Parameter class ParameterVectorElement(Parameter): """An element of a ParameterVector.""" ___slots__ = ("_vector", "_index") def __init__(self, vector, index, uuid=None): super().__init__(f"{vector.name}[{index}]", uuid=uuid) self._vector = vector self._index = index @property def index(self): """Get the index of this element in the parent vector.""" return self._index @property def vector(self): """Get the parent vector instance.""" return self._vector def __getstate__(self): return super().__getstate__() + (self._vector, self._index) def __setstate__(self, state): *super_state, vector, index = state super().__setstate__(super_state) self._vector = vector self._index = index class ParameterVector: """ParameterVector class to quickly generate lists of parameters.""" __slots__ = ("_name", "_params", "_root_uuid") def __init__(self, name, length=0): self._name = name self._root_uuid = uuid4() root_uuid_int = self._root_uuid.int self._params = [ ParameterVectorElement(self, i, UUID(int=root_uuid_int + i)) for i in range(length) ] @property def name(self): """Returns the name of the ParameterVector.""" return self._name @property def params(self): """Returns the list of parameters in the ParameterVector.""" return self._params def index(self, value): """Returns first index of value.""" return self._params.index(value) def __getitem__(self, key): return self.params[key] def __iter__(self): return iter(self.params) def __len__(self): return len(self._params) def __str__(self): return f"{self.name}, {[str(item) for item in self.params]}" def __repr__(self): return f"{self.__class__.__name__}(name={repr(self.name)}, length={len(self)})" def resize(self, length): """Resize the parameter vector. If necessary, new elements are generated. Note that the UUID of each :class:`.Parameter` element will be generated deterministically given the root UUID of the ``ParameterVector`` and the index of the element. In particular, if a ``ParameterVector`` is resized to be smaller and then later resized to be larger, the UUID of the later generated element at a given index will be the same as the UUID of the previous element at that index. This is to ensure that the parameter instances do not change. >>> from qiskit.circuit import ParameterVector >>> pv = ParameterVector("theta", 20) >>> elt_19 = pv[19] >>> rv.resize(10) >>> rv.resize(20) >>> pv[19] == elt_19 True """ if length > len(self._params): root_uuid_int = self._root_uuid.int self._params.extend( [ ParameterVectorElement(self, i, UUID(int=root_uuid_int + i)) for i in range(len(self._params), length) ] ) else: del self._params[length:]
qiskit/qiskit/circuit/parametervector.py/0
{ "file_path": "qiskit/qiskit/circuit/parametervector.py", "repo_id": "qiskit", "token_count": 1523 }
194
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2024. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=invalid-sequence-index """Circuit transpile function""" import logging from time import time from typing import List, Union, Dict, Callable, Any, Optional, TypeVar import warnings from qiskit import user_config from qiskit.circuit.quantumcircuit import QuantumCircuit from qiskit.dagcircuit import DAGCircuit from qiskit.providers.backend import Backend from qiskit.providers.backend_compat import BackendV2Converter from qiskit.providers.models.backendproperties import BackendProperties from qiskit.pulse import Schedule, InstructionScheduleMap from qiskit.transpiler import Layout, CouplingMap, PropertySet from qiskit.transpiler.basepasses import BasePass from qiskit.transpiler.exceptions import TranspilerError, CircuitTooWideForTarget from qiskit.transpiler.instruction_durations import InstructionDurationsType from qiskit.transpiler.passes.synthesis.high_level_synthesis import HLSConfig from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager from qiskit.transpiler.target import Target logger = logging.getLogger(__name__) _CircuitT = TypeVar("_CircuitT", bound=Union[QuantumCircuit, List[QuantumCircuit]]) def transpile( # pylint: disable=too-many-return-statements circuits: _CircuitT, backend: Optional[Backend] = None, basis_gates: Optional[List[str]] = None, inst_map: Optional[List[InstructionScheduleMap]] = None, coupling_map: Optional[Union[CouplingMap, List[List[int]]]] = None, backend_properties: Optional[BackendProperties] = None, initial_layout: Optional[Union[Layout, Dict, List]] = None, layout_method: Optional[str] = None, routing_method: Optional[str] = None, translation_method: Optional[str] = None, scheduling_method: Optional[str] = None, instruction_durations: Optional[InstructionDurationsType] = None, dt: Optional[float] = None, approximation_degree: Optional[float] = 1.0, timing_constraints: Optional[Dict[str, int]] = None, seed_transpiler: Optional[int] = None, optimization_level: Optional[int] = None, callback: Optional[Callable[[BasePass, DAGCircuit, float, PropertySet, int], Any]] = None, output_name: Optional[Union[str, List[str]]] = None, unitary_synthesis_method: str = "default", unitary_synthesis_plugin_config: Optional[dict] = None, target: Optional[Target] = None, hls_config: Optional[HLSConfig] = None, init_method: Optional[str] = None, optimization_method: Optional[str] = None, ignore_backend_supplied_default_methods: bool = False, num_processes: Optional[int] = None, qubits_initially_zero: bool = True, ) -> _CircuitT: """Transpile one or more circuits, according to some desired transpilation targets. Transpilation is potentially done in parallel using multiprocessing when ``circuits`` is a list with > 1 :class:`~.QuantumCircuit` object, depending on the local environment and configuration. The prioritization of transpilation target constraints works as follows: if a ``target`` input is provided, it will take priority over any ``backend`` input or loose constraints (``basis_gates``, ``inst_map``, ``coupling_map``, ``backend_properties``, ``instruction_durations``, ``dt`` or ``timing_constraints``). If a ``backend`` is provided together with any loose constraint from the list above, the loose constraint will take priority over the corresponding backend constraint. This behavior is independent of whether the ``backend`` instance is of type :class:`.BackendV1` or :class:`.BackendV2`, as summarized in the table below. The first column in the table summarizes the potential user-provided constraints, and each cell shows whether the priority is assigned to that specific constraint input or another input (`target`/`backend(V1)`/`backend(V2)`). ============================ ========= ======================== ======================= User Provided target backend(V1) backend(V2) ============================ ========= ======================== ======================= **basis_gates** target basis_gates basis_gates **coupling_map** target coupling_map coupling_map **instruction_durations** target instruction_durations instruction_durations **inst_map** target inst_map inst_map **dt** target dt dt **timing_constraints** target timing_constraints timing_constraints **backend_properties** target backend_properties backend_properties ============================ ========= ======================== ======================= Args: circuits: Circuit(s) to transpile backend: If set, the transpiler will compile the input circuit to this target device. If any other option is explicitly set (e.g., ``coupling_map``), it will override the backend's. basis_gates: List of basis gate names to unroll to (e.g: ``['u1', 'u2', 'u3', 'cx']``). If ``None``, do not unroll. inst_map: Mapping of unrolled gates to pulse schedules. If this is not provided, transpiler tries to get from the backend. If any user defined calibration is found in the map and this is used in a circuit, transpiler attaches the custom gate definition to the circuit. This enables one to flexibly override the low-level instruction implementation. This feature is available iff the backend supports the pulse gate experiment. coupling_map: Directed coupling map (perhaps custom) to target in mapping. If the coupling map is symmetric, both directions need to be specified. Multiple formats are supported: #. ``CouplingMap`` instance #. List, must be given as an adjacency matrix, where each entry specifies all directed two-qubit interactions supported by backend, e.g: ``[[0, 1], [0, 3], [1, 2], [1, 5], [2, 5], [4, 1], [5, 3]]`` backend_properties: properties returned by a backend, including information on gate errors, readout errors, qubit coherence times, etc. Find a backend that provides this information with: ``backend.properties()`` initial_layout: Initial position of virtual qubits on physical qubits. If this layout makes the circuit compatible with the coupling_map constraints, it will be used. The final layout is not guaranteed to be the same, as the transpiler may permute qubits through swaps or other means. Multiple formats are supported: #. ``Layout`` instance #. Dict * virtual to physical:: {qr[0]: 0, qr[1]: 3, qr[2]: 5} * physical to virtual:: {0: qr[0], 3: qr[1], 5: qr[2]} #. List * virtual to physical:: [0, 3, 5] # virtual qubits are ordered (in addition to named) * physical to virtual:: [qr[0], None, None, qr[1], None, qr[2]] layout_method: Name of layout selection pass ('trivial', 'dense', 'sabre'). This can also be the external plugin name to use for the ``layout`` stage. You can see a list of installed plugins by using :func:`~.list_stage_plugins` with ``"layout"`` for the ``stage_name`` argument. routing_method: Name of routing pass ('basic', 'lookahead', 'stochastic', 'sabre', 'none'). Note This can also be the external plugin name to use for the ``routing`` stage. You can see a list of installed plugins by using :func:`~.list_stage_plugins` with ``"routing"`` for the ``stage_name`` argument. translation_method: Name of translation pass ('unroller', 'translator', 'synthesis') This can also be the external plugin name to use for the ``translation`` stage. You can see a list of installed plugins by using :func:`~.list_stage_plugins` with ``"translation"`` for the ``stage_name`` argument. scheduling_method: Name of scheduling pass. * ``'as_soon_as_possible'``: Schedule instructions greedily, as early as possible on a qubit resource. (alias: ``'asap'``) * ``'as_late_as_possible'``: Schedule instructions late, i.e. keeping qubits in the ground state when possible. (alias: ``'alap'``) If ``None``, no scheduling will be done. This can also be the external plugin name to use for the ``scheduling`` stage. You can see a list of installed plugins by using :func:`~.list_stage_plugins` with ``"scheduling"`` for the ``stage_name`` argument. instruction_durations: Durations of instructions. Applicable only if scheduling_method is specified. The gate lengths defined in ``backend.properties`` are used as default. They are overwritten if this ``instruction_durations`` is specified. The format of ``instruction_durations`` must be as follows. The `instruction_durations` must be given as a list of tuples [(instruction_name, qubits, duration, unit), ...]. | [('cx', [0, 1], 12.3, 'ns'), ('u3', [0], 4.56, 'ns')] | [('cx', [0, 1], 1000), ('u3', [0], 300)] If unit is omitted, the default is 'dt', which is a sample time depending on backend. If the time unit is 'dt', the duration must be an integer. dt: Backend sample time (resolution) in seconds. If ``None`` (default), ``backend.configuration().dt`` is used. approximation_degree (float): heuristic dial used for circuit approximation (1.0=no approximation, 0.0=maximal approximation) timing_constraints: An optional control hardware restriction on instruction time resolution. A quantum computer backend may report a set of restrictions, namely: - granularity: An integer value representing minimum pulse gate resolution in units of ``dt``. A user-defined pulse gate should have duration of a multiple of this granularity value. - min_length: An integer value representing minimum pulse gate length in units of ``dt``. A user-defined pulse gate should be longer than this length. - pulse_alignment: An integer value representing a time resolution of gate instruction starting time. Gate instruction should start at time which is a multiple of the alignment value. - acquire_alignment: An integer value representing a time resolution of measure instruction starting time. Measure instruction should start at time which is a multiple of the alignment value. This information will be provided by the backend configuration. If the backend doesn't have any restriction on the instruction time allocation, then ``timing_constraints`` is None and no adjustment will be performed. seed_transpiler: Sets random seed for the stochastic parts of the transpiler optimization_level: How much optimization to perform on the circuits. Higher levels generate more optimized circuits, at the expense of longer transpilation time. * 0: no optimization * 1: light optimization * 2: heavy optimization * 3: even heavier optimization If ``None``, level 2 will be chosen as default. callback: A callback function that will be called after each pass execution. The function will be called with 5 keyword arguments, | ``pass_``: the pass being run. | ``dag``: the dag output of the pass. | ``time``: the time to execute the pass. | ``property_set``: the property set. | ``count``: the index for the pass execution. The exact arguments passed expose the internals of the pass manager, and are subject to change as the pass manager internals change. If you intend to reuse a callback function over multiple releases, be sure to check that the arguments being passed are the same. To use the callback feature, define a function that will take in kwargs dict and access the variables. For example:: def callback_func(**kwargs): pass_ = kwargs['pass_'] dag = kwargs['dag'] time = kwargs['time'] property_set = kwargs['property_set'] count = kwargs['count'] ... transpile(circ, callback=callback_func) output_name: A list with strings to identify the output circuits. The length of the list should be exactly the length of the ``circuits`` parameter. unitary_synthesis_method (str): The name of the unitary synthesis method to use. By default ``'default'`` is used. You can see a list of installed plugins with :func:`.unitary_synthesis_plugin_names`. unitary_synthesis_plugin_config: An optional configuration dictionary that will be passed directly to the unitary synthesis plugin. By default this setting will have no effect as the default unitary synthesis method does not take custom configuration. This should only be necessary when a unitary synthesis plugin is specified with the ``unitary_synthesis_method`` argument. As this is custom for each unitary synthesis plugin refer to the plugin documentation for how to use this option. target: A backend transpiler target. Normally this is specified as part of the ``backend`` argument, but if you have manually constructed a :class:`~qiskit.transpiler.Target` object you can specify it manually here. This will override the target from ``backend``. hls_config: An optional configuration class :class:`~qiskit.transpiler.passes.synthesis.HLSConfig` that will be passed directly to :class:`~qiskit.transpiler.passes.synthesis.HighLevelSynthesis` transformation pass. This configuration class allows to specify for various high-level objects the lists of synthesis algorithms and their parameters. init_method: The plugin name to use for the ``init`` stage. By default an external plugin is not used. You can see a list of installed plugins by using :func:`~.list_stage_plugins` with ``"init"`` for the stage name argument. optimization_method: The plugin name to use for the ``optimization`` stage. By default an external plugin is not used. You can see a list of installed plugins by using :func:`~.list_stage_plugins` with ``"optimization"`` for the ``stage_name`` argument. ignore_backend_supplied_default_methods: If set to ``True`` any default methods specified by a backend will be ignored. Some backends specify alternative default methods to support custom compilation target-specific passes/plugins which support backend-specific compilation techniques. If you'd prefer that these defaults were not used this option is used to disable those backend-specific defaults. num_processes: The maximum number of parallel processes to launch for this call to transpile if parallel execution is enabled. This argument overrides ``num_processes`` in the user configuration file, and the ``QISKIT_NUM_PROCS`` environment variable. If set to ``None`` the system default or local user configuration will be used. qubits_initially_zero: Indicates whether the input circuit is zero-initialized. Returns: The transpiled circuit(s). Raises: TranspilerError: in case of bad inputs to transpiler (like conflicting parameters) or errors in passes """ arg_circuits_list = isinstance(circuits, list) circuits = circuits if arg_circuits_list else [circuits] if not circuits: return [] # transpiling schedules is not supported yet. start_time = time() if all(isinstance(c, Schedule) for c in circuits): warnings.warn("Transpiling schedules is not supported yet.", UserWarning) end_time = time() _log_transpile_time(start_time, end_time) if arg_circuits_list: return circuits else: return circuits[0] if optimization_level is None: # Take optimization level from the configuration or 1 as default. config = user_config.get_config() optimization_level = config.get("transpile_optimization_level", 2) if backend is not None and getattr(backend, "version", 0) <= 1: warnings.warn( "The `transpile` function will stop supporting inputs of " f"type `BackendV1` ( {backend} ) in the `backend` parameter in a future " "release no earlier than 2.0. `BackendV1` is deprecated and implementations " "should move to `BackendV2`.", category=DeprecationWarning, stacklevel=2, ) with warnings.catch_warnings(): # This is a temporary conversion step to allow for a smoother transition # to a fully target-based transpiler pipeline while maintaining the behavior # of `transpile` with BackendV1 inputs. # TODO BackendV1 is deprecated and this path can be # removed once it gets removed: # https://github.com/Qiskit/qiskit/pull/12850 warnings.filterwarnings( "ignore", category=DeprecationWarning, message=r".+qiskit\.providers\.backend_compat\.BackendV2Converter.+", module="qiskit", ) backend = BackendV2Converter(backend) if ( scheduling_method is not None and backend is None and target is None and not instruction_durations ): warnings.warn( "When scheduling circuits without backend," " 'instruction_durations' should be usually provided.", UserWarning, ) if not ignore_backend_supplied_default_methods: if scheduling_method is None and hasattr(backend, "get_scheduling_stage_plugin"): scheduling_method = backend.get_scheduling_stage_plugin() if translation_method is None and hasattr(backend, "get_translation_stage_plugin"): translation_method = backend.get_translation_stage_plugin() output_name = _parse_output_name(output_name, circuits) coupling_map = _parse_coupling_map(coupling_map) _check_circuits_coupling_map(circuits, coupling_map, backend) # Edge cases require using the old model (loose constraints) instead of building a target, # but we don't populate the passmanager config with loose constraints unless it's one of # the known edge cases to control the execution path. pm = generate_preset_pass_manager( optimization_level, target=target, backend=backend, basis_gates=basis_gates, coupling_map=coupling_map, instruction_durations=instruction_durations, backend_properties=backend_properties, timing_constraints=timing_constraints, inst_map=inst_map, initial_layout=initial_layout, layout_method=layout_method, routing_method=routing_method, translation_method=translation_method, scheduling_method=scheduling_method, approximation_degree=approximation_degree, seed_transpiler=seed_transpiler, unitary_synthesis_method=unitary_synthesis_method, unitary_synthesis_plugin_config=unitary_synthesis_plugin_config, hls_config=hls_config, init_method=init_method, optimization_method=optimization_method, dt=dt, qubits_initially_zero=qubits_initially_zero, ) out_circuits = pm.run(circuits, callback=callback, num_processes=num_processes) for name, circ in zip(output_name, out_circuits): circ.name = name end_time = time() _log_transpile_time(start_time, end_time) if arg_circuits_list: return out_circuits else: return out_circuits[0] def _check_circuits_coupling_map(circuits, cmap, backend): # Check circuit width against number of qubits in coupling_map(s) max_qubits = None if cmap is not None: max_qubits = cmap.size() elif backend is not None: max_qubits = backend.num_qubits for circuit in circuits: # If coupling_map is not None or num_qubits == 1 num_qubits = len(circuit.qubits) if max_qubits is not None and (num_qubits > max_qubits): raise CircuitTooWideForTarget( f"Number of qubits ({num_qubits}) in {circuit.name} " f"is greater than maximum ({max_qubits}) in the coupling_map" ) def _log_transpile_time(start_time, end_time): log_msg = f"Total Transpile Time - {((end_time - start_time) * 1000):.5f} (ms)" logger.info(log_msg) def _parse_coupling_map(coupling_map): # coupling_map could be None, or a list of lists, e.g. [[0, 1], [2, 1]] if isinstance(coupling_map, list) and all( isinstance(i, list) and len(i) == 2 for i in coupling_map ): return CouplingMap(coupling_map) elif isinstance(coupling_map, list): raise TranspilerError( "Only a single input coupling map can be used with transpile() if you need to " "target different coupling maps for different circuits you must call transpile() " "multiple times" ) else: return coupling_map def _parse_output_name(output_name, circuits): # naming and returning circuits # output_name could be either a string or a list if output_name is not None: if isinstance(output_name, str): # single circuit if len(circuits) == 1: return [output_name] # multiple circuits else: raise TranspilerError( "Expected a list object of length equal " + "to that of the number of circuits " + "being transpiled" ) elif isinstance(output_name, list): if len(circuits) == len(output_name) and all( isinstance(name, str) for name in output_name ): return output_name else: raise TranspilerError( "The length of output_name list " "must be equal to the number of " "transpiled circuits and the output_name " "list should be strings." ) else: raise TranspilerError( "The parameter output_name should be a string or a" f"list of strings: {type(output_name)} was used." ) else: return [circuit.name for circuit in circuits]
qiskit/qiskit/compiler/transpiler.py/0
{ "file_path": "qiskit/qiskit/compiler/transpiler.py", "repo_id": "qiskit", "token_count": 9360 }
195
# 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. """_DAGDependencyV2 class for representing non-commutativity in a circuit. """ import math from collections import OrderedDict, defaultdict, namedtuple from typing import Dict, List, Generator, Any import numpy as np import rustworkx as rx from qiskit.circuit import ( QuantumRegister, ClassicalRegister, Qubit, Clbit, Gate, ParameterExpression, ) from qiskit.circuit.controlflow import condition_resources from qiskit.circuit.bit import Bit from qiskit.dagcircuit.dagnode import DAGOpNode from qiskit.dagcircuit.exceptions import DAGDependencyError from qiskit.circuit.commutation_checker import CommutationChecker BitLocations = namedtuple("BitLocations", ("index", "registers")) class _DAGDependencyV2: """Object to represent a quantum circuit as a Directed Acyclic Graph (DAG) via operation dependencies (i.e. lack of commutation). .. warning:: This is not part of the public API. The nodes in the graph are operations represented by quantum gates. The edges correspond to non-commutation between two operations (i.e. a dependency). A directed edge from node A to node B means that operation A does not commute with operation B. The object's methods allow circuits to be constructed. **Example:** Bell circuit with no measurement. .. parsed-literal:: β”Œβ”€β”€β”€β” qr_0: ─ H β”œβ”€β”€β– β”€β”€ β””β”€β”€β”€β”˜β”Œβ”€β”΄β”€β” qr_1: ────── X β”œ β””β”€β”€β”€β”˜ The dependency DAG for the above circuit is represented by two nodes. The first one corresponds to Hadamard gate, the second one to the CNOT gate as the gates do not commute there is an edge between the two nodes. **Reference:** [1] Iten, R., Moyard, R., Metger, T., Sutter, D. and Woerner, S., 2020. Exact and practical pattern matching for quantum circuit optimization. `arXiv:1909.05270 <https://arxiv.org/abs/1909.05270>`_ """ def __init__(self): """ Create an empty _DAGDependencyV2. """ # Circuit name self.name = None # Circuit metadata self.metadata = {} # Cache of dag op node sort keys self._key_cache = {} # Directed multigraph whose nodes are operations(gates) and edges # represent non-commutativity between two gates. self._multi_graph = rx.PyDAG() # Map of qreg/creg name to Register object. self.qregs = OrderedDict() self.cregs = OrderedDict() # List of Qubit/Clbit wires that the DAG acts on. self.qubits: List[Qubit] = [] self.clbits: List[Clbit] = [] # Dictionary mapping of Qubit and Clbit instances to a tuple comprised of # 0) corresponding index in dag.{qubits,clbits} and # 1) a list of Register-int pairs for each Register containing the Bit and # its index within that register. self._qubit_indices: Dict[Qubit, BitLocations] = {} self._clbit_indices: Dict[Clbit, BitLocations] = {} self._global_phase = 0 self._calibrations = defaultdict(dict) # Map of number of each kind of op, keyed on op name self._op_names = {} self.duration = None self.unit = "dt" self.comm_checker = CommutationChecker() @property def global_phase(self): """Return the global phase of the circuit.""" return self._global_phase @global_phase.setter def global_phase(self, angle): """Set the global phase of the circuit. Args: angle (float, ParameterExpression) """ if isinstance(angle, ParameterExpression): self._global_phase = angle else: # Set the phase to the [0, 2Ο€) interval angle = float(angle) if not angle: self._global_phase = 0 else: self._global_phase = angle % (2 * math.pi) @property def calibrations(self): """Return calibration dictionary. The custom pulse definition of a given gate is of the form ``{'gate_name': {(qubits, params): schedule}}``. """ return dict(self._calibrations) @calibrations.setter def calibrations(self, calibrations): """Set the circuit calibration data from a dictionary of calibration definition. Args: calibrations (dict): A dictionary of input in the format {'gate_name': {(qubits, gate_params): schedule}} """ self._calibrations = defaultdict(dict, calibrations) def add_calibration(self, gate, qubits, schedule, params=None): """Register a low-level, custom pulse definition for the given gate. Args: gate (Union[Gate, str]): Gate information. qubits (Union[int, Tuple[int]]): List of qubits to be measured. schedule (Schedule): Schedule information. params (Optional[List[Union[float, Parameter]]]): A list of parameters. Raises: Exception: if the gate is of type string and params is None. """ def _format(operand): try: # Using float/complex value as a dict key is not good idea. # This makes the mapping quite sensitive to the rounding error. # However, the mechanism is already tied to the execution model (i.e. pulse gate) # and we cannot easily update this rule. # The same logic exists in QuantumCircuit.add_calibration. evaluated = complex(operand) if np.isreal(evaluated): evaluated = float(evaluated.real) if evaluated.is_integer(): evaluated = int(evaluated) return evaluated except TypeError: # Unassigned parameter return operand if isinstance(gate, Gate): params = gate.params gate = gate.name if params is not None: params = tuple(map(_format, params)) else: params = () self._calibrations[gate][(tuple(qubits), params)] = schedule def has_calibration_for(self, node): """Return True if the dag has a calibration defined for the node operation. In this case, the operation does not need to be translated to the device basis. """ if not self.calibrations or node.op.name not in self.calibrations: return False qubits = tuple(self.qubits.index(qubit) for qubit in node.qargs) params = [] for p in node.op.params: if isinstance(p, ParameterExpression) and not p.parameters: params.append(float(p)) else: params.append(p) params = tuple(params) return (qubits, params) in self.calibrations[node.op.name] def size(self): """Returns the number of gates in the circuit""" return len(self._multi_graph) def depth(self): """Return the circuit depth. Returns: int: the circuit depth """ depth = rx.dag_longest_path_length(self._multi_graph) return depth if depth >= 0 else 0 def width(self): """Return the total number of qubits + clbits used by the circuit.""" return len(self.qubits) + len(self.clbits) def num_qubits(self): """Return the total number of qubits used by the circuit.""" return len(self.qubits) def num_clbits(self): """Return the total number of classical bits used by the circuit.""" return len(self.clbits) def add_qubits(self, qubits): """Add individual qubit wires.""" if any(not isinstance(qubit, Qubit) for qubit in qubits): raise DAGDependencyError("not a Qubit instance.") duplicate_qubits = set(self.qubits).intersection(qubits) if duplicate_qubits: raise DAGDependencyError(f"duplicate qubits {duplicate_qubits}") for qubit in qubits: self.qubits.append(qubit) self._qubit_indices[qubit] = BitLocations(len(self.qubits) - 1, []) def add_clbits(self, clbits): """Add individual clbit wires.""" if any(not isinstance(clbit, Clbit) for clbit in clbits): raise DAGDependencyError("not a Clbit instance.") duplicate_clbits = set(self.clbits).intersection(clbits) if duplicate_clbits: raise DAGDependencyError(f"duplicate clbits {duplicate_clbits}") for clbit in clbits: self.clbits.append(clbit) self._clbit_indices[clbit] = BitLocations(len(self.clbits) - 1, []) def add_qreg(self, qreg): """Add qubits in a quantum register.""" if not isinstance(qreg, QuantumRegister): raise DAGDependencyError("not a QuantumRegister instance.") if qreg.name in self.qregs: raise DAGDependencyError(f"duplicate register {qreg.name}") self.qregs[qreg.name] = qreg existing_qubits = set(self.qubits) for j in range(qreg.size): if qreg[j] in self._qubit_indices: self._qubit_indices[qreg[j]].registers.append((qreg, j)) if qreg[j] not in existing_qubits: self.qubits.append(qreg[j]) self._qubit_indices[qreg[j]] = BitLocations( len(self.qubits) - 1, registers=[(qreg, j)] ) def add_creg(self, creg): """Add clbits in a classical register.""" if not isinstance(creg, ClassicalRegister): raise DAGDependencyError("not a ClassicalRegister instance.") if creg.name in self.cregs: raise DAGDependencyError(f"duplicate register {creg.name}") self.cregs[creg.name] = creg existing_clbits = set(self.clbits) for j in range(creg.size): if creg[j] in self._clbit_indices: self._clbit_indices[creg[j]].registers.append((creg, j)) if creg[j] not in existing_clbits: self.clbits.append(creg[j]) self._clbit_indices[creg[j]] = BitLocations( len(self.clbits) - 1, registers=[(creg, j)] ) def find_bit(self, bit: Bit) -> BitLocations: """ Finds locations in the _DAGDependencyV2, by mapping the Qubit and Clbit to positional index BitLocations is defined as: BitLocations = namedtuple("BitLocations", ("index", "registers")) Args: bit (Bit): The bit to locate. Returns: namedtuple(int, List[Tuple(Register, int)]): A 2-tuple. The first element (``index``) contains the index at which the ``Bit`` can be found (in either :obj:`~_DAGDependencyV2.qubits`, :obj:`~_DAGDependencyV2.clbits`, depending on its type). The second element (``registers``) is a list of ``(register, index)`` pairs with an entry for each :obj:`~Register` in the circuit which contains the :obj:`~Bit` (and the index in the :obj:`~Register` at which it can be found). Raises: DAGDependencyError: If the supplied :obj:`~Bit` was of an unknown type. DAGDependencyError: If the supplied :obj:`~Bit` could not be found on the circuit. """ try: if isinstance(bit, Qubit): return self._qubit_indices[bit] elif isinstance(bit, Clbit): return self._clbit_indices[bit] else: raise DAGDependencyError(f"Could not locate bit of unknown type: {type(bit)}") except KeyError as err: raise DAGDependencyError( f"Could not locate provided bit: {bit}. Has it been added to the DAGDependency?" ) from err def apply_operation_back(self, operation, qargs=(), cargs=()): """Add a DAGOpNode to the graph and update the edges. Args: operation (qiskit.circuit.Operation): operation as a quantum gate qargs (list[~qiskit.circuit.Qubit]): list of qubits on which the operation acts cargs (list[Clbit]): list of classical wires to attach to """ new_node = DAGOpNode( op=operation, qargs=qargs, cargs=cargs, dag=self, ) new_node._node_id = self._multi_graph.add_node(new_node) self._update_edges() self._increment_op(new_node.op) def _update_edges(self): """ Updates DagDependencyV2 by adding edges to the newly added node (max_node) from the previously added nodes. For each previously added node (prev_node), an edge from prev_node to max_node is added if max_node is "reachable" from prev_node (this means that the two nodes can be made adjacent by commuting them with other nodes), but the two nodes themselves do not commute. Currently. this function is only used when creating a new _DAGDependencyV2 from another representation of a circuit, and hence there are no removed nodes (this is why iterating over all nodes is fine). """ max_node_id = len(self._multi_graph) - 1 max_node = self._get_node(max_node_id) reachable = [True] * max_node_id # Analyze nodes in the reverse topological order. # An improvement to the original algorithm is to consider only direct predecessors # and to avoid constructing the lists of forward and backward reachable predecessors # for every node when not required. for prev_node_id in range(max_node_id - 1, -1, -1): if reachable[prev_node_id]: prev_node = self._get_node(prev_node_id) if not self.comm_checker.commute( prev_node.op, prev_node.qargs, prev_node.cargs, max_node.op, max_node.qargs, max_node.cargs, ): # If prev_node and max_node do not commute, then we add an edge # between the two, and mark all direct predecessors of prev_node # as not reaching max_node. self._multi_graph.add_edge(prev_node_id, max_node_id, {"commute": False}) predecessor_ids = sorted( [node._node_id for node in self.predecessors(self._get_node(prev_node_id))] ) for predecessor_id in predecessor_ids: reachable[predecessor_id] = False else: # If prev_node cannot reach max_node, then none of its predecessors can # reach max_node either. predecessor_ids = sorted( [node._node_id for node in self.predecessors(self._get_node(prev_node_id))] ) for predecessor_id in predecessor_ids: reachable[predecessor_id] = False def _get_node(self, node_id): """ Args: node_id (int): label of considered node. Returns: node: corresponding to the label. """ return self._multi_graph.get_node_data(node_id) def named_nodes(self, *names): """Get the set of "op" nodes with the given name.""" named_nodes = [] for node in self._multi_graph.nodes(): if node.op.name in names: named_nodes.append(node) return named_nodes def _increment_op(self, op): if op.name in self._op_names: self._op_names[op.name] += 1 else: self._op_names[op.name] = 1 def _decrement_op(self, op): if self._op_names[op.name] == 1: del self._op_names[op.name] else: self._op_names[op.name] -= 1 def count_ops(self): """Count the occurrences of operation names.""" return self._op_names def op_nodes(self): """ Returns: generator(dict): iterator over all the nodes. """ return iter(self._multi_graph.nodes()) def topological_nodes(self, key=None) -> Generator[DAGOpNode, Any, Any]: """ Yield nodes in topological order. Args: key (Callable): A callable which will take a DAGNode object and return a string sort key. If not specified the :attr:`~qiskit.dagcircuit.DAGNode.sort_key` attribute will be used as the sort key for each node. Returns: generator(DAGOpNode): node in topological order """ def _key(x): return x.sort_key if key is None: key = _key return iter(rx.lexicographical_topological_sort(self._multi_graph, key=key)) def topological_op_nodes(self, key=None) -> Generator[DAGOpNode, Any, Any]: """ Yield nodes in topological order. This is a wrapper for topological_nodes since all nodes are op nodes. It's here so that calls to dag.topological_op_nodes can use either DAGCircuit or _DAGDependencyV2. Returns: generator(DAGOpNode): nodes in topological order. """ return self.topological_nodes(key) def successors(self, node): """Returns iterator of the successors of a node as DAGOpNodes.""" return iter(self._multi_graph.successors(node._node_id)) def predecessors(self, node): """Returns iterator of the predecessors of a node as DAGOpNodes.""" return iter(self._multi_graph.predecessors(node._node_id)) def is_successor(self, node, node_succ): """Checks if a second node is in the successors of node.""" return self._multi_graph.has_edge(node._node_id, node_succ._node_id) def is_predecessor(self, node, node_pred): """Checks if a second node is in the predecessors of node.""" return self._multi_graph.has_edge(node_pred._node_id, node._node_id) def ancestors(self, node): """Returns set of the ancestors of a node as DAGOpNodes.""" return {self._multi_graph[x] for x in rx.ancestors(self._multi_graph, node._node_id)} def descendants(self, node): """Returns set of the descendants of a node as DAGOpNodes.""" return {self._multi_graph[x] for x in rx.descendants(self._multi_graph, node._node_id)} def bfs_successors(self, node): """ Returns an iterator of tuples of (DAGOpNode, [DAGOpNodes]) where the DAGOpNode is the current node and [DAGOpNode] is its successors in BFS order. """ return iter(rx.bfs_successors(self._multi_graph, node._node_id)) def copy_empty_like(self): """Return a copy of self with the same structure but empty. That structure includes: * name and other metadata * global phase * duration * all the qubits and clbits, including the registers. Returns: _DAGDependencyV2: An empty copy of self. """ target_dag = _DAGDependencyV2() target_dag.name = self.name target_dag._global_phase = self._global_phase target_dag.duration = self.duration target_dag.unit = self.unit target_dag.metadata = self.metadata target_dag._key_cache = self._key_cache target_dag.comm_checker = self.comm_checker target_dag.add_qubits(self.qubits) target_dag.add_clbits(self.clbits) for qreg in self.qregs.values(): target_dag.add_qreg(qreg) for creg in self.cregs.values(): target_dag.add_creg(creg) return target_dag def draw(self, scale=0.7, filename=None, style="color"): """ Draws the _DAGDependencyV2 graph. This function needs `pydot <https://github.com/erocarrera/pydot>`, which in turn needs Graphviz <https://www.graphviz.org/>` to be installed. Args: scale (float): scaling factor filename (str): file path to save image to (format inferred from name) style (str): 'plain': B&W graph 'color' (default): color input/output/op nodes Returns: Ipython.display.Image: if in Jupyter notebook and not saving to file, otherwise None. """ from qiskit.visualization.dag_visualization import dag_drawer return dag_drawer(dag=self, scale=scale, filename=filename, style=style) def replace_block_with_op(self, node_block, op, wire_pos_map, cycle_check=True): """Replace a block of nodes with a single node. This is used to consolidate a block of DAGOpNodes into a single operation. A typical example is a block of CX and SWAP gates consolidated into a LinearFunction. This function is an adaptation of a similar function from DAGCircuit. It is important that such consolidation preserves commutativity assumptions present in _DAGDependencyV2. As an example, suppose that every node in a block [A, B, C, D] commutes with another node E. Let F be the consolidated node, F = A o B o C o D. Then F also commutes with E, and thus the result of replacing [A, B, C, D] by F results in a valid _DAGDependencyV2. That is, any deduction about commutativity in consolidated _DAGDependencyV2 is correct. On the other hand, suppose that at least one of the nodes, say B, does not commute with E. Then the consolidated _DAGDependencyV2 would imply that F does not commute with E. Even though F and E may actually commute, it is still safe to assume that they do not. That is, the current implementation of consolidation may lead to suboptimal but not to incorrect results. Args: node_block (List[DAGOpNode]): A list of dag nodes that represents the node block to be replaced op (qiskit.circuit.Operation): The operation to replace the block with wire_pos_map (Dict[~qiskit.circuit.Qubit, int]): The dictionary mapping the qarg to the position. This is necessary to reconstruct the qarg order over multiple gates in the combined single op node. cycle_check (bool): When set to True this method will check that replacing the provided ``node_block`` with a single node would introduce a cycle (which would invalidate the ``_DAGDependencyV2``) and will raise a ``DAGDependencyError`` if a cycle would be introduced. This checking comes with a run time penalty. If you can guarantee that your input ``node_block`` is a contiguous block and won't introduce a cycle when it's contracted to a single node, this can be set to ``False`` to improve the runtime performance of this method. Raises: DAGDependencyError: if ``cycle_check`` is set to ``True`` and replacing the specified block introduces a cycle or if ``node_block`` is empty. """ block_qargs = set() block_cargs = set() block_ids = [x._node_id for x in node_block] # If node block is empty return early if not node_block: raise DAGDependencyError("Can't replace an empty node_block") for nd in node_block: block_qargs |= set(nd.qargs) block_cargs |= set(nd.cargs) cond = getattr(nd.op, "condition", None) if cond is not None: block_cargs.update(condition_resources(cond).clbits) # Create replacement node new_node = DAGOpNode( op, qargs=sorted(block_qargs, key=lambda x: wire_pos_map[x]), cargs=sorted(block_cargs, key=lambda x: wire_pos_map[x]), dag=self, ) try: new_node._node_id = self._multi_graph.contract_nodes( block_ids, new_node, check_cycle=cycle_check ) except rx.DAGWouldCycle as ex: raise DAGDependencyError( "Replacing the specified node block would introduce a cycle" ) from ex self._increment_op(op) for nd in node_block: self._decrement_op(nd.op) return new_node
qiskit/qiskit/dagcircuit/dagdependency_v2.py/0
{ "file_path": "qiskit/qiskit/dagcircuit/dagdependency_v2.py", "repo_id": "qiskit", "token_count": 10909 }
196
# This code is part of Qiskit. # # (C) Copyright IBM 2024. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """PrimitiveResult""" from __future__ import annotations from collections.abc import Iterable from typing import Any, Generic, TypeVar from .pub_result import PubResult T = TypeVar("T", bound=PubResult) class PrimitiveResult(Generic[T]): """A container for multiple pub results and global metadata.""" def __init__(self, pub_results: Iterable[T], metadata: dict[str, Any] | None = None): """ Args: pub_results: Pub results. metadata: Metadata that is common to all pub results; metadata specific to particular pubs should be placed in their metadata fields. Keys are expected to be strings. """ self._pub_results = list(pub_results) self._metadata = metadata or {} @property def metadata(self) -> dict[str, Any]: """The metadata of this primitive result.""" return self._metadata def __getitem__(self, index) -> T: return self._pub_results[index] def __len__(self) -> int: return len(self._pub_results) def __repr__(self) -> str: return f"PrimitiveResult({self._pub_results}, metadata={self.metadata})" def __iter__(self) -> Iterable[T]: return iter(self._pub_results)
qiskit/qiskit/primitives/containers/primitive_result.py/0
{ "file_path": "qiskit/qiskit/primitives/containers/primitive_result.py", "repo_id": "qiskit", "token_count": 583 }
197
# 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. """This module implements the job class used by Basic Aer Provider.""" import warnings from qiskit.providers import JobStatus from qiskit.providers.job import JobV1 class BasicProviderJob(JobV1): """BasicProviderJob class.""" _async = False def __init__(self, backend, job_id, result): super().__init__(backend, job_id) self._result = result def submit(self): """Submit the job to the backend for execution. Raises: JobError: if trying to re-submit the job. """ return def result(self, timeout=None): """Get job result . Returns: qiskit.result.Result: Result object """ if timeout is not None: warnings.warn( "The timeout kwarg doesn't have any meaning with " "BasicProvider because execution is synchronous and the " "result already exists when run() returns.", UserWarning, ) return self._result def status(self): """Gets the status of the job by querying the Python's future Returns: qiskit.providers.JobStatus: The current JobStatus """ return JobStatus.DONE def backend(self): """Return the instance of the backend used for this job.""" return self._backend
qiskit/qiskit/providers/basic_provider/basic_provider_job.py/0
{ "file_path": "qiskit/qiskit/providers/basic_provider/basic_provider_job.py", "repo_id": "qiskit", "token_count": 697 }
198
# 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. """ Fake backend supporting OpenPulse. """ import datetime import warnings from qiskit.providers.models.backendconfiguration import ( GateConfig, PulseBackendConfiguration, UchannelLO, ) from qiskit.providers.models.backendproperties import Nduv, Gate, BackendProperties from qiskit.providers.models.pulsedefaults import PulseDefaults, Command from qiskit.qobj import PulseQobjInstruction from .fake_backend import FakeBackend class FakeOpenPulse2Q(FakeBackend): """A fake 2 qubit backend for pulse test.""" def __init__(self): configuration = PulseBackendConfiguration( backend_name="fake_openpulse_2q", backend_version="0.0.0", n_qubits=2, meas_levels=[0, 1, 2], basis_gates=["u1", "u2", "u3", "cx", "id"], simulator=False, local=True, conditional=True, open_pulse=True, memory=False, max_shots=65536, gates=[GateConfig(name="TODO", parameters=[], qasm_def="TODO")], coupling_map=[[0, 1]], n_registers=2, n_uchannels=2, u_channel_lo=[ [UchannelLO(q=0, scale=1.0 + 0.0j)], [UchannelLO(q=0, scale=-1.0 + 0.0j), UchannelLO(q=1, scale=1.0 + 0.0j)], ], qubit_lo_range=[[4.5, 5.5], [4.5, 5.5]], meas_lo_range=[[6.0, 7.0], [6.0, 7.0]], dt=1.3333, dtm=10.5, rep_times=[100, 250, 500, 1000], meas_map=[[0, 1]], channel_bandwidth=[ [-0.2, 0.4], [-0.3, 0.3], [-0.3, 0.3], [-0.02, 0.02], [-0.02, 0.02], [-0.02, 0.02], ], meas_kernels=["kernel1"], discriminators=["max_1Q_fidelity"], acquisition_latency=[[100, 100], [100, 100]], conditional_latency=[ [100, 1000], [1000, 100], [100, 1000], [1000, 100], [100, 1000], [1000, 100], ], hamiltonian={ "h_str": [ "np.pi*(2*v0-alpha0)*O0", "np.pi*alpha0*O0*O0", "2*np.pi*r*X0||D0", "2*np.pi*r*X0||U1", "2*np.pi*r*X1||U0", "np.pi*(2*v1-alpha1)*O1", "np.pi*alpha1*O1*O1", "2*np.pi*r*X1||D1", "2*np.pi*j*(Sp0*Sm1+Sm0*Sp1)", ], "description": "A hamiltonian for a mocked 2Q device, with 1Q and 2Q terms.", "qub": {"0": 3, "1": 3}, "vars": { "v0": 5.00, "v1": 5.1, "j": 0.01, "r": 0.02, "alpha0": -0.33, "alpha1": -0.33, }, }, channels={ "acquire0": {"operates": {"qubits": [0]}, "purpose": "acquire", "type": "acquire"}, "acquire1": {"operates": {"qubits": [1]}, "purpose": "acquire", "type": "acquire"}, "d0": {"operates": {"qubits": [0]}, "purpose": "drive", "type": "drive"}, "d1": {"operates": {"qubits": [1]}, "purpose": "drive", "type": "drive"}, "m0": {"type": "measure", "purpose": "measure", "operates": {"qubits": [0]}}, "m1": {"type": "measure", "purpose": "measure", "operates": {"qubits": [1]}}, "u0": { "operates": {"qubits": [0, 1]}, "purpose": "cross-resonance", "type": "control", }, "u1": { "operates": {"qubits": [1, 0]}, "purpose": "cross-resonance", "type": "control", }, }, processor_type={ "family": "Canary", "revision": "1.0", "segment": "A", }, description="A fake test backend with pulse defaults", ) with warnings.catch_warnings(): # The class PulseQobjInstruction is deprecated warnings.filterwarnings("ignore", category=DeprecationWarning, module="qiskit") self._defaults = PulseDefaults.from_dict( { "qubit_freq_est": [4.9, 5.0], "meas_freq_est": [6.5, 6.6], "buffer": 10, "pulse_library": [ {"name": "x90p_d0", "samples": 2 * [0.1 + 0j]}, {"name": "x90p_d1", "samples": 2 * [0.1 + 0j]}, {"name": "x90m_d0", "samples": 2 * [-0.1 + 0j]}, {"name": "x90m_d1", "samples": 2 * [-0.1 + 0j]}, {"name": "y90p_d0", "samples": 2 * [0.1j]}, {"name": "y90p_d1", "samples": 2 * [0.1j]}, {"name": "xp_d0", "samples": 2 * [0.2 + 0j]}, {"name": "ym_d0", "samples": 2 * [-0.2j]}, {"name": "cr90p_u0", "samples": 9 * [0.1 + 0j]}, {"name": "cr90m_u0", "samples": 9 * [-0.1 + 0j]}, {"name": "measure_m0", "samples": 10 * [0.1 + 0j]}, {"name": "measure_m1", "samples": 10 * [0.1 + 0j]}, ], "cmd_def": [ Command.from_dict( { "name": "u1", "qubits": [0], "sequence": [ PulseQobjInstruction( name="fc", ch="d0", t0=0, phase="-P0" ).to_dict() ], } ).to_dict(), Command.from_dict( { "name": "u1", "qubits": [1], "sequence": [ PulseQobjInstruction( name="fc", ch="d1", t0=0, phase="-P0" ).to_dict() ], } ).to_dict(), Command.from_dict( { "name": "u2", "qubits": [0], "sequence": [ PulseQobjInstruction( name="fc", ch="d0", t0=0, phase="-P1" ).to_dict(), PulseQobjInstruction(name="y90p_d0", ch="d0", t0=0).to_dict(), PulseQobjInstruction( name="fc", ch="d0", t0=2, phase="-P0" ).to_dict(), ], } ).to_dict(), Command.from_dict( { "name": "u2", "qubits": [1], "sequence": [ PulseQobjInstruction( name="fc", ch="d1", t0=0, phase="-P1" ).to_dict(), PulseQobjInstruction(name="y90p_d1", ch="d1", t0=0).to_dict(), PulseQobjInstruction( name="fc", ch="d1", t0=2, phase="-P0" ).to_dict(), ], } ).to_dict(), Command.from_dict( { "name": "u3", "qubits": [0], "sequence": [ PulseQobjInstruction( name="fc", ch="d0", t0=0, phase="-P2" ).to_dict(), PulseQobjInstruction(name="x90p_d0", ch="d0", t0=0).to_dict(), PulseQobjInstruction( name="fc", ch="d0", t0=2, phase="-P0" ).to_dict(), PulseQobjInstruction(name="x90m_d0", ch="d0", t0=2).to_dict(), PulseQobjInstruction( name="fc", ch="d0", t0=4, phase="-P1" ).to_dict(), ], } ).to_dict(), Command.from_dict( { "name": "u3", "qubits": [1], "sequence": [ PulseQobjInstruction( name="fc", ch="d1", t0=0, phase="-P2" ).to_dict(), PulseQobjInstruction(name="x90p_d1", ch="d1", t0=0).to_dict(), PulseQobjInstruction( name="fc", ch="d1", t0=2, phase="-P0" ).to_dict(), PulseQobjInstruction(name="x90m_d1", ch="d1", t0=2).to_dict(), PulseQobjInstruction( name="fc", ch="d1", t0=4, phase="-P1" ).to_dict(), ], } ).to_dict(), Command.from_dict( { "name": "cx", "qubits": [0, 1], "sequence": [ PulseQobjInstruction( name="fc", ch="d0", t0=0, phase=1.57 ).to_dict(), PulseQobjInstruction(name="ym_d0", ch="d0", t0=0).to_dict(), PulseQobjInstruction(name="xp_d0", ch="d0", t0=11).to_dict(), PulseQobjInstruction(name="x90p_d1", ch="d1", t0=0).to_dict(), PulseQobjInstruction(name="cr90p_u0", ch="u0", t0=2).to_dict(), PulseQobjInstruction(name="cr90m_u0", ch="u0", t0=13).to_dict(), ], } ).to_dict(), Command.from_dict( { "name": "measure", "qubits": [0, 1], "sequence": [ PulseQobjInstruction( name="measure_m0", ch="m0", t0=0 ).to_dict(), PulseQobjInstruction( name="measure_m1", ch="m1", t0=0 ).to_dict(), PulseQobjInstruction( name="acquire", duration=10, t0=0, qubits=[0, 1], memory_slot=[0, 1], ).to_dict(), ], } ).to_dict(), ], } ) mock_time = datetime.datetime.now() dt = 1.3333 self._properties = BackendProperties( backend_name="fake_openpulse_2q", backend_version="0.0.0", last_update_date=mock_time, qubits=[ [ Nduv(date=mock_time, name="T1", unit="Β΅s", value=71.9500421005539), Nduv(date=mock_time, name="T2", unit="Β΅s", value=69.4240447362455), Nduv(date=mock_time, name="frequency", unit="MHz", value=4919.96800692), Nduv(date=mock_time, name="readout_error", unit="", value=0.02), ], [ Nduv(date=mock_time, name="T1", unit="Β΅s", value=81.9500421005539), Nduv(date=mock_time, name="T2", unit="Β΅s", value=75.5598482446578), Nduv(date=mock_time, name="frequency", unit="GHz", value=5.01996800692), Nduv(date=mock_time, name="readout_error", unit="", value=0.02), ], ], gates=[ Gate( gate="id", qubits=[0], parameters=[ Nduv(date=mock_time, name="gate_error", unit="", value=0), Nduv(date=mock_time, name="gate_length", unit="ns", value=2 * dt), ], ), Gate( gate="id", qubits=[1], parameters=[ Nduv(date=mock_time, name="gate_error", unit="", value=0), Nduv(date=mock_time, name="gate_length", unit="ns", value=2 * dt), ], ), Gate( gate="u1", qubits=[0], parameters=[ Nduv(date=mock_time, name="gate_error", unit="", value=0.06), Nduv(date=mock_time, name="gate_length", unit="ns", value=0.0), ], ), Gate( gate="u1", qubits=[1], parameters=[ Nduv(date=mock_time, name="gate_error", unit="", value=0.06), Nduv(date=mock_time, name="gate_length", unit="ns", value=0.0), ], ), Gate( gate="u2", qubits=[0], parameters=[ Nduv(date=mock_time, name="gate_error", unit="", value=0.06), Nduv(date=mock_time, name="gate_length", unit="ns", value=2 * dt), ], ), Gate( gate="u2", qubits=[1], parameters=[ Nduv(date=mock_time, name="gate_error", unit="", value=0.06), Nduv(date=mock_time, name="gate_length", unit="ns", value=2 * dt), ], ), Gate( gate="u3", qubits=[0], parameters=[ Nduv(date=mock_time, name="gate_error", unit="", value=0.06), Nduv(date=mock_time, name="gate_length", unit="ns", value=4 * dt), ], ), Gate( gate="u3", qubits=[1], parameters=[ Nduv(date=mock_time, name="gate_error", unit="", value=0.06), Nduv(date=mock_time, name="gate_length", unit="ns", value=4 * dt), ], ), Gate( gate="cx", qubits=[0, 1], parameters=[ Nduv(date=mock_time, name="gate_error", unit="", value=1.0), Nduv(date=mock_time, name="gate_length", unit="ns", value=22 * dt), ], ), ], general=[], ) super().__init__(configuration) def defaults(self): """Return the default pulse-related settings provided by the backend (such as gate to Schedule mappings). """ return self._defaults def properties(self): """Return the measured characteristics of the backend.""" return self._properties
qiskit/qiskit/providers/fake_provider/fake_openpulse_2q.py/0
{ "file_path": "qiskit/qiskit/providers/fake_provider/fake_openpulse_2q.py", "repo_id": "qiskit", "token_count": 11754 }
199
# 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. """Container class for backend options.""" import io from collections.abc import Mapping class Options(Mapping): """Base options object This class is what all backend options are based on. The properties of the class are intended to be all dynamically adjustable so that a user can reconfigure the backend on demand. If a property is immutable to the user (eg something like number of qubits) that should be a configuration of the backend class itself instead of the options. Instances of this class behave like dictionaries. Accessing an option with a default value can be done with the `get()` method: >>> options = Options(opt1=1, opt2=2) >>> options.get("opt1") 1 >>> options.get("opt3", default="hello") 'hello' Key-value pairs for all options can be retrieved using the `items()` method: >>> list(options.items()) [('opt1', 1), ('opt2', 2)] Options can be updated by name: >>> options["opt1"] = 3 >>> options.get("opt1") 3 Runtime validators can be registered. See `set_validator`. Updates through `update_options` and indexing (`__setitem__`) validate the new value before performing the update and raise `ValueError` if the new value is invalid. >>> options.set_validator("opt1", (1, 5)) >>> options["opt1"] = 4 >>> options["opt1"] 4 >>> options["opt1"] = 10 # doctest: +ELLIPSIS Traceback (most recent call last): ... ValueError: ... """ # Here there are dragons. # This class preamble is an abhorrent hack to make `Options` work similarly to a # SimpleNamespace, but with its instance methods and attributes in a separate namespace. This # is required to make the initial release of Qiskit Terra 0.19 compatible with already released # versions of Qiskit Experiments, which rely on both of # options.my_key = my_value # transpile(qc, **options.__dict__) # working. # # Making `__dict__` a property which gets a slotted attribute solves the second line. The # slotted attributes are not stored in a `__dict__` anyway, and `__slots__` classes suppress the # creation of `__dict__`. That leaves it free for us to override it with a property, which # returns the options namespace `_fields`. # # We need to make attribute setting simply set options as well, to support statements of the # form `options.key = value`. We also need to ensure that existing uses do not override any new # methods. We do this by overriding `__setattr__` to purely write into our `_fields` dict # instead. This has the highly unusual behavior that # >>> options = Options() # >>> options.validator = "my validator option setting" # >>> options.validator # {} # >>> options.get("validator") # "my validator option setting" # This is the most we can do to support the old interface; _getting_ attributes must return the # new forms where appropriate, but setting will work with anything. All options can always be # returned by `Options.get`. To initialise the attributes in `__init__`, we need to dodge the # overriding of `__setattr__`, and upcall to `object.__setattr__`. # # To support copying and pickling, we also have to define how to set our state, because Python's # normal way of trying to get attributes in the unpickle will fail. # # This is a terrible hack, and is purely to ensure that Terra 0.19 does not break versions of # other Qiskit-family packages that are already deployed. It should be removed as soon as # possible. __slots__ = ("_fields", "validator") # implementation of the Mapping ABC: def __getitem__(self, key): return self._fields[key] def __iter__(self): return iter(self._fields) def __len__(self): return len(self._fields) # Allow modifying the options (validated) def __setitem__(self, key, value): self.update_options(**{key: value}) # backwards-compatibility with Qiskit Experiments: @property def __dict__(self): return self._fields # SimpleNamespace-like access to options: def __getattr__(self, name): # This does not interrupt the normal lookup of things like methods or `_fields`, because # those are successfully resolved by the normal Python lookup apparatus. If we are here, # then lookup has failed, so we must be looking for an option. If the user has manually # called `self.__getattr__("_fields")` then they'll get the option not the full dict, but # that's not really our fault. `getattr(self, "_fields")` will still find the dict. try: return self._fields[name] except KeyError as ex: raise AttributeError(f"Option {name} is not defined") from ex # setting options with the namespace interface is not validated def __setattr__(self, key, value): self._fields[key] = value # custom pickling: def __getstate__(self): return (self._fields, self.validator) def __setstate__(self, state): _fields, validator = state super().__setattr__("_fields", _fields) super().__setattr__("validator", validator) def __copy__(self): """Return a copy of the Options. The returned option and validator values are shallow copies of the originals. """ out = self.__new__(type(self)) # pylint:disable=no-value-for-parameter out.__setstate__((self._fields.copy(), self.validator.copy())) return out def __init__(self, **kwargs): super().__setattr__("_fields", kwargs) super().__setattr__("validator", {}) # The eldritch horrors are over, and normal service resumes below. Beware that while # `__setattr__` is overridden, you cannot do `self.x = y` (but `self.x[key] = y` is fine). This # should not be necessary, but if _absolutely_ required, you must do # super().__setattr__("x", y) # to avoid just setting a value in `_fields`. def __repr__(self): items = (f"{k}={v!r}" for k, v in self._fields.items()) return f"{type(self).__name__}({', '.join(items)})" def __eq__(self, other): if isinstance(self, Options) and isinstance(other, Options): return self._fields == other._fields return NotImplemented def set_validator(self, field, validator_value): """Set an optional validator for a field in the options Setting a validator enables changes to an options values to be validated for correctness when :meth:`~qiskit.providers.Options.update_options` is called. For example if you have a numeric field like ``shots`` you can specify a bounds tuple that set an upper and lower bound on the value such as:: options.set_validator("shots", (1, 4096)) In this case whenever the ``"shots"`` option is updated by the user it will enforce that the value is >=1 and <=4096. A ``ValueError`` will be raised if it's outside those bounds. If a validator is already present for the specified field it will be silently overridden. Args: field (str): The field name to set the validator on validator_value (list or tuple or type): The value to use for the validator depending on the type indicates on how the value for a field is enforced. If a tuple is passed in it must have a length of two and will enforce the min and max value (inclusive) for an integer or float value option. If it's a list it will list the valid values for a field. If it's a ``type`` the validator will just enforce the value is of a certain type. Raises: KeyError: If field is not present in the options object ValueError: If the ``validator_value`` has an invalid value for a given type TypeError: If ``validator_value`` is not a valid type """ if field not in self._fields: raise KeyError(f"Field '{field}' is not present in this options object") if isinstance(validator_value, tuple): if len(validator_value) != 2: raise ValueError( "A tuple validator must be of the form '(lower, upper)' " "where lower and upper are the lower and upper bounds " "inclusive of the numeric value" ) elif isinstance(validator_value, list): if len(validator_value) == 0: raise ValueError("A list validator must have at least one entry") elif isinstance(validator_value, type): pass else: raise TypeError( f"{type(validator_value)} is not a valid validator type, it " "must be a tuple, list, or class/type" ) self.validator[field] = validator_value # pylint: disable=unsupported-assignment-operation def update_options(self, **fields): """Update options with kwargs""" for field_name, field in fields.items(): field_validator = self.validator.get(field_name, None) if isinstance(field_validator, tuple): if field > field_validator[1] or field < field_validator[0]: raise ValueError( f"Specified value for '{field_name}' is not a valid value, " f"must be >={field_validator[0]} or <={field_validator[1]}" ) elif isinstance(field_validator, list): if field not in field_validator: raise ValueError( f"Specified value for {field_name} is not a valid choice, " f"must be one of {field_validator}" ) elif isinstance(field_validator, type): if not isinstance(field, field_validator): raise TypeError( f"Specified value for {field_name} is not of required type {field_validator}" ) self._fields.update(fields) def __str__(self): no_validator = super().__str__() if not self.validator: return no_validator else: out_str = io.StringIO() out_str.write(no_validator) out_str.write("\nWhere:\n") for field, value in self.validator.items(): if isinstance(value, tuple): out_str.write(f"\t{field} is >= {value[0]} and <= {value[1]}\n") elif isinstance(value, list): out_str.write(f"\t{field} is one of {value}\n") elif isinstance(value, type): out_str.write(f"\t{field} is of type {value}\n") return out_str.getvalue()
qiskit/qiskit/providers/options.py/0
{ "file_path": "qiskit/qiskit/providers/options.py", "repo_id": "qiskit", "token_count": 4458 }
200
# 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. """ ``Instruction`` s are single operations within a :py:class:`~qiskit.pulse.Schedule`, and can be used the same way as :py:class:`~qiskit.pulse.Schedule` s. For example:: duration = 10 channel = DriveChannel(0) sched = Schedule() sched += Delay(duration, channel) # Delay is a specific subclass of Instruction """ from __future__ import annotations from abc import ABC, abstractmethod from collections.abc import Iterable from qiskit.circuit import Parameter, ParameterExpression from qiskit.pulse.channels import Channel from qiskit.pulse.exceptions import PulseError # pylint: disable=bad-docstring-quotes class Instruction(ABC): """The smallest schedulable unit: a single instruction. It has a fixed duration and specified channels. """ def __init__( self, operands: tuple, name: str | None = None, ): """Instruction initializer. Args: operands: The argument list. name: Optional display name for this instruction. """ self._operands = operands self._name = name self._validate() def _validate(self): """Called after initialization to validate instruction data. Raises: PulseError: If the input ``channels`` are not all of type :class:`Channel`. """ for channel in self.channels: if not isinstance(channel, Channel): raise PulseError(f"Expected a channel, got {channel} instead.") @property def name(self) -> str: """Name of this instruction.""" return self._name @property def id(self) -> int: # pylint: disable=invalid-name """Unique identifier for this instruction.""" return id(self) @property def operands(self) -> tuple: """Return instruction operands.""" return self._operands @property @abstractmethod def channels(self) -> tuple[Channel, ...]: """Returns the channels that this schedule uses.""" raise NotImplementedError @property def start_time(self) -> int: """Relative begin time of this instruction.""" return 0 @property def stop_time(self) -> int: """Relative end time of this instruction.""" return self.duration @property def duration(self) -> int | ParameterExpression: """Duration of this instruction.""" raise NotImplementedError @property def _children(self) -> tuple["Instruction", ...]: """Instruction has no child nodes.""" return () @property def instructions(self) -> tuple[tuple[int, "Instruction"], ...]: """Iterable for getting instructions from Schedule tree.""" return tuple(self._instructions()) def ch_duration(self, *channels: Channel) -> int: """Return duration of the supplied channels in this Instruction. Args: *channels: Supplied channels """ return self.ch_stop_time(*channels) def ch_start_time(self, *channels: Channel) -> int: # pylint: disable=unused-argument """Return minimum start time for supplied channels. Args: *channels: Supplied channels """ return 0 def ch_stop_time(self, *channels: Channel) -> int: """Return maximum start time for supplied channels. Args: *channels: Supplied channels """ if any(chan in self.channels for chan in channels): return self.duration return 0 def _instructions(self, time: int = 0) -> Iterable[tuple[int, "Instruction"]]: """Iterable for flattening Schedule tree. Args: time: Shifted time of this node due to parent Yields: Tuple[int, Union['Schedule, 'Instruction']]: Tuple of the form (start_time, instruction). """ yield (time, self) def shift(self, time: int, name: str | None = None): """Return a new schedule shifted forward by `time`. Args: time: Time to shift by name: Name of the new schedule. Defaults to name of self Returns: Schedule: The shifted schedule. """ from qiskit.pulse.schedule import Schedule if name is None: name = self.name return Schedule((time, self), name=name) def insert(self, start_time: int, schedule, name: str | None = None): """Return a new :class:`~qiskit.pulse.Schedule` with ``schedule`` inserted within ``self`` at ``start_time``. Args: start_time: Time to insert the schedule schedule schedule (Union['Schedule', 'Instruction']): Schedule or instruction to insert name: Name of the new schedule. Defaults to name of self Returns: Schedule: A new schedule with ``schedule`` inserted with this instruction at t=0. """ from qiskit.pulse.schedule import Schedule if name is None: name = self.name return Schedule(self, (start_time, schedule), name=name) def append(self, schedule, name: str | None = None): """Return a new :class:`~qiskit.pulse.Schedule` with ``schedule`` inserted at the maximum time over all channels shared between ``self`` and ``schedule``. Args: schedule (Union['Schedule', 'Instruction']): Schedule or instruction to be appended name: Name of the new schedule. Defaults to name of self Returns: Schedule: A new schedule with ``schedule`` a this instruction at t=0. """ common_channels = set(self.channels) & set(schedule.channels) time = self.ch_stop_time(*common_channels) return self.insert(time, schedule, name=name) @property def parameters(self) -> set: """Parameters which determine the instruction behavior.""" def _get_parameters_recursive(obj): params = set() if hasattr(obj, "parameters"): for param in obj.parameters: if isinstance(param, Parameter): params.add(param) else: params |= _get_parameters_recursive(param) return params parameters = set() for op in self.operands: parameters |= _get_parameters_recursive(op) return parameters def is_parameterized(self) -> bool: """Return True iff the instruction is parameterized.""" return any(self.parameters) def __eq__(self, other: object) -> bool: """Check if this Instruction is equal to the `other` instruction. Equality is determined by the instruction sharing the same operands and channels. """ if not isinstance(other, Instruction): return NotImplemented return isinstance(other, type(self)) and self.operands == other.operands def __hash__(self) -> int: return hash((type(self), self.operands, self.name)) def __add__(self, other): """Return a new schedule with `other` inserted within `self` at `start_time`. Args: other (Union['Schedule', 'Instruction']): Schedule or instruction to be appended Returns: Schedule: A new schedule with ``schedule`` appended after this instruction at t=0. """ return self.append(other) def __or__(self, other): """Return a new schedule which is the union of `self` and `other`. Args: other (Union['Schedule', 'Instruction']): Schedule or instruction to union with Returns: Schedule: A new schedule with ``schedule`` inserted with this instruction at t=0 """ return self.insert(0, other) def __lshift__(self, time: int): """Return a new schedule which is shifted forward by `time`. Returns: Schedule: The shifted schedule """ return self.shift(time) def __repr__(self) -> str: operands = ", ".join(str(op) for op in self.operands) name_repr = f", name='{self.name}'" if self.name else "" return f"{self.__class__.__name__}({operands}{name_repr})"
qiskit/qiskit/pulse/instructions/instruction.py/0
{ "file_path": "qiskit/qiskit/pulse/instructions/instruction.py", "repo_id": "qiskit", "token_count": 3451 }
201
# 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. """Management of schedule block references.""" from typing import Tuple from collections import UserDict from qiskit.pulse.exceptions import PulseError class ReferenceManager(UserDict): """Dictionary wrapper to manage pulse schedule references.""" def unassigned(self) -> Tuple[Tuple[str, ...], ...]: """Get the keys of unassigned references. Returns: Tuple of reference keys. """ keys = [] for key, value in self.items(): if value is None: keys.append(key) return tuple(keys) def __setitem__(self, key, value): if key in self and self[key] is not None: # Check subroutine conflict. if self[key] != value: raise PulseError( f"Subroutine {key} is already assigned to the reference of the current scope, " "however, the newly assigned schedule conflicts with the existing schedule. " "This operation was not successfully done." ) return super().__setitem__(key, value) def __repr__(self): keys = ", ".join(map(repr, self.keys())) return f"{self.__class__.__name__}(references=[{keys}])" def __str__(self): out = f"{self.__class__.__name__}:" for key, reference in self.items(): prog_repr = repr(reference) if len(prog_repr) > 50: prog_repr = prog_repr[:50] + "..." out += f"\n - {repr(key)}: {prog_repr}" return out
qiskit/qiskit/pulse/reference_manager.py/0
{ "file_path": "qiskit/qiskit/pulse/reference_manager.py", "repo_id": "qiskit", "token_count": 838 }
202
# This code is part of Qiskit. # # (C) Copyright IBM 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=invalid-name, super-init-not-called, missing-class-docstring, redefined-builtin """QASM3 AST Nodes""" import enum from typing import Optional, List, Union, Iterable, Tuple class ASTNode: """Base abstract class for AST nodes""" class Statement(ASTNode): """ statement : expressionStatement | assignmentStatement | classicalDeclarationStatement | branchingStatement | loopStatement | endStatement | aliasStatement | quantumStatement """ class Pragma(ASTNode): """ pragma : '#pragma' LBRACE statement* RBRACE // match any valid openqasm statement """ def __init__(self, content): self.content = content class CalibrationGrammarDeclaration(Statement): """ calibrationGrammarDeclaration : 'defcalgrammar' calibrationGrammar SEMICOLON """ def __init__(self, name): self.name = name class Program(ASTNode): """ program : header (globalStatement | statement)* """ def __init__(self, header, statements=None): self.header = header self.statements = statements or [] class Header(ASTNode): """ header : version? include* """ def __init__(self, version, includes): self.version = version self.includes = includes class Include(ASTNode): """ include : 'include' StringLiteral SEMICOLON """ def __init__(self, filename): self.filename = filename class Version(ASTNode): """ version : 'OPENQASM'(Integer | RealNumber) SEMICOLON """ def __init__(self, version_number): self.version_number = version_number class QuantumInstruction(ASTNode): """ quantumInstruction : quantumGateCall | quantumPhase | quantumMeasurement | quantumReset | quantumBarrier """ class ClassicalType(ASTNode): """Information about a classical type. This is just an abstract base for inheritance tests.""" class FloatType(ClassicalType, enum.Enum): """Allowed values for the width of floating-point types.""" HALF = 16 SINGLE = 32 DOUBLE = 64 QUAD = 128 OCT = 256 class BoolType(ClassicalType): """Type information for a Boolean.""" class IntType(ClassicalType): """Type information for a signed integer.""" def __init__(self, size: Optional[int] = None): self.size = size class UintType(ClassicalType): """Type information for an unsigned integer.""" def __init__(self, size: Optional[int] = None): self.size = size class BitType(ClassicalType): """Type information for a single bit.""" class BitArrayType(ClassicalType): """Type information for a sized number of classical bits.""" def __init__(self, size: int): self.size = size class Expression(ASTNode): pass class StringifyAndPray(Expression): # This is not a real AST node, yet is somehow very common. It's used when there are # `ParameterExpression` instances; instead of actually visiting the Sympy expression tree into # an OQ3 AST, we just convert it to a string, cross our fingers, and hope. def __init__(self, obj): self.obj = obj class Range(Expression): def __init__( self, start: Optional[Expression] = None, end: Optional[Expression] = None, step: Optional[Expression] = None, ): self.start = start self.step = step self.end = end class Identifier(Expression): def __init__(self, string): self.string = string class SubscriptedIdentifier(Identifier): """An identifier with subscripted access.""" def __init__(self, string: str, subscript: Union[Range, Expression]): super().__init__(string) self.subscript = subscript class Constant(Expression, enum.Enum): """A constant value defined by the QASM 3 spec.""" PI = enum.auto() EULER = enum.auto() TAU = enum.auto() class IntegerLiteral(Expression): def __init__(self, value): self.value = value class BooleanLiteral(Expression): def __init__(self, value): self.value = value class BitstringLiteral(Expression): def __init__(self, value, width): self.value = value self.width = width class DurationUnit(enum.Enum): """Valid values for the unit of durations.""" NANOSECOND = "ns" MICROSECOND = "us" MILLISECOND = "ms" SECOND = "s" SAMPLE = "dt" class DurationLiteral(Expression): def __init__(self, value: float, unit: DurationUnit): self.value = value self.unit = unit class Unary(Expression): class Op(enum.Enum): LOGIC_NOT = "!" BIT_NOT = "~" def __init__(self, op: Op, operand: Expression): self.op = op self.operand = operand class Binary(Expression): class Op(enum.Enum): BIT_AND = "&" BIT_OR = "|" BIT_XOR = "^" LOGIC_AND = "&&" LOGIC_OR = "||" LESS = "<" LESS_EQUAL = "<=" GREATER = ">" GREATER_EQUAL = ">=" EQUAL = "==" NOT_EQUAL = "!=" SHIFT_LEFT = "<<" SHIFT_RIGHT = ">>" def __init__(self, op: Op, left: Expression, right: Expression): self.op = op self.left = left self.right = right class Cast(Expression): def __init__(self, type: ClassicalType, operand: Expression): self.type = type self.operand = operand class Index(Expression): def __init__(self, target: Expression, index: Expression): self.target = target self.index = index class IndexSet(ASTNode): """ A literal index set of values:: { Expression (, Expression)* } """ def __init__(self, values: List[Expression]): self.values = values class QuantumMeasurement(ASTNode): """ quantumMeasurement : 'measure' indexIdentifierList """ def __init__(self, identifierList: List[Identifier]): self.identifierList = identifierList class QuantumMeasurementAssignment(Statement): """ quantumMeasurementAssignment : quantumMeasurement ARROW indexIdentifierList | indexIdentifier EQUALS quantumMeasurement # eg: bits = measure qubits; """ def __init__(self, identifier: Identifier, quantumMeasurement: QuantumMeasurement): self.identifier = identifier self.quantumMeasurement = quantumMeasurement class Designator(ASTNode): """ designator : LBRACKET expression RBRACKET """ def __init__(self, expression: Expression): self.expression = expression class ClassicalDeclaration(Statement): """Declaration of a classical type, optionally initializing it to a value.""" def __init__(self, type_: ClassicalType, identifier: Identifier, initializer=None): self.type = type_ self.identifier = identifier self.initializer = initializer class AssignmentStatement(Statement): """Assignment of an expression to an l-value.""" def __init__(self, lvalue: SubscriptedIdentifier, rvalue: Expression): self.lvalue = lvalue self.rvalue = rvalue class QuantumDeclaration(ASTNode): """ quantumDeclaration : 'qreg' Identifier designator? | # NOT SUPPORTED 'qubit' designator? Identifier """ def __init__(self, identifier: Identifier, designator=None): self.identifier = identifier self.designator = designator class AliasStatement(ASTNode): """ aliasStatement : 'let' Identifier EQUALS indexIdentifier SEMICOLON """ def __init__(self, identifier: Identifier, value: Expression): self.identifier = identifier self.value = value class QuantumGateModifierName(enum.Enum): """The names of the allowed modifiers of quantum gates.""" CTRL = enum.auto() NEGCTRL = enum.auto() INV = enum.auto() POW = enum.auto() class QuantumGateModifier(ASTNode): """A modifier of a gate. For example, in ``ctrl @ x $0``, the ``ctrl @`` is the modifier.""" def __init__(self, modifier: QuantumGateModifierName, argument: Optional[Expression] = None): self.modifier = modifier self.argument = argument class QuantumGateCall(QuantumInstruction): """ quantumGateCall : quantumGateModifier* quantumGateName ( LPAREN expressionList? RPAREN )? indexIdentifierList """ def __init__( self, quantumGateName: Identifier, indexIdentifierList: List[Identifier], parameters: List[Expression] = None, modifiers: Optional[List[QuantumGateModifier]] = None, ): self.quantumGateName = quantumGateName self.indexIdentifierList = indexIdentifierList self.parameters = parameters or [] self.modifiers = modifiers or [] class QuantumBarrier(QuantumInstruction): """ quantumBarrier : 'barrier' indexIdentifierList """ def __init__(self, indexIdentifierList: List[Identifier]): self.indexIdentifierList = indexIdentifierList class QuantumReset(QuantumInstruction): """A built-in ``reset q0;`` statement.""" def __init__(self, identifier: Identifier): self.identifier = identifier class QuantumDelay(QuantumInstruction): """A built-in ``delay[duration] q0;`` statement.""" def __init__(self, duration: Expression, qubits: List[Identifier]): self.duration = duration self.qubits = qubits class ProgramBlock(ASTNode): """ programBlock : statement | controlDirective | LBRACE(statement | controlDirective) * RBRACE """ def __init__(self, statements: List[Statement]): self.statements = statements class ReturnStatement(ASTNode): # TODO probably should be a subclass of ControlDirective """ returnStatement : 'return' ( expression | quantumMeasurement )? SEMICOLON; """ def __init__(self, expression=None): self.expression = expression class QuantumBlock(ProgramBlock): """ quantumBlock : LBRACE ( quantumStatement | quantumLoop )* RBRACE """ pass class SubroutineBlock(ProgramBlock): """ subroutineBlock : LBRACE statement* returnStatement? RBRACE """ pass class QuantumGateDefinition(Statement): """ quantumGateDefinition : 'gate' quantumGateSignature quantumBlock """ def __init__( self, name: Identifier, params: Tuple[Identifier, ...], qubits: Tuple[Identifier, ...], body: QuantumBlock, ): self.name = name self.params = params self.qubits = qubits self.body = body class SubroutineDefinition(Statement): """ subroutineDefinition : 'def' Identifier LPAREN anyTypeArgumentList? RPAREN returnSignature? subroutineBlock """ def __init__( self, identifier: Identifier, subroutineBlock: SubroutineBlock, arguments=None, # [ClassicalArgument] ): self.identifier = identifier self.arguments = arguments or [] self.subroutineBlock = subroutineBlock class CalibrationArgument(ASTNode): """ calibrationArgumentList : classicalArgumentList | expressionList """ pass class CalibrationDefinition(Statement): """ calibrationDefinition : 'defcal' Identifier ( LPAREN calibrationArgumentList? RPAREN )? identifierList returnSignature? LBRACE .*? RBRACE // for now, match anything inside body ; """ def __init__( self, name: Identifier, identifierList: List[Identifier], calibrationArgumentList: Optional[List[CalibrationArgument]] = None, ): self.name = name self.identifierList = identifierList self.calibrationArgumentList = calibrationArgumentList or [] class BranchingStatement(Statement): """ branchingStatement : 'if' LPAREN booleanExpression RPAREN programBlock ( 'else' programBlock )? """ def __init__(self, condition: Expression, true_body: ProgramBlock, false_body=None): self.condition = condition self.true_body = true_body self.false_body = false_body class ForLoopStatement(Statement): """ AST node for ``for`` loops. :: ForLoop: "for" Identifier "in" SetDeclaration ProgramBlock SetDeclaration: | Identifier | "{" Expression ("," Expression)* "}" | "[" Range "]" """ def __init__( self, indexset: Union[Identifier, IndexSet, Range], parameter: Identifier, body: ProgramBlock, ): self.indexset = indexset self.parameter = parameter self.body = body class WhileLoopStatement(Statement): """ AST node for ``while`` loops. :: WhileLoop: "while" "(" Expression ")" ProgramBlock """ def __init__(self, condition: Expression, body: ProgramBlock): self.condition = condition self.body = body class BreakStatement(Statement): """AST node for ``break`` statements. Has no associated information.""" class ContinueStatement(Statement): """AST node for ``continue`` statements. Has no associated information.""" class IOModifier(enum.Enum): """IO Modifier object""" INPUT = enum.auto() OUTPUT = enum.auto() class IODeclaration(ClassicalDeclaration): """A declaration of an IO variable.""" def __init__(self, modifier: IOModifier, type_: ClassicalType, identifier: Identifier): super().__init__(type_, identifier) self.modifier = modifier class DefaultCase(Expression): """An object representing the `default` special label in switch statements.""" class SwitchStatementPreview(Statement): """AST node for the proposed 'switch-case' extension to OpenQASM 3, before the syntax was stabilized. This corresponds to the :attr:`.ExperimentalFeatures.SWITCH_CASE_V1` logic. The stabilized form of the syntax instead uses :class:`.SwitchStatement`.""" def __init__( self, target: Expression, cases: Iterable[Tuple[Iterable[Expression], ProgramBlock]] ): self.target = target self.cases = [(tuple(values), case) for values, case in cases] class SwitchStatement(Statement): """AST node for the stable 'switch' statement of OpenQASM 3. The only real difference from an AST form is that the default is required to be separate; it cannot be joined with other cases (even though that's meaningless, the V1 syntax permitted it). """ def __init__( self, target: Expression, cases: Iterable[Tuple[Iterable[Expression], ProgramBlock]], default: Optional[ProgramBlock] = None, ): self.target = target self.cases = [(tuple(values), case) for values, case in cases] self.default = default
qiskit/qiskit/qasm3/ast.py/0
{ "file_path": "qiskit/qiskit/qasm3/ast.py", "repo_id": "qiskit", "token_count": 5823 }
203
# 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. """Read and write schedule and schedule instructions.""" import json import struct import zlib import warnings from io import BytesIO import numpy as np import symengine as sym from symengine.lib.symengine_wrapper import ( # pylint: disable = no-name-in-module load_basic, ) from qiskit.exceptions import QiskitError from qiskit.pulse import library, channels, instructions from qiskit.pulse.schedule import ScheduleBlock from qiskit.qpy import formats, common, type_keys from qiskit.qpy.binary_io import value from qiskit.qpy.exceptions import QpyError from qiskit.pulse.configuration import Kernel, Discriminator def _read_channel(file_obj, version): type_key = common.read_type_key(file_obj) index = value.read_value(file_obj, version, {}) channel_cls = type_keys.ScheduleChannel.retrieve(type_key) return channel_cls(index) def _read_waveform(file_obj, version): header = formats.WAVEFORM._make( struct.unpack( formats.WAVEFORM_PACK, file_obj.read(formats.WAVEFORM_SIZE), ) ) samples_raw = file_obj.read(header.data_size) samples = common.data_from_binary(samples_raw, np.load) name = value.read_value(file_obj, version, {}) return library.Waveform( samples=samples, name=name, epsilon=header.epsilon, limit_amplitude=header.amp_limited, ) def _loads_obj(type_key, binary_data, version, vectors): """Wraps `value.loads_value` to deserialize binary data to dictionary or list objects which are not supported by `value.loads_value`. """ if type_key == b"D": with BytesIO(binary_data) as container: return common.read_mapping( file_obj=container, deserializer=_loads_obj, version=version, vectors=vectors ) elif type_key == b"l": with BytesIO(binary_data) as container: return common.read_sequence( file_obj=container, deserializer=_loads_obj, version=version, vectors=vectors ) else: return value.loads_value(type_key, binary_data, version, vectors) def _read_kernel(file_obj, version): params = common.read_mapping( file_obj=file_obj, deserializer=_loads_obj, version=version, vectors={}, ) name = value.read_value(file_obj, version, {}) return Kernel(name=name, **params) def _read_discriminator(file_obj, version): params = common.read_mapping( file_obj=file_obj, deserializer=_loads_obj, version=version, vectors={}, ) name = value.read_value(file_obj, version, {}) return Discriminator(name=name, **params) def _loads_symbolic_expr(expr_bytes, use_symengine=False): if expr_bytes == b"": return None expr_bytes = zlib.decompress(expr_bytes) if use_symengine: return load_basic(expr_bytes) else: from sympy import parse_expr expr_txt = expr_bytes.decode(common.ENCODE) expr = parse_expr(expr_txt) return sym.sympify(expr) def _read_symbolic_pulse(file_obj, version): make = formats.SYMBOLIC_PULSE._make pack = formats.SYMBOLIC_PULSE_PACK size = formats.SYMBOLIC_PULSE_SIZE header = make( struct.unpack( pack, file_obj.read(size), ) ) pulse_type = file_obj.read(header.type_size).decode(common.ENCODE) envelope = _loads_symbolic_expr(file_obj.read(header.envelope_size)) constraints = _loads_symbolic_expr(file_obj.read(header.constraints_size)) valid_amp_conditions = _loads_symbolic_expr(file_obj.read(header.valid_amp_conditions_size)) parameters = common.read_mapping( file_obj, deserializer=value.loads_value, version=version, vectors={}, ) # In the transition to Qiskit Terra 0.23 (QPY version 6), the representation of library pulses # was changed from complex "amp" to float "amp" and "angle". The existing library pulses in # previous versions are handled here separately to conform with the new representation. To # avoid role assumption for "amp" for custom pulses, only the library pulses are handled this # way. # List of pulses in the library in QPY version 5 and below: legacy_library_pulses = ["Gaussian", "GaussianSquare", "Drag", "Constant"] class_name = "SymbolicPulse" # Default class name, if not in the library if pulse_type in legacy_library_pulses: parameters["angle"] = np.angle(parameters["amp"]) parameters["amp"] = np.abs(parameters["amp"]) _amp, _angle = sym.symbols("amp, angle") envelope = envelope.subs(_amp, _amp * sym.exp(sym.I * _angle)) warnings.warn( f"Library pulses with complex amp are no longer supported. " f"{pulse_type} with complex amp was converted to (amp,angle) representation.", UserWarning, ) class_name = "ScalableSymbolicPulse" duration = value.read_value(file_obj, version, {}) name = value.read_value(file_obj, version, {}) if class_name == "SymbolicPulse": return library.SymbolicPulse( pulse_type=pulse_type, duration=duration, parameters=parameters, name=name, limit_amplitude=header.amp_limited, envelope=envelope, constraints=constraints, valid_amp_conditions=valid_amp_conditions, ) elif class_name == "ScalableSymbolicPulse": return library.ScalableSymbolicPulse( pulse_type=pulse_type, duration=duration, amp=parameters["amp"], angle=parameters["angle"], parameters=parameters, name=name, limit_amplitude=header.amp_limited, envelope=envelope, constraints=constraints, valid_amp_conditions=valid_amp_conditions, ) else: raise NotImplementedError(f"Unknown class '{class_name}'") def _read_symbolic_pulse_v6(file_obj, version, use_symengine): make = formats.SYMBOLIC_PULSE_V2._make pack = formats.SYMBOLIC_PULSE_PACK_V2 size = formats.SYMBOLIC_PULSE_SIZE_V2 header = make( struct.unpack( pack, file_obj.read(size), ) ) class_name = file_obj.read(header.class_name_size).decode(common.ENCODE) pulse_type = file_obj.read(header.type_size).decode(common.ENCODE) envelope = _loads_symbolic_expr(file_obj.read(header.envelope_size), use_symengine) constraints = _loads_symbolic_expr(file_obj.read(header.constraints_size), use_symengine) valid_amp_conditions = _loads_symbolic_expr( file_obj.read(header.valid_amp_conditions_size), use_symengine ) parameters = common.read_mapping( file_obj, deserializer=value.loads_value, version=version, vectors={}, ) duration = value.read_value(file_obj, version, {}) name = value.read_value(file_obj, version, {}) if class_name == "SymbolicPulse": return library.SymbolicPulse( pulse_type=pulse_type, duration=duration, parameters=parameters, name=name, limit_amplitude=header.amp_limited, envelope=envelope, constraints=constraints, valid_amp_conditions=valid_amp_conditions, ) elif class_name == "ScalableSymbolicPulse": # Between Qiskit 0.40 and 0.46, the (amp, angle) representation was present, # but complex amp was still allowed. In Qiskit 1.0 and beyond complex amp # is no longer supported and so the amp needs to be checked and converted. # Once QPY version is bumped, a new reader function can be introduced without # this check. if isinstance(parameters["amp"], complex): parameters["angle"] = np.angle(parameters["amp"]) parameters["amp"] = np.abs(parameters["amp"]) warnings.warn( f"ScalableSymbolicPulse with complex amp are no longer supported. " f"{pulse_type} with complex amp was converted to (amp,angle) representation.", UserWarning, ) return library.ScalableSymbolicPulse( pulse_type=pulse_type, duration=duration, amp=parameters["amp"], angle=parameters["angle"], parameters=parameters, name=name, limit_amplitude=header.amp_limited, envelope=envelope, constraints=constraints, valid_amp_conditions=valid_amp_conditions, ) else: raise NotImplementedError(f"Unknown class '{class_name}'") def _read_alignment_context(file_obj, version): type_key = common.read_type_key(file_obj) context_params = common.read_sequence( file_obj, deserializer=value.loads_value, version=version, vectors={}, ) context_cls = type_keys.ScheduleAlignment.retrieve(type_key) instance = object.__new__(context_cls) instance._context_params = tuple(context_params) return instance # pylint: disable=too-many-return-statements def _loads_operand(type_key, data_bytes, version, use_symengine): if type_key == type_keys.ScheduleOperand.WAVEFORM: return common.data_from_binary(data_bytes, _read_waveform, version=version) if type_key == type_keys.ScheduleOperand.SYMBOLIC_PULSE: if version < 6: return common.data_from_binary(data_bytes, _read_symbolic_pulse, version=version) else: return common.data_from_binary( data_bytes, _read_symbolic_pulse_v6, version=version, use_symengine=use_symengine ) if type_key == type_keys.ScheduleOperand.CHANNEL: return common.data_from_binary(data_bytes, _read_channel, version=version) if type_key == type_keys.ScheduleOperand.OPERAND_STR: return data_bytes.decode(common.ENCODE) if type_key == type_keys.ScheduleOperand.KERNEL: return common.data_from_binary( data_bytes, _read_kernel, version=version, ) if type_key == type_keys.ScheduleOperand.DISCRIMINATOR: return common.data_from_binary( data_bytes, _read_discriminator, version=version, ) return value.loads_value(type_key, data_bytes, version, {}) def _read_element(file_obj, version, metadata_deserializer, use_symengine): type_key = common.read_type_key(file_obj) if type_key == type_keys.Program.SCHEDULE_BLOCK: return read_schedule_block(file_obj, version, metadata_deserializer, use_symengine) operands = common.read_sequence( file_obj, deserializer=_loads_operand, version=version, use_symengine=use_symengine ) name = value.read_value(file_obj, version, {}) instance = object.__new__(type_keys.ScheduleInstruction.retrieve(type_key)) instance._operands = tuple(operands) instance._name = name instance._hash = None return instance def _loads_reference_item(type_key, data_bytes, metadata_deserializer, version): if type_key == type_keys.Value.NULL: return None if type_key == type_keys.Program.SCHEDULE_BLOCK: return common.data_from_binary( data_bytes, deserializer=read_schedule_block, version=version, metadata_deserializer=metadata_deserializer, ) raise QpyError( f"Loaded schedule reference item is neither None nor ScheduleBlock. " f"Type key {type_key} is not valid data type for a reference items. " "This data cannot be loaded. Please check QPY version." ) def _write_channel(file_obj, data, version): type_key = type_keys.ScheduleChannel.assign(data) common.write_type_key(file_obj, type_key) value.write_value(file_obj, data.index, version=version) def _write_waveform(file_obj, data, version): samples_bytes = common.data_to_binary(data.samples, np.save) header = struct.pack( formats.WAVEFORM_PACK, data.epsilon, len(samples_bytes), data._limit_amplitude, ) file_obj.write(header) file_obj.write(samples_bytes) value.write_value(file_obj, data.name, version=version) def _dumps_obj(obj, version): """Wraps `value.dumps_value` to serialize dictionary and list objects which are not supported by `value.dumps_value`. """ if isinstance(obj, dict): with BytesIO() as container: common.write_mapping( file_obj=container, mapping=obj, serializer=_dumps_obj, version=version ) binary_data = container.getvalue() return b"D", binary_data elif isinstance(obj, list): with BytesIO() as container: common.write_sequence( file_obj=container, sequence=obj, serializer=_dumps_obj, version=version ) binary_data = container.getvalue() return b"l", binary_data else: return value.dumps_value(obj, version=version) def _write_kernel(file_obj, data, version): name = data.name params = data.params common.write_mapping(file_obj=file_obj, mapping=params, serializer=_dumps_obj, version=version) value.write_value(file_obj, name, version=version) def _write_discriminator(file_obj, data, version): name = data.name params = data.params common.write_mapping(file_obj=file_obj, mapping=params, serializer=_dumps_obj, version=version) value.write_value(file_obj, name, version=version) def _dumps_symbolic_expr(expr, use_symengine): if expr is None: return b"" if use_symengine: expr_bytes = expr.__reduce__()[1][0] else: from sympy import srepr, sympify expr_bytes = srepr(sympify(expr)).encode(common.ENCODE) return zlib.compress(expr_bytes) def _write_symbolic_pulse(file_obj, data, use_symengine, version): class_name_bytes = data.__class__.__name__.encode(common.ENCODE) pulse_type_bytes = data.pulse_type.encode(common.ENCODE) envelope_bytes = _dumps_symbolic_expr(data.envelope, use_symengine) constraints_bytes = _dumps_symbolic_expr(data.constraints, use_symengine) valid_amp_conditions_bytes = _dumps_symbolic_expr(data.valid_amp_conditions, use_symengine) header_bytes = struct.pack( formats.SYMBOLIC_PULSE_PACK_V2, len(class_name_bytes), len(pulse_type_bytes), len(envelope_bytes), len(constraints_bytes), len(valid_amp_conditions_bytes), data._limit_amplitude, ) file_obj.write(header_bytes) file_obj.write(class_name_bytes) file_obj.write(pulse_type_bytes) file_obj.write(envelope_bytes) file_obj.write(constraints_bytes) file_obj.write(valid_amp_conditions_bytes) common.write_mapping( file_obj, mapping=data._params, serializer=value.dumps_value, version=version, ) value.write_value(file_obj, data.duration, version=version) value.write_value(file_obj, data.name, version=version) def _write_alignment_context(file_obj, context, version): type_key = type_keys.ScheduleAlignment.assign(context) common.write_type_key(file_obj, type_key) common.write_sequence( file_obj, sequence=context._context_params, serializer=value.dumps_value, version=version ) def _dumps_operand(operand, use_symengine, version): if isinstance(operand, library.Waveform): type_key = type_keys.ScheduleOperand.WAVEFORM data_bytes = common.data_to_binary(operand, _write_waveform, version=version) elif isinstance(operand, library.SymbolicPulse): type_key = type_keys.ScheduleOperand.SYMBOLIC_PULSE data_bytes = common.data_to_binary( operand, _write_symbolic_pulse, use_symengine=use_symengine, version=version ) elif isinstance(operand, channels.Channel): type_key = type_keys.ScheduleOperand.CHANNEL data_bytes = common.data_to_binary(operand, _write_channel, version=version) elif isinstance(operand, str): type_key = type_keys.ScheduleOperand.OPERAND_STR data_bytes = operand.encode(common.ENCODE) elif isinstance(operand, Kernel): type_key = type_keys.ScheduleOperand.KERNEL data_bytes = common.data_to_binary(operand, _write_kernel, version=version) elif isinstance(operand, Discriminator): type_key = type_keys.ScheduleOperand.DISCRIMINATOR data_bytes = common.data_to_binary(operand, _write_discriminator, version=version) else: type_key, data_bytes = value.dumps_value(operand, version=version) return type_key, data_bytes def _write_element(file_obj, element, metadata_serializer, use_symengine, version): if isinstance(element, ScheduleBlock): common.write_type_key(file_obj, type_keys.Program.SCHEDULE_BLOCK) write_schedule_block(file_obj, element, metadata_serializer, use_symengine, version=version) else: type_key = type_keys.ScheduleInstruction.assign(element) common.write_type_key(file_obj, type_key) common.write_sequence( file_obj, sequence=element.operands, serializer=_dumps_operand, use_symengine=use_symengine, version=version, ) value.write_value(file_obj, element.name, version=version) def _dumps_reference_item(schedule, metadata_serializer, version): if schedule is None: type_key = type_keys.Value.NULL data_bytes = b"" else: type_key = type_keys.Program.SCHEDULE_BLOCK data_bytes = common.data_to_binary( obj=schedule, serializer=write_schedule_block, metadata_serializer=metadata_serializer, version=version, ) return type_key, data_bytes def read_schedule_block(file_obj, version, metadata_deserializer=None, use_symengine=False): """Read a single ScheduleBlock from the file like object. Args: file_obj (File): A file like object that contains the QPY binary data. version (int): QPY version. metadata_deserializer (JSONDecoder): An optional JSONDecoder class that will be used for the ``cls`` kwarg on the internal ``json.load`` call used to deserialize the JSON payload used for the :attr:`.ScheduleBlock.metadata` attribute for a schedule block in the file-like object. If this is not specified the circuit metadata will be parsed as JSON with the stdlib ``json.load()`` function using the default ``JSONDecoder`` class. use_symengine (bool): If True, symbolic objects will be serialized using symengine's native mechanism. This is a faster serialization alternative, but not supported in all platforms. Please check that your target platform is supported by the symengine library before setting this option, as it will be required by qpy to deserialize the payload. Returns: ScheduleBlock: The schedule block object from the file. Raises: TypeError: If any of the instructions is invalid data format. QiskitError: QPY version is earlier than block support. """ if version < 5: raise QiskitError(f"QPY version {version} does not support ScheduleBlock.") data = formats.SCHEDULE_BLOCK_HEADER._make( struct.unpack( formats.SCHEDULE_BLOCK_HEADER_PACK, file_obj.read(formats.SCHEDULE_BLOCK_HEADER_SIZE), ) ) name = file_obj.read(data.name_size).decode(common.ENCODE) metadata_raw = file_obj.read(data.metadata_size) metadata = json.loads(metadata_raw, cls=metadata_deserializer) context = _read_alignment_context(file_obj, version) block = ScheduleBlock( name=name, metadata=metadata, alignment_context=context, ) for _ in range(data.num_elements): block_elm = _read_element(file_obj, version, metadata_deserializer, use_symengine) block.append(block_elm, inplace=True) # Load references if version >= 7: flat_key_refdict = common.read_mapping( file_obj=file_obj, deserializer=_loads_reference_item, version=version, metadata_deserializer=metadata_deserializer, ) ref_dict = {} for key_str, schedule in flat_key_refdict.items(): if schedule is not None: composite_key = tuple(key_str.split(instructions.Reference.key_delimiter)) ref_dict[composite_key] = schedule if ref_dict: block.assign_references(ref_dict, inplace=True) return block def write_schedule_block( file_obj, block, metadata_serializer=None, use_symengine=False, version=common.QPY_VERSION ): """Write a single ScheduleBlock object in the file like object. Args: file_obj (File): The file like object to write the circuit data in. block (ScheduleBlock): A schedule block data to write. metadata_serializer (JSONEncoder): An optional JSONEncoder class that will be passed the :attr:`.ScheduleBlock.metadata` dictionary for ``block`` and will be used as the ``cls`` kwarg on the ``json.dump()`` call to JSON serialize that dictionary. use_symengine (bool): If True, symbolic objects will be serialized using symengine's native mechanism. This is a faster serialization alternative, but not supported in all platforms. Please check that your target platform is supported by the symengine library before setting this option, as it will be required by qpy to deserialize the payload. version (int): The QPY format version to use for serializing this circuit block Raises: TypeError: If any of the instructions is invalid data format. """ metadata = json.dumps(block.metadata, separators=(",", ":"), cls=metadata_serializer).encode( common.ENCODE ) block_name = block.name.encode(common.ENCODE) # Write schedule block header header_raw = formats.SCHEDULE_BLOCK_HEADER( name_size=len(block_name), metadata_size=len(metadata), num_elements=len(block), ) header = struct.pack(formats.SCHEDULE_BLOCK_HEADER_PACK, *header_raw) file_obj.write(header) file_obj.write(block_name) file_obj.write(metadata) _write_alignment_context(file_obj, block.alignment_context, version=version) for block_elm in block._blocks: # Do not call block.blocks. This implicitly assigns references to instruction. # This breaks original reference structure. _write_element(file_obj, block_elm, metadata_serializer, use_symengine, version=version) # Write references flat_key_refdict = {} for ref_keys, schedule in block._reference_manager.items(): # Do not call block.reference. This returns the reference of most outer program by design. key_str = instructions.Reference.key_delimiter.join(ref_keys) flat_key_refdict[key_str] = schedule common.write_mapping( file_obj=file_obj, mapping=flat_key_refdict, serializer=_dumps_reference_item, metadata_serializer=metadata_serializer, version=version, )
qiskit/qiskit/qpy/binary_io/schedules.py/0
{ "file_path": "qiskit/qiskit/qpy/binary_io/schedules.py", "repo_id": "qiskit", "token_count": 9854 }
204
# 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. """ Chi-matrix representation of a Quantum Channel. """ from __future__ import annotations import copy as _copy import math import numpy as np from qiskit import _numpy_compat from qiskit.circuit.quantumcircuit import QuantumCircuit from qiskit.circuit.instruction import Instruction from qiskit.exceptions import QiskitError from qiskit.quantum_info.operators.channel.quantum_channel import QuantumChannel from qiskit.quantum_info.operators.channel.choi import Choi from qiskit.quantum_info.operators.channel.superop import SuperOp from qiskit.quantum_info.operators.channel.transformations import _to_chi from qiskit.quantum_info.operators.mixins import generate_apidocs from qiskit.quantum_info.operators.base_operator import BaseOperator class Chi(QuantumChannel): r"""Pauli basis Chi-matrix representation of a quantum channel. The Chi-matrix representation of an :math:`n`-qubit quantum channel :math:`\mathcal{E}` is a matrix :math:`\chi` such that the evolution of a :class:`~qiskit.quantum_info.DensityMatrix` :math:`\rho` is given by .. math:: \mathcal{E}(ρ) = \frac{1}{2^n} \sum_{i, j} \chi_{i,j} P_i ρ P_j where :math:`[P_0, P_1, ..., P_{4^{n}-1}]` is the :math:`n`-qubit Pauli basis in lexicographic order. It is related to the :class:`Choi` representation by a change of basis of the Choi-matrix into the Pauli basis. The :math:`\frac{1}{2^n}` in the definition above is a normalization factor that arises from scaling the Pauli basis to make it orthonormal. See reference [1] for further details. References: 1. C.J. Wood, J.D. Biamonte, D.G. Cory, *Tensor networks and graphical calculus for open quantum systems*, Quant. Inf. Comp. 15, 0579-0811 (2015). `arXiv:1111.6950 [quant-ph] <https://arxiv.org/abs/1111.6950>`_ """ def __init__( self, data: QuantumCircuit | Instruction | BaseOperator | np.ndarray, input_dims: int | tuple | None = None, output_dims: int | tuple | None = None, ): """Initialize a quantum channel Chi-matrix operator. Args: data (QuantumCircuit or Instruction or BaseOperator or matrix): data to initialize superoperator. input_dims (tuple): the input subsystem dimensions. [Default: None] output_dims (tuple): the output subsystem dimensions. [Default: None] Raises: QiskitError: if input data is not an N-qubit channel or cannot be initialized as a Chi-matrix. Additional Information: If the input or output dimensions are None, they will be automatically determined from the input data. The Chi matrix representation is only valid for N-qubit channels. """ # If the input is a raw list or matrix we assume that it is # already a Chi matrix. if isinstance(data, (list, np.ndarray)): # Initialize from raw numpy or list matrix. chi_mat = np.asarray(data, dtype=complex) # Determine input and output dimensions dim_l, dim_r = chi_mat.shape if dim_l != dim_r: raise QiskitError("Invalid Chi-matrix input.") if input_dims: input_dim = np.prod(input_dims) if output_dims: output_dim = np.prod(input_dims) if output_dims is None and input_dims is None: output_dim = int(math.sqrt(dim_l)) input_dim = dim_l // output_dim elif input_dims is None: input_dim = dim_l // output_dim elif output_dims is None: output_dim = dim_l // input_dim # Check dimensions if input_dim * output_dim != dim_l: raise QiskitError("Invalid shape for Chi-matrix input.") else: # Otherwise we initialize by conversion from another Qiskit # object into the QuantumChannel. if isinstance(data, (QuantumCircuit, Instruction)): # If the input is a Terra QuantumCircuit or Instruction we # convert it to a SuperOp data = SuperOp._init_instruction(data) else: # We use the QuantumChannel init transform to initialize # other objects into a QuantumChannel or Operator object. data = self._init_transformer(data) input_dim, output_dim = data.dim # Now that the input is an operator we convert it to a Chi object rep = getattr(data, "_channel_rep", "Operator") chi_mat = _to_chi(rep, data._data, input_dim, output_dim) if input_dims is None: input_dims = data.input_dims() if output_dims is None: output_dims = data.output_dims() # Check input is N-qubit channel num_qubits = int(math.log2(input_dim)) if 2**num_qubits != input_dim or input_dim != output_dim: raise QiskitError("Input is not an n-qubit Chi matrix.") super().__init__(chi_mat, num_qubits=num_qubits) def __array__(self, dtype=None, copy=_numpy_compat.COPY_ONLY_IF_NEEDED): dtype = self.data.dtype return np.array(self.data, dtype=dtype, copy=copy) @property def _bipartite_shape(self): """Return the shape for bipartite matrix""" return (self._input_dim, self._output_dim, self._input_dim, self._output_dim) def _evolve(self, state, qargs=None): return SuperOp(self)._evolve(state, qargs) # --------------------------------------------------------------------- # BaseOperator methods # --------------------------------------------------------------------- def conjugate(self): # Since conjugation is basis dependent we transform # to the Choi representation to compute the # conjugate channel return Chi(Choi(self).conjugate()) def transpose(self): return Chi(Choi(self).transpose()) def adjoint(self): return Chi(Choi(self).adjoint()) def compose(self, other: Chi, qargs: list | None = None, front: bool = False) -> Chi: if qargs is None: qargs = getattr(other, "qargs", None) if qargs is not None: return Chi(SuperOp(self).compose(other, qargs=qargs, front=front)) # If no qargs we compose via Choi representation to avoid an additional # representation conversion to SuperOp and then convert back to Chi return Chi(Choi(self).compose(other, front=front)) def tensor(self, other: Chi) -> Chi: if not isinstance(other, Chi): other = Chi(other) return self._tensor(self, other) def expand(self, other: Chi) -> Chi: if not isinstance(other, Chi): other = Chi(other) return self._tensor(other, self) @classmethod def _tensor(cls, a, b): ret = _copy.copy(a) ret._op_shape = a._op_shape.tensor(b._op_shape) ret._data = np.kron(a._data, b.data) return ret # Update docstrings for API docs generate_apidocs(Chi)
qiskit/qiskit/quantum_info/operators/channel/chi.py/0
{ "file_path": "qiskit/qiskit/quantum_info/operators/channel/chi.py", "repo_id": "qiskit", "token_count": 3246 }
205
# 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. """ Operator Mixins """ from inspect import getdoc from .group import GroupMixin from .adjoint import AdjointMixin from .linear import LinearMixin from .multiply import MultiplyMixin from .tolerances import TolerancesMixin def generate_apidocs(cls): """Decorator to format API docstrings for classes using Mixins. This runs string replacement on the docstrings of the mixin methods to replace the placeholder CLASS with the class name `cls.__name__`. Args: cls (type): The class to format docstrings. Returns: cls: the original class with updated docstrings. """ def _replace_name(mixin, methods): if issubclass(cls, mixin): for i in methods: meth = getattr(cls, i) doc = getdoc(meth) if doc is not None: meth.__doc__ = doc.replace("CLASS", cls.__name__) _replace_name(GroupMixin, ("tensor", "expand", "compose", "dot", "power")) _replace_name(AdjointMixin, ("transpose", "conjugate", "adjoint")) _replace_name(MultiplyMixin, ("_multiply",)) _replace_name(LinearMixin, ("_add",)) return cls
qiskit/qiskit/quantum_info/operators/mixins/__init__.py/0
{ "file_path": "qiskit/qiskit/quantum_info/operators/mixins/__init__.py", "repo_id": "qiskit", "token_count": 599 }
206
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2020 # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ N-qubit Pauli Operator Class """ from __future__ import annotations import re from typing import Literal, TYPE_CHECKING import numpy as np from qiskit.circuit import Instruction, QuantumCircuit from qiskit.circuit.barrier import Barrier from qiskit.circuit.delay import Delay from qiskit.circuit.library.generalized_gates import PauliGate from qiskit.circuit.library.standard_gates import IGate, XGate, YGate, ZGate from qiskit.exceptions import QiskitError from qiskit.quantum_info.operators.mixins import generate_apidocs from qiskit.quantum_info.operators.scalar_op import ScalarOp from qiskit.quantum_info.operators.symplectic.base_pauli import BasePauli, _count_y if TYPE_CHECKING: from qiskit.quantum_info.operators.symplectic.clifford import Clifford from qiskit.quantum_info.operators.symplectic.pauli_list import PauliList from qiskit.transpiler.layout import TranspileLayout class Pauli(BasePauli): r"""N-qubit Pauli operator. This class represents an operator :math:`P` from the full :math:`n`-qubit *Pauli* group .. math:: P = (-i)^{q} P_{n-1} \otimes ... \otimes P_{0} where :math:`q\in \mathbb{Z}_4` and :math:`P_i \in \{I, X, Y, Z\}` are single-qubit Pauli matrices: .. math:: I = \begin{pmatrix} 1 & 0 \\ 0 & 1 \end{pmatrix}, X = \begin{pmatrix} 0 & 1 \\ 1 & 0 \end{pmatrix}, Y = \begin{pmatrix} 0 & -i \\ i & 0 \end{pmatrix}, Z = \begin{pmatrix} 1 & 0 \\ 0 & -1 \end{pmatrix}. **Initialization** A Pauli object can be initialized in several ways: ``Pauli(obj)`` where ``obj`` is a Pauli string, ``Pauli`` or :class:`~qiskit.quantum_info.ScalarOp` operator, or a Pauli gate or :class:`~qiskit.QuantumCircuit` containing only Pauli gates. ``Pauli((z, x, phase))`` where ``z`` and ``x`` are boolean ``numpy.ndarrays`` and ``phase`` is an integer in ``[0, 1, 2, 3]``. ``Pauli((z, x))`` equivalent to ``Pauli((z, x, 0))`` with trivial phase. **String representation** An :math:`n`-qubit Pauli may be represented by a string consisting of :math:`n` characters from ``['I', 'X', 'Y', 'Z']``, and optionally phase coefficient in ``['', '-i', '-', 'i']``. For example: ``'XYZ'`` or ``'-iZIZ'``. In the string representation qubit-0 corresponds to the right-most Pauli character, and qubit-:math:`(n-1)` to the left-most Pauli character. For example ``'XYZ'`` represents :math:`X\otimes Y \otimes Z` with ``'Z'`` on qubit-0, ``'Y'`` on qubit-1, and ``'X'`` on qubit-2. The string representation can be converted to a ``Pauli`` using the class initialization (``Pauli('-iXYZ')``). A ``Pauli`` object can be converted back to the string representation using the :meth:`to_label` method or ``str(pauli)``. .. note:: Using ``str`` to convert a ``Pauli`` to a string will truncate the returned string for large numbers of qubits while :meth:`to_label` will return the full string with no truncation. The default truncation length is 50 characters. The default value can be changed by setting the class ``__truncate__`` attribute to an integer value. If set to ``0`` no truncation will be performed. **Array Representation** The internal data structure of an :math:`n`-qubit Pauli is two length-:math:`n` boolean vectors :math:`z \in \mathbb{Z}_2^N`, :math:`x \in \mathbb{Z}_2^N`, and an integer :math:`q \in \mathbb{Z}_4` defining the Pauli operator .. math:: P = (-i)^{q + z\cdot x} Z^z \cdot X^x. The :math:`k`-th qubit corresponds to the :math:`k`-th entry in the :math:`z` and :math:`x` arrays .. math:: \begin{aligned} P &= P_{n-1} \otimes ... \otimes P_{0} \\ P_k &= (-i)^{z[k] * x[k]} Z^{z[k]}\cdot X^{x[k]} \end{aligned} where ``z[k] = P.z[k]``, ``x[k] = P.x[k]`` respectively. The :math:`z` and :math:`x` arrays can be accessed and updated using the :attr:`z` and :attr:`x` properties respectively. The phase integer :math:`q` can be accessed and updated using the :attr:`phase` property. **Matrix Operator Representation** Pauli's can be converted to :math:`(2^n, 2^n)` :class:`~qiskit.quantum_info.Operator` using the :meth:`to_operator` method, or to a dense or sparse complex matrix using the :meth:`to_matrix` method. **Data Access** The individual qubit Paulis can be accessed and updated using the ``[]`` operator which accepts integer, lists, or slices for selecting subsets of Paulis. Note that selecting subsets of Pauli's will discard the phase of the current Pauli. For example .. code-block:: python P = Pauli('-iXYZ') print('P[0] =', repr(P[0])) print('P[1] =', repr(P[1])) print('P[2] =', repr(P[2])) print('P[:] =', repr(P[:])) print('P[::-1] =', repr(P[::-1])) """ # Set the max Pauli string size before truncation __truncate__ = 50 _VALID_LABEL_PATTERN = re.compile(r"(?P<coeff>[+-]?1?[ij]?)(?P<pauli>[IXYZ]*)") _CANONICAL_PHASE_LABEL = {"": 0, "-i": 1, "-": 2, "i": 3} def __init__(self, data: str | tuple | Pauli | ScalarOp | QuantumCircuit | None = None): r"""Initialize the Pauli. When using the symplectic array input data both z and x arguments must be provided, however the first (z) argument can be used alone for string label, Pauli operator, or :class:`.ScalarOp` input data. Args: data (str or tuple or Pauli or ScalarOp): input data for Pauli. If input is a tuple it must be of the form ``(z, x)`` or ``(z, x, phase)`` where ``z`` and ``x`` are boolean Numpy arrays, and phase is an integer from :math:`\mathbb{Z}_4`. If input is a string, it must be a concatenation of a phase and a Pauli string (e.g. ``'XYZ', '-iZIZ'``) where a phase string is a combination of at most three characters from ``['+', '-', '']``, ``['1', '']``, and ``['i', 'j', '']`` in this order, e.g. ``''``, ``'-1j'`` while a Pauli string is 1 or more characters of ``'I'``, ``'X'``, ``'Y'``, or ``'Z'``, e.g. ``'Z'``, ``'XIYY'``. Raises: QiskitError: if input array is invalid shape. """ if isinstance(data, BasePauli): base_z, base_x, base_phase = data._z, data._x, data._phase elif isinstance(data, tuple): if len(data) not in [2, 3]: raise QiskitError( "Invalid input tuple for Pauli, input tuple must be `(z, x, phase)` or `(z, x)`" ) base_z, base_x, base_phase = self._from_array(*data) elif isinstance(data, str): base_z, base_x, base_phase = self._from_label(data) elif isinstance(data, ScalarOp): base_z, base_x, base_phase = self._from_scalar_op(data) elif isinstance(data, (QuantumCircuit, Instruction)): base_z, base_x, base_phase = self._from_circuit(data) else: raise QiskitError("Invalid input data for Pauli.") # Initialize BasePauli if base_z.shape[0] != 1: raise QiskitError("Input is not a single Pauli") super().__init__(base_z, base_x, base_phase) @property def name(self): """Unique string identifier for operation type.""" return "pauli" @property def num_clbits(self): """Number of classical bits.""" return 0 def __repr__(self): """Display representation.""" return f"Pauli('{self.__str__()}')" def __str__(self): """Print representation.""" if self.__truncate__ and self.num_qubits > self.__truncate__: front = self[-self.__truncate__ :].to_label() return front + "..." return self.to_label() def __array__(self, dtype=None, copy=None): if copy is False: raise ValueError("unable to avoid copy while creating an array as requested") arr = self.to_matrix() return arr if dtype is None else arr.astype(dtype, copy=False) @classmethod def set_truncation(cls, val: int): """Set the max number of Pauli characters to display before truncation/ Args: val (int): the number of characters. .. note:: Truncation will be disabled if the truncation value is set to 0. """ cls.__truncate__ = int(val) def __eq__(self, other): """Test if two Paulis are equal.""" if not isinstance(other, BasePauli): return False return self._eq(other) def equiv(self, other: Pauli) -> bool: """Return True if Pauli's are equivalent up to group phase. Args: other (Pauli): an operator object. Returns: bool: True if the Pauli's are equivalent up to group phase. """ if not isinstance(other, Pauli): try: other = Pauli(other) except QiskitError: return False return np.all(self._z == other._z) and np.all(self._x == other._x) @property def settings(self) -> dict: """Return settings.""" return {"data": self.to_label()} # --------------------------------------------------------------------- # Direct array access # --------------------------------------------------------------------- @property def phase(self): """Return the group phase exponent for the Pauli.""" # Convert internal ZX-phase convention of BasePauli to group phase return np.mod(self._phase - self._count_y(dtype=self._phase.dtype), 4)[0] @phase.setter def phase(self, value): # Convert group phase convention to internal ZX-phase convention self._phase[:] = np.mod(value + self._count_y(dtype=self._phase.dtype), 4) @property def x(self): """The x vector for the Pauli.""" return self._x[0] @x.setter def x(self, val): self._x[0, :] = val @property def z(self): """The z vector for the Pauli.""" return self._z[0] @z.setter def z(self, val): self._z[0, :] = val # --------------------------------------------------------------------- # Pauli Array methods # --------------------------------------------------------------------- def __len__(self): """Return the number of qubits in the Pauli.""" return self.num_qubits def __getitem__(self, qubits): """Return the unsigned Pauli group Pauli for subset of qubits.""" # Set group phase to 0 so returned Pauli is always +1 coeff if isinstance(qubits, (int, np.integer)): qubits = [qubits] return Pauli((self.z[qubits], self.x[qubits])) def __setitem__(self, qubits, value): """Update the Pauli for a subset of qubits.""" if not isinstance(value, Pauli): value = Pauli(value) self._z[0, qubits] = value.z self._x[0, qubits] = value.x # Add extra phase from new Pauli to current self._phase = self._phase + value._phase def delete(self, qubits: int | list) -> Pauli: """Return a Pauli with qubits deleted. Args: qubits (int or list): qubits to delete from Pauli. Returns: Pauli: the resulting Pauli with the specified qubits removed. Raises: QiskitError: if ind is out of bounds for the array size or number of qubits. """ if isinstance(qubits, (int, np.integer)): qubits = [qubits] if len(qubits) == 0: return Pauli((self._z, self._x, self.phase)) if max(qubits) > self.num_qubits - 1: raise QiskitError( "Qubit index is larger than the number of qubits " f"({max(qubits)}>{self.num_qubits - 1})." ) if len(qubits) == self.num_qubits: raise QiskitError("Cannot delete all qubits of Pauli") z = np.delete(self._z, qubits, axis=1) x = np.delete(self._x, qubits, axis=1) return Pauli((z, x, self.phase)) def insert(self, qubits: int | list, value: Pauli) -> Pauli: """Insert a Pauli at specific qubit value. Args: qubits (int or list): qubits index to insert at. value (Pauli): value to insert. Returns: Pauli: the resulting Pauli with the entries inserted. Raises: QiskitError: if the insertion qubits are invalid. """ if not isinstance(value, Pauli): value = Pauli(value) # Initialize empty operator ret_qubits = self.num_qubits + value.num_qubits ret = Pauli((np.zeros(ret_qubits, dtype=bool), np.zeros(ret_qubits, dtype=bool))) if isinstance(qubits, (int, np.integer)): if value.num_qubits == 1: qubits = [qubits] else: qubits = list(range(qubits, qubits + value.num_qubits)) if len(qubits) != value.num_qubits: raise QiskitError( "Number of indices does not match number of qubits for " f"the inserted Pauli ({len(qubits)}!={value.num_qubits})" ) if max(qubits) > ret.num_qubits - 1: raise QiskitError( "Index is too larger for combined Pauli number of qubits " f"({max(qubits)}>{ret.num_qubits - 1})." ) # Qubit positions for original op self_qubits = [i for i in range(ret.num_qubits) if i not in qubits] ret[self_qubits] = self ret[qubits] = value return ret # --------------------------------------------------------------------- # Representation conversions # --------------------------------------------------------------------- def __hash__(self): """Make hashable based on string representation.""" return hash(self.to_label()) def to_label(self) -> str: """Convert a Pauli to a string label. .. note:: The difference between `to_label` and :meth:`__str__` is that the later will truncate the output for large numbers of qubits. Returns: str: the Pauli string label. """ return self._to_label(self.z, self.x, self._phase[0]) def to_matrix(self, sparse: bool = False) -> np.ndarray: r"""Convert to a Numpy array or sparse CSR matrix. Args: sparse (bool): if True return sparse CSR matrices, otherwise return dense Numpy arrays (default: False). Returns: array: The Pauli matrix. """ return self._to_matrix(self.z, self.x, self._phase[0], sparse=sparse) def to_instruction(self): """Convert to Pauli circuit instruction.""" from math import pi pauli, phase = self._to_label( self.z, self.x, self._phase[0], full_group=False, return_phase=True ) if len(pauli) == 1: gate = {"I": IGate(), "X": XGate(), "Y": YGate(), "Z": ZGate()}[pauli] else: gate = PauliGate(pauli) if not phase: return gate # Add global phase circuit = QuantumCircuit(self.num_qubits, name=str(self)) circuit.global_phase = -phase * pi / 2 circuit.append(gate, range(self.num_qubits)) return circuit.to_instruction() # --------------------------------------------------------------------- # BaseOperator methods # --------------------------------------------------------------------- def compose( self, other: Pauli, qargs: list | None = None, front: bool = False, inplace: bool = False ) -> Pauli: """Return the operator composition with another Pauli. Args: other (Pauli): a Pauli object. qargs (list or None): Optional, qubits to apply dot product on (default: None). front (bool): If True compose using right operator multiplication, instead of left multiplication [default: False]. inplace (bool): If True update in-place (default: False). Returns: Pauli: The composed Pauli. Raises: QiskitError: if other cannot be converted to an operator, or has incompatible dimensions for specified subsystems. .. note:: Composition (``&``) by default is defined as `left` matrix multiplication for matrix operators, while :meth:`dot` is defined as `right` matrix multiplication. That is that ``A & B == A.compose(B)`` is equivalent to ``B.dot(A)`` when ``A`` and ``B`` are of the same type. Setting the ``front=True`` kwarg changes this to `right` matrix multiplication and is equivalent to the :meth:`dot` method ``A.dot(B) == A.compose(B, front=True)``. """ if qargs is None: qargs = getattr(other, "qargs", None) if not isinstance(other, Pauli): other = Pauli(other) return Pauli(super().compose(other, qargs=qargs, front=front, inplace=inplace)) def dot(self, other: Pauli, qargs: list | None = None, inplace: bool = False) -> Pauli: """Return the right multiplied operator self * other. Args: other (Pauli): an operator object. qargs (list or None): Optional, qubits to apply dot product on (default: None). inplace (bool): If True update in-place (default: False). Returns: Pauli: The operator self * other. """ return self.compose(other, qargs=qargs, front=True, inplace=inplace) def tensor(self, other: Pauli) -> Pauli: if not isinstance(other, Pauli): other = Pauli(other) return Pauli(super().tensor(other)) def expand(self, other: Pauli) -> Pauli: if not isinstance(other, Pauli): other = Pauli(other) return Pauli(super().expand(other)) def _multiply(self, other): return Pauli(super()._multiply(other)) def conjugate(self): return Pauli(super().conjugate()) def transpose(self): return Pauli(super().transpose()) def adjoint(self): return Pauli(super().adjoint()) def inverse(self): """Return the inverse of the Pauli.""" return Pauli(super().adjoint()) # --------------------------------------------------------------------- # Utility methods # --------------------------------------------------------------------- def commutes(self, other: Pauli | PauliList, qargs: list | None = None) -> bool: """Return True if the Pauli commutes with other. Args: other (Pauli or PauliList): another Pauli operator. qargs (list): qubits to apply dot product on (default: None). Returns: bool: True if Pauli's commute, False if they anti-commute. """ if qargs is None: qargs = getattr(other, "qargs", None) if not isinstance(other, BasePauli): other = Pauli(other) ret = super().commutes(other, qargs=qargs) if len(ret) == 1: return ret[0] return ret def anticommutes(self, other: Pauli, qargs: list | None = None) -> bool: """Return True if other Pauli anticommutes with self. Args: other (Pauli): another Pauli operator. qargs (list): qubits to apply dot product on (default: None). Returns: bool: True if Pauli's anticommute, False if they commute. """ return np.logical_not(self.commutes(other, qargs=qargs)) def evolve( self, other: Pauli | Clifford | QuantumCircuit, qargs: list | None = None, frame: Literal["h", "s"] = "h", ) -> Pauli: r"""Performs either Heisenberg (default) or SchrΓΆdinger picture evolution of the Pauli by a Clifford and returns the evolved Pauli. SchrΓΆdinger picture evolution can be chosen by passing parameter ``frame='s'``. This option yields a faster calculation. Heisenberg picture evolves the Pauli as :math:`P^\prime = C^\dagger.P.C`. SchrΓΆdinger picture evolves the Pauli as :math:`P^\prime = C.P.C^\dagger`. Args: other (Pauli or Clifford or QuantumCircuit): The Clifford operator to evolve by. qargs (list): a list of qubits to apply the Clifford to. frame (string): ``'h'`` for Heisenberg (default) or ``'s'`` for SchrΓΆdinger framework. Returns: Pauli: the Pauli :math:`C^\dagger.P.C` (Heisenberg picture) or the Pauli :math:`C.P.C^\dagger` (SchrΓΆdinger picture). Raises: QiskitError: if the Clifford number of qubits and qargs don't match. """ if qargs is None: qargs = getattr(other, "qargs", None) # pylint: disable=cyclic-import from qiskit.quantum_info.operators.symplectic.clifford import Clifford if not isinstance(other, (Pauli, Instruction, QuantumCircuit, Clifford)): # Convert to a Pauli other = Pauli(other) return Pauli(super().evolve(other, qargs=qargs, frame=frame)) # --------------------------------------------------------------------- # Initialization helper functions # --------------------------------------------------------------------- @staticmethod def _from_label(label): """Return the symplectic representation of Pauli string. Args: label (str): the Pauli string label. Returns: BasePauli: the BasePauli corresponding to the label. Raises: QiskitError: if Pauli string is not valid. """ match_ = Pauli._VALID_LABEL_PATTERN.fullmatch(label) if match_ is None: raise QiskitError(f'Pauli string label "{label}" is not valid.') phase = Pauli._CANONICAL_PHASE_LABEL[ (match_["coeff"] or "").replace("1", "").replace("+", "").replace("j", "i") ] # Convert to Symplectic representation pauli_bytes = np.frombuffer(match_["pauli"].encode("ascii"), dtype=np.uint8)[::-1] ys = pauli_bytes == ord("Y") base_x = np.logical_or(pauli_bytes == ord("X"), ys).reshape(1, -1) base_z = np.logical_or(pauli_bytes == ord("Z"), ys).reshape(1, -1) base_phase = np.array([(phase + np.count_nonzero(ys)) % 4], dtype=int) return base_z, base_x, base_phase @classmethod def _from_scalar_op(cls, op): """Convert a ScalarOp to BasePauli data.""" if op.num_qubits is None: raise QiskitError(f"{op} is not an N-qubit identity") base_z = np.zeros((1, op.num_qubits), dtype=bool) base_x = np.zeros((1, op.num_qubits), dtype=bool) base_phase = np.mod( cls._phase_from_complex(op.coeff) + _count_y(base_x, base_z), 4, dtype=int ) return base_z, base_x, base_phase @classmethod def _from_pauli_instruction(cls, instr): """Convert a Pauli instruction to BasePauli data.""" if isinstance(instr, PauliGate): return cls._from_label(instr.params[0]) if isinstance(instr, IGate): return np.array([[False]]), np.array([[False]]), np.array([0]) if isinstance(instr, XGate): return np.array([[False]]), np.array([[True]]), np.array([0]) if isinstance(instr, YGate): return np.array([[True]]), np.array([[True]]), np.array([1]) if isinstance(instr, ZGate): return np.array([[True]]), np.array([[False]]), np.array([0]) raise QiskitError("Invalid Pauli instruction.") @classmethod def _from_circuit(cls, instr): """Convert a Pauli circuit to BasePauli data.""" # Try and convert single instruction if isinstance(instr, (PauliGate, IGate, XGate, YGate, ZGate)): return cls._from_pauli_instruction(instr) if isinstance(instr, Instruction): # Convert other instructions to circuit definition if instr.definition is None: raise QiskitError(f"Cannot apply Instruction: {instr.name}") # Convert to circuit instr = instr.definition # Initialize identity Pauli ret = Pauli( BasePauli( np.zeros((1, instr.num_qubits), dtype=bool), np.zeros((1, instr.num_qubits), dtype=bool), np.zeros(1, dtype=int), ) ) # Add circuit global phase if specified if instr.global_phase: ret.phase = cls._phase_from_complex(np.exp(1j * float(instr.global_phase))) # Recursively apply instructions for inner in instr.data: if inner.clbits: raise QiskitError( f"Cannot apply instruction with classical bits: {inner.operation.name}" ) if not isinstance(inner.operation, (Barrier, Delay)): next_instr = BasePauli(*cls._from_circuit(inner.operation)) if next_instr is not None: qargs = [instr.find_bit(tup).index for tup in inner.qubits] ret = ret.compose(next_instr, qargs=qargs) return ret._z, ret._x, ret._phase def apply_layout( self, layout: TranspileLayout | list[int] | None, num_qubits: int | None = None ) -> Pauli: """Apply a transpiler layout to this :class:`~.Pauli` Args: layout: Either a :class:`~.TranspileLayout`, a list of integers or None. If both layout and num_qubits are none, a copy of the operator is returned. num_qubits: The number of qubits to expand the operator to. If not provided then if ``layout`` is a :class:`~.TranspileLayout` the number of the transpiler output circuit qubits will be used by default. If ``layout`` is a list of integers the permutation specified will be applied without any expansion. If layout is None, the operator will be expanded to the given number of qubits. Returns: A new :class:`.Pauli` with the provided layout applied """ from qiskit.transpiler.layout import TranspileLayout if layout is None and num_qubits is None: return self.copy() n_qubits = self.num_qubits if isinstance(layout, TranspileLayout): n_qubits = len(layout._output_qubit_list) layout = layout.final_index_layout() if num_qubits is not None: if num_qubits < n_qubits: raise QiskitError( f"The input num_qubits is too small, a {num_qubits} qubit layout cannot be " f"applied to a {n_qubits} qubit operator" ) n_qubits = num_qubits if layout is None: layout = list(range(self.num_qubits)) else: if any(x < 0 or x >= n_qubits for x in layout): raise QiskitError("Provided layout contains indices outside the number of qubits.") if len(set(layout)) != len(layout): raise QiskitError("Provided layout contains duplicate indices.") new_op = type(self)("I" * n_qubits) return new_op.compose(self, qargs=layout) # Update docstrings for API docs generate_apidocs(Pauli)
qiskit/qiskit/quantum_info/operators/symplectic/pauli.py/0
{ "file_path": "qiskit/qiskit/quantum_info/operators/symplectic/pauli.py", "repo_id": "qiskit", "token_count": 12377 }
207
# 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 from collections.abc import Collection 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 Given a list of stabilizers, :meth:`qiskit.quantum_info.StabilizerState.from_stabilizer_list` returns a state stabilized by the list .. code-block:: python from qiskit.quantum_info import StabilizerState stabilizer_list = ["ZXX", "-XYX", "+ZYY"] stab = StabilizerState.from_stabilizer_list(stabilizer_list) 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)) @classmethod def from_stabilizer_list( cls, stabilizers: Collection[str], allow_redundant: bool = False, allow_underconstrained: bool = False, ) -> StabilizerState: """Create a stabilizer state from the collection of stabilizers. Args: stabilizers (Collection[str]): list of stabilizer strings allow_redundant (bool): allow redundant stabilizers (i.e., some stabilizers can be products of the others) allow_underconstrained (bool): allow underconstrained set of stabilizers (i.e., the stabilizers do not specify a unique state) Return: StabilizerState: a state stabilized by stabilizers. """ # pylint: disable=cyclic-import from qiskit.synthesis.stabilizer import synth_circuit_from_stabilizers circuit = synth_circuit_from_stabilizers( stabilizers, allow_redundant=allow_redundant, allow_underconstrained=allow_underconstrained, ) return cls(circuit) def __eq__(self, other): return (self._data.stab == other._data.stab).all() def __repr__(self): return f"StabilizerState({self._data.to_labels(mode='S')})" @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 destabilisers 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_from_bitstring( self, outcome_bitstring: str, qargs: None | list = None, decimals: None | int = None, ) -> dict[str, float]: """Return the subsystem measurement probability dictionary utilizing a targeted outcome_bitstring to perform the measurement for. This will calculate a probability for only a single targeted outcome_bitstring value, giving a performance boost over calculating all possible outcomes. 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: outcome_bitstring (None or str): targeted outcome bitstring to perform a measurement calculation for, this will significantly reduce the number of calculation performed (Default: None) 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[str, float]: The measurement probabilities in dict (ket) form. """ return self._get_probabilities_dict( outcome_bitstring=outcome_bitstring, qargs=qargs, decimals=decimals ) def probabilities_dict( self, qargs: None | list = None, decimals: None | int = None ) -> dict[str, float]: """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 (key) form. """ return self._get_probabilities_dict(outcome_bitstring=None, qargs=qargs, decimals=decimals) 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 auxiliary 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_probabilities( self, qubits: range, outcome: list[str], outcome_prob: float, probs: dict[str, float], outcome_bitstring: str = None, ): """Recursive helper function for calculating the probabilities Args: qubits (range): range of qubits outcome (list[str]): outcome being built outcome_prob (float): probability of the outcome probs (dict[str, float]): holds the outcomes and probability results outcome_bitstring (str): target outcome to measure which reduces measurements, None if not targeting a specific target """ qubit_for_branching: int = -1 ret: StabilizerState = self.copy() # Find outcomes for each qubit for i in range(len(qubits)): if outcome[i] == "X": # Retrieve the qubit for the current measurement qubit = qubits[(len(qubits) - i - 1)] # Determine if the probability is deterministic if not any(ret.clifford.stab_x[:, qubit]): single_qubit_outcome: np.int64 = ret._measure_and_update(qubit, 0) if outcome_bitstring is None or ( int(outcome_bitstring[i]) == single_qubit_outcome ): # No outcome_bitstring target, or using outcome_bitstring target and # the single_qubit_outcome equals the desired outcome_bitstring target value, # then use current outcome_prob value outcome[i] = str(single_qubit_outcome) else: # If the single_qubit_outcome does not equal the outcome_bitsring target # then we know that the probability will be 0 outcome[i] = str(outcome_bitstring[i]) outcome_prob = 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) if (outcome_bitstring is None) else [int(outcome_bitstring[qubit_for_branching])] ): new_outcome = outcome.copy() new_outcome[qubit_for_branching] = str(single_qubit_outcome) stab_cpy = ret.copy() stab_cpy._measure_and_update( qubits[(len(qubits) - qubit_for_branching - 1)], single_qubit_outcome ) stab_cpy._get_probabilities( qubits, new_outcome, (0.5 * outcome_prob), probs, outcome_bitstring ) def _get_probabilities_dict( self, outcome_bitstring: None | str = None, qargs: None | list = None, decimals: None | int = None, ) -> dict[str, float]: """Helper Function for calculating the subsystem measurement probability dictionary. When the targeted outcome_bitstring value is set, then only the single outcome_bitstring probability will be calculated. Args: outcome_bitstring (None or str): targeted outcome bitstring to perform a measurement calculation for, this will significantly reduce the number of calculation performed (Default: None) 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 (key) form. """ if qargs is None: qubits = range(self.clifford.num_qubits) else: qubits = qargs outcome = ["X"] * len(qubits) outcome_prob = 1.0 probs: dict[str, float] = {} # Probabilities dict to return with the measured values self._get_probabilities(qubits, outcome, outcome_prob, probs, outcome_bitstring) if decimals is not None: for key, value in probs.items(): probs[key] = round(value, decimals) return probs
qiskit/qiskit/quantum_info/states/stabilizerstate.py/0
{ "file_path": "qiskit/qiskit/quantum_info/states/stabilizerstate.py", "repo_id": "qiskit", "token_count": 12807 }
208
# 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. """Model for schema-conformant Results.""" import copy import warnings from qiskit.circuit.quantumcircuit import QuantumCircuit from qiskit.pulse.schedule import Schedule from qiskit.exceptions import QiskitError from qiskit.quantum_info.states import statevector from qiskit.result.models import ExperimentResult from qiskit.result import postprocess from qiskit.result.counts import Counts from qiskit.qobj.utils import MeasLevel from qiskit.qobj import QobjHeader class Result: """Model for Results. Attributes: backend_name (str): backend name. backend_version (str): backend version, in the form X.Y.Z. qobj_id (str): user-generated Qobj id. job_id (str): unique execution id from the backend. success (bool): True if complete input qobj executed correctly. (Implies each experiment success) results (list[ExperimentResult]): corresponding results for array of experiments of the input qobj """ _metadata = {} def __init__( self, backend_name, backend_version, qobj_id, job_id, success, results, date=None, status=None, header=None, **kwargs, ): self._metadata = {} self.backend_name = backend_name self.backend_version = backend_version self.qobj_id = qobj_id self.job_id = job_id self.success = success self.results = results self.date = date self.status = status self.header = header self._metadata.update(kwargs) def __repr__(self): out = ( f"Result(backend_name='{self.backend_name}', backend_version='{self.backend_version}'," f" qobj_id='{self.qobj_id}', job_id='{self.job_id}', success={self.success}," f" results={self.results}" ) out += f", date={self.date}, status={self.status}, header={self.header}" for key, value in self._metadata.items(): if isinstance(value, str): value_str = f"'{value}'" else: value_str = repr(value) out += f", {key}={value_str}" out += ")" return out def to_dict(self): """Return a dictionary format representation of the Result Returns: dict: The dictionary form of the Result """ out_dict = { "backend_name": self.backend_name, "backend_version": self.backend_version, "date": self.date, "header": None if self.header is None else self.header.to_dict(), "qobj_id": self.qobj_id, "job_id": self.job_id, "status": self.status, "success": self.success, "results": [x.to_dict() for x in self.results], } out_dict.update(self._metadata) return out_dict def __getattr__(self, name): try: return self._metadata[name] except KeyError as ex: raise AttributeError(f"Attribute {name} is not defined") from ex @classmethod def from_dict(cls, data): """Create a new ExperimentResultData object from a dictionary. Args: data (dict): A dictionary representing the Result to create. It will be in the same format as output by :meth:`to_dict`. Returns: Result: The ``Result`` object from the input dictionary. """ in_data = copy.copy(data) in_data["results"] = [ExperimentResult.from_dict(x) for x in in_data.pop("results")] if in_data.get("header") is not None: with warnings.catch_warnings(): warnings.filterwarnings("ignore", category=DeprecationWarning, module="qiskit") in_data["header"] = QobjHeader.from_dict(in_data.pop("header")) return cls(**in_data) def data(self, experiment=None): """Get the raw data for an experiment. Note this data will be a single classical and quantum register and in a format required by the results schema. We recommend that most users use the get_xxx method, and the data will be post-processed for the data type. Args: experiment (str or QuantumCircuit or Schedule or int or None): the index of the experiment. Several types are accepted for convenience:: * str: the name of the experiment. * QuantumCircuit: the name of the circuit instance will be used. * Schedule: the name of the schedule instance will be used. * int: the position of the experiment. * None: if there is only one experiment, returns it. Returns: dict: A dictionary of results data for an experiment. The data depends on the backend it ran on and the settings of `meas_level`, `meas_return` and `memory`. OpenQASM backends return a dictionary of dictionary with the key 'counts' and with the counts, with the second dictionary keys containing a string in hex format (``0x123``) and values equal to the number of times this outcome was measured. Statevector backends return a dictionary with key 'statevector' and values being a list[list[complex components]] list of 2^num_qubits complex amplitudes. Where each complex number is represented as a 2 entry list for each component. For example, a list of [0.5+1j, 0-1j] would be represented as [[0.5, 1], [0, -1]]. Unitary backends return a dictionary with key 'unitary' and values being a list[list[list[complex components]]] list of 2^num_qubits x 2^num_qubits complex amplitudes in a two entry list for each component. For example if the amplitude is [[0.5+0j, 0-1j], ...] the value returned will be [[[0.5, 0], [0, -1]], ...]. The simulator backends also have an optional key 'snapshots' which returns a dict of snapshots specified by the simulator backend. The value is of the form dict[slot: dict[str: array]] where the keys are the requested snapshot slots, and the values are a dictionary of the snapshots. Raises: QiskitError: if data for the experiment could not be retrieved. """ try: return self._get_experiment(experiment).data.to_dict() except (KeyError, TypeError) as ex: raise QiskitError(f'No data for experiment "{repr(experiment)}"') from ex def get_memory(self, experiment=None): """Get the sequence of memory states (readouts) for each shot The data from the experiment is a list of format ['00000', '01000', '10100', '10100', '11101', '11100', '00101', ..., '01010'] Args: experiment (str or QuantumCircuit or Schedule or int or None): the index of the experiment, as specified by ``data()``. Returns: List[str] or np.ndarray: Either the list of each outcome, formatted according to registers in circuit or a complex numpy np.ndarray with shape: ============ ============= ===== `meas_level` `meas_return` shape ============ ============= ===== 0 `single` np.ndarray[shots, memory_slots, memory_slot_size] 0 `avg` np.ndarray[memory_slots, memory_slot_size] 1 `single` np.ndarray[shots, memory_slots] 1 `avg` np.ndarray[memory_slots] 2 `memory=True` list ============ ============= ===== Raises: QiskitError: if there is no memory data for the circuit. """ exp_result = self._get_experiment(experiment) try: try: # header is not available header = exp_result.header.to_dict() except (AttributeError, QiskitError): header = None meas_level = exp_result.meas_level memory = self.data(experiment)["memory"] if meas_level == MeasLevel.CLASSIFIED: return postprocess.format_level_2_memory(memory, header) elif meas_level == MeasLevel.KERNELED: return postprocess.format_level_1_memory(memory) elif meas_level == MeasLevel.RAW: return postprocess.format_level_0_memory(memory) else: raise QiskitError(f"Measurement level {meas_level} is not supported") except KeyError as ex: raise QiskitError( f'No memory for experiment "{repr(experiment)}". ' "Please verify that you either ran a measurement level 2 job " 'with the memory flag set, eg., "memory=True", ' "or a measurement level 0/1 job." ) from ex def get_counts(self, experiment=None): """Get the histogram data of an experiment. Args: experiment (str or QuantumCircuit or Schedule or int or None): the index of the experiment, as specified by ``data([experiment])``. Returns: dict[str, int] or list[dict[str, int]]: a dictionary or a list of dictionaries. A dictionary has the counts for each qubit with the keys containing a string in binary format and separated according to the registers in circuit (e.g. ``0100 1110``). The string is little-endian (cr[0] on the right hand side). Raises: QiskitError: if there are no counts for the experiment. """ if experiment is None: exp_keys = range(len(self.results)) else: exp_keys = [experiment] dict_list = [] for key in exp_keys: exp = self._get_experiment(key) try: header = exp.header.to_dict() except (AttributeError, QiskitError): # header is not available header = None if "counts" in self.data(key).keys(): if header: counts_header = { k: v for k, v in header.items() if k in {"time_taken", "creg_sizes", "memory_slots"} } else: counts_header = {} dict_list.append(Counts(self.data(key)["counts"], **counts_header)) elif "statevector" in self.data(key).keys(): vec = postprocess.format_statevector(self.data(key)["statevector"]) dict_list.append(statevector.Statevector(vec).probabilities_dict(decimals=15)) else: raise QiskitError(f'No counts for experiment "{repr(key)}"') # Return first item of dict_list if size is 1 if len(dict_list) == 1: return dict_list[0] else: return dict_list def get_statevector(self, experiment=None, decimals=None): """Get the final statevector of an experiment. Args: experiment (str or QuantumCircuit or Schedule or int or None): the index of the experiment, as specified by ``data()``. decimals (int): the number of decimals in the statevector. If None, does not round. Returns: list[complex]: list of 2^num_qubits complex amplitudes. Raises: QiskitError: if there is no statevector for the experiment. """ try: return postprocess.format_statevector( self.data(experiment)["statevector"], decimals=decimals ) except KeyError as ex: raise QiskitError(f'No statevector for experiment "{repr(experiment)}"') from ex def get_unitary(self, experiment=None, decimals=None): """Get the final unitary of an experiment. Args: experiment (str or QuantumCircuit or Schedule or int or None): the index of the experiment, as specified by ``data()``. decimals (int): the number of decimals in the unitary. If None, does not round. Returns: list[list[complex]]: list of 2^num_qubits x 2^num_qubits complex amplitudes. Raises: QiskitError: if there is no unitary for the experiment. """ try: return postprocess.format_unitary(self.data(experiment)["unitary"], decimals=decimals) except KeyError as ex: raise QiskitError(f'No unitary for experiment "{repr(experiment)}"') from ex def _get_experiment(self, key=None): """Return a single experiment result from a given key. Args: key (str or QuantumCircuit or Schedule or int or None): the index of the experiment, as specified by ``data()``. Returns: ExperimentResult: the results for an experiment. Raises: QiskitError: if there is no data for the experiment, or an unhandled error occurred while fetching the data. """ # Automatically return the first result if no key was provided. if key is None: if len(self.results) != 1: raise QiskitError( "You have to select a circuit or schedule when there is more than one available" ) key = 0 # Key is a QuantumCircuit/Schedule or str: retrieve result by name. if isinstance(key, (QuantumCircuit, Schedule)): key = key.name # Key is an integer: return result by index. if isinstance(key, int): try: exp = self.results[key] except IndexError as ex: raise QiskitError(f'Result for experiment "{key}" could not be found.') from ex else: # Look into `result[x].header.name` for the names. exp = [ result for result in self.results if getattr(getattr(result, "header", None), "name", "") == key ] if len(exp) == 0: raise QiskitError(f'Data for experiment "{key}" could not be found.') if len(exp) == 1: exp = exp[0] else: warnings.warn( f'Result object contained multiple results matching name "{key}", ' "only first match will be returned. Use an integer index to " "retrieve results for all entries." ) exp = exp[0] # Check that the retrieved experiment was successful if getattr(exp, "success", False): return exp # If unsuccessful check experiment and result status and raise exception result_status = getattr(self, "status", "Result was not successful") exp_status = getattr(exp, "status", "Experiment was not successful") raise QiskitError(result_status, ", ", exp_status)
qiskit/qiskit/result/result.py/0
{ "file_path": "qiskit/qiskit/result/result.py", "repo_id": "qiskit", "token_count": 7022 }
209
# This code is part of Qiskit. # # (C) Copyright IBM 2023, 2024. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Circuit synthesis for the Clifford class into layers. """ # pylint: disable=invalid-name from __future__ import annotations from collections.abc import Callable import numpy as np from qiskit.circuit import QuantumCircuit from qiskit.exceptions import QiskitError from qiskit.quantum_info import Clifford # pylint: disable=cyclic-import from qiskit.quantum_info.operators.symplectic.clifford_circuits import ( _append_h, _append_s, _append_cz, ) from qiskit.synthesis.linear import ( synth_cnot_count_full_pmh, synth_cnot_depth_line_kms, ) from qiskit.synthesis.linear_phase import synth_cz_depth_line_mr, synth_cx_cz_depth_line_my from qiskit.synthesis.linear.linear_matrix_utils import ( calc_inverse_matrix, compute_rank, gauss_elimination, gauss_elimination_with_perm, binary_matmul, ) def _default_cx_synth_func(mat): """ Construct the layer of CX gates from a boolean invertible matrix mat. """ CX_circ = synth_cnot_count_full_pmh(mat) CX_circ.name = "CX" return CX_circ def _default_cz_synth_func(symmetric_mat): """ Construct the layer of CZ gates from a symmetric matrix. """ nq = symmetric_mat.shape[0] qc = QuantumCircuit(nq, name="CZ") for j in range(nq): for i in range(0, j): if symmetric_mat[i][j]: qc.cz(i, j) return qc def synth_clifford_layers( cliff: Clifford, cx_synth_func: Callable[[np.ndarray], QuantumCircuit] = _default_cx_synth_func, cz_synth_func: Callable[[np.ndarray], QuantumCircuit] = _default_cz_synth_func, cx_cz_synth_func: Callable[[np.ndarray], QuantumCircuit] | None = None, cz_func_reverse_qubits: bool = False, validate: bool = False, ) -> QuantumCircuit: """Synthesis of a :class:`.Clifford` into layers, it provides a similar decomposition to the synthesis described in Lemma 8 of Bravyi and Maslov [1]. For example, a 5-qubit Clifford circuit is decomposed into the following layers: .. parsed-literal:: β”Œβ”€β”€β”€β”€β”€β”β”Œβ”€β”€β”€β”€β”€β”β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”β”Œβ”€β”€β”€β”€β”€β”β”Œβ”€β”€β”€β”€β”€β”β”Œβ”€β”€β”€β”€β”€β”β”Œβ”€β”€β”€β”€β”€β”β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β” q_0: ─0 β”œβ”€0 β”œβ”€0 β”œβ”€0 β”œβ”€0 β”œβ”€0 β”œβ”€0 β”œβ”€0 β”œ β”‚ β”‚β”‚ β”‚β”‚ β”‚β”‚ β”‚β”‚ β”‚β”‚ β”‚β”‚ β”‚β”‚ β”‚ q_1: ─1 β”œβ”€1 β”œβ”€1 β”œβ”€1 β”œβ”€1 β”œβ”€1 β”œβ”€1 β”œβ”€1 β”œ β”‚ β”‚β”‚ β”‚β”‚ β”‚β”‚ β”‚β”‚ β”‚β”‚ β”‚β”‚ β”‚β”‚ β”‚ q_2: ─2 S2 β”œβ”€2 CZ β”œβ”€2 CX_dg β”œβ”€2 H2 β”œβ”€2 S1 β”œβ”€2 CZ β”œβ”€2 H1 β”œβ”€2 Pauli β”œ β”‚ β”‚β”‚ β”‚β”‚ β”‚β”‚ β”‚β”‚ β”‚β”‚ β”‚β”‚ β”‚β”‚ β”‚ q_3: ─3 β”œβ”€3 β”œβ”€3 β”œβ”€3 β”œβ”€3 β”œβ”€3 β”œβ”€3 β”œβ”€3 β”œ β”‚ β”‚β”‚ β”‚β”‚ β”‚β”‚ β”‚β”‚ β”‚β”‚ β”‚β”‚ β”‚β”‚ β”‚ q_4: ─4 β”œβ”€4 β”œβ”€4 β”œβ”€4 β”œβ”€4 β”œβ”€4 β”œβ”€4 β”œβ”€4 β”œ β””β”€β”€β”€β”€β”€β”˜β””β”€β”€β”€β”€β”€β”˜β””β”€β”€β”€β”€β”€β”€β”€β”€β”˜β””β”€β”€β”€β”€β”€β”˜β””β”€β”€β”€β”€β”€β”˜β””β”€β”€β”€β”€β”€β”˜β””β”€β”€β”€β”€β”€β”˜β””β”€β”€β”€β”€β”€β”€β”€β”€β”˜ This decomposition is for the default ``cz_synth_func`` and ``cx_synth_func`` functions, with other functions one may see slightly different decomposition. Args: cliff: A Clifford operator. cx_synth_func: A function to decompose the CX sub-circuit. It gets as input a boolean invertible matrix, and outputs a :class:`.QuantumCircuit`. cz_synth_func: A function to decompose the CZ sub-circuit. It gets as input a boolean symmetric matrix, and outputs a :class:`.QuantumCircuit`. cx_cz_synth_func (Callable): optional, a function to decompose both sub-circuits CZ and CX. validate (Boolean): if True, validates the synthesis process. cz_func_reverse_qubits (Boolean): True only if ``cz_synth_func`` is :func:`.synth_cz_depth_line_mr`, since this function returns a circuit that reverts the order of qubits. Returns: 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>`_ """ num_qubits = cliff.num_qubits if cz_func_reverse_qubits: cliff0 = _reverse_clifford(cliff) else: cliff0 = cliff qubit_list = list(range(num_qubits)) layeredCircuit = QuantumCircuit(num_qubits) H1_circ, cliff1 = _create_graph_state(cliff0, validate=validate) H2_circ, CZ1_circ, S1_circ, cliff2 = _decompose_graph_state( cliff1, validate=validate, cz_synth_func=cz_synth_func ) S2_circ, CZ2_circ, CX_circ = _decompose_hadamard_free( cliff2.adjoint(), validate=validate, cz_synth_func=cz_synth_func, cx_synth_func=cx_synth_func, cx_cz_synth_func=cx_cz_synth_func, cz_func_reverse_qubits=cz_func_reverse_qubits, ) layeredCircuit.append(S2_circ, qubit_list, copy=False) if cx_cz_synth_func is None: layeredCircuit.append(CZ2_circ, qubit_list, copy=False) CXinv = CX_circ.copy().inverse() layeredCircuit.append(CXinv, qubit_list, copy=False) else: # note that CZ2_circ is None and built into the CX_circ when # cx_cz_synth_func is not None layeredCircuit.append(CX_circ, qubit_list, copy=False) layeredCircuit.append(H2_circ, qubit_list, copy=False) layeredCircuit.append(S1_circ, qubit_list, copy=False) layeredCircuit.append(CZ1_circ, qubit_list, copy=False) if cz_func_reverse_qubits: H1_circ = H1_circ.reverse_bits() layeredCircuit.append(H1_circ, qubit_list, copy=False) # Add Pauli layer to fix the Clifford phase signs clifford_target = Clifford(layeredCircuit) pauli_circ = _calc_pauli_diff(cliff, clifford_target) layeredCircuit.append(pauli_circ, qubit_list, copy=False) return layeredCircuit def _reverse_clifford(cliff): """Reverse qubit order of a Clifford cliff""" cliff_cpy = cliff.copy() cliff_cpy.stab_z = np.flip(cliff.stab_z, axis=1) cliff_cpy.destab_z = np.flip(cliff.destab_z, axis=1) cliff_cpy.stab_x = np.flip(cliff.stab_x, axis=1) cliff_cpy.destab_x = np.flip(cliff.destab_x, axis=1) return cliff_cpy def _create_graph_state(cliff, validate=False): """Given a Clifford cliff (denoted by U) that induces a stabilizer state U |0>, apply a layer H1 of Hadamard gates to a subset of the qubits to make H1 U |0> into a graph state, namely to make cliff.stab_x matrix have full rank. Returns the QuantumCircuit H1_circ that includes the Hadamard gates and the updated Clifford that induces the graph state. The algorithm is based on Lemma 6 in [2]. Args: cliff (Clifford): a Clifford operator. validate (Boolean): if True, validates the synthesis process. Returns: H1_circ: a circuit containing a layer of Hadamard gates. cliffh: cliffh.stab_x has full rank. Raises: QiskitError: if there are errors in the Gauss elimination process. References: 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>`_ """ num_qubits = cliff.num_qubits rank = compute_rank(np.asarray(cliff.stab_x, dtype=bool)) H1_circ = QuantumCircuit(num_qubits, name="H1") cliffh = cliff.copy() if rank < num_qubits: stab = cliff.stab[:, :-1] stab = stab.astype(bool, copy=True) gauss_elimination(stab, num_qubits) Cmat = stab[rank:num_qubits, num_qubits:] Cmat = np.transpose(Cmat) perm = gauss_elimination_with_perm(Cmat) perm = perm[0 : num_qubits - rank] # validate that the output matrix has the same rank if validate: if compute_rank(Cmat) != num_qubits - rank: raise QiskitError("The matrix Cmat after Gauss elimination has wrong rank.") if compute_rank(stab[:, 0:num_qubits]) != rank: raise QiskitError("The matrix after Gauss elimination has wrong rank.") # validate that we have a num_qubits - rank zero rows for i in range(rank, num_qubits): if stab[i, 0:num_qubits].any(): raise QiskitError( "After Gauss elimination, the final num_qubits - rank rows" "contain non-zero elements" ) for qubit in perm: H1_circ.h(qubit) _append_h(cliffh, qubit) # validate that a layer of Hadamard gates and then appending cliff, provides a graph state. if validate: stabh = (cliffh.stab_x).astype(bool, copy=False) if compute_rank(stabh) != num_qubits: raise QiskitError("The state is not a graph state.") return H1_circ, cliffh def _decompose_graph_state(cliff, validate, cz_synth_func): """Assumes that a stabilizer state of the Clifford cliff (denoted by U) corresponds to a graph state. Decompose it into the layers S1 - CZ1 - H2, such that: S1 CZ1 H2 |0> = U |0>, where S1_circ is a circuit that can contain only S gates, CZ1_circ is a circuit that can contain only CZ gates, and H2_circ is a circuit that can contain H gates on all qubits. Args: cliff (Clifford): a Clifford operator corresponding to a graph state, cliff.stab_x has full rank. validate (Boolean): if True, validates the synthesis process. cz_synth_func (Callable): a function to decompose the CZ sub-circuit. Returns: S1_circ: a circuit that can contain only S gates. CZ1_circ: a circuit that can contain only CZ gates. H2_circ: a circuit containing a layer of Hadamard gates. cliff_cpy: a Hadamard-free Clifford. Raises: QiskitError: if cliff does not induce a graph state. """ num_qubits = cliff.num_qubits rank = compute_rank(np.asarray(cliff.stab_x, dtype=bool)) cliff_cpy = cliff.copy() if rank < num_qubits: raise QiskitError("The stabilizer state is not a graph state.") S1_circ = QuantumCircuit(num_qubits, name="S1") H2_circ = QuantumCircuit(num_qubits, name="H2") stabx = cliff.stab_x stabz = cliff.stab_z stabx_inv = calc_inverse_matrix(stabx, validate) stabz_update = binary_matmul(stabx_inv, stabz) # Assert that stabz_update is a symmetric matrix. if validate: if (stabz_update != stabz_update.T).any(): raise QiskitError( "The multiplication of stabx_inv and stab_z is not a symmetric matrix." ) CZ1_circ = cz_synth_func(stabz_update) for j in range(num_qubits): for i in range(0, j): if stabz_update[i][j]: _append_cz(cliff_cpy, i, j) for i in range(0, num_qubits): if stabz_update[i][i]: S1_circ.s(i) _append_s(cliff_cpy, i) for qubit in range(num_qubits): H2_circ.h(qubit) _append_h(cliff_cpy, qubit) return H2_circ, CZ1_circ, S1_circ, cliff_cpy def _decompose_hadamard_free( cliff, validate, cz_synth_func, cx_synth_func, cx_cz_synth_func, cz_func_reverse_qubits ): """Assumes that the Clifford cliff is Hadamard free. Decompose it into the layers S2 - CZ2 - CX, where S2_circ is a circuit that can contain only S gates, CZ2_circ is a circuit that can contain only CZ gates, and CX_circ is a circuit that can contain CX gates. Args: cliff (Clifford): a Hadamard-free clifford operator. validate (Boolean): if True, validates the synthesis process. cz_synth_func (Callable): a function to decompose the CZ sub-circuit. cx_synth_func (Callable): a function to decompose the CX sub-circuit. cx_cz_synth_func (Callable): optional, a function to decompose both sub-circuits CZ and CX. cz_func_reverse_qubits (Boolean): True only if cz_synth_func is synth_cz_depth_line_mr. Returns: S2_circ: a circuit that can contain only S gates. CZ2_circ: a circuit that can contain only CZ gates. CX_circ: a circuit that can contain only CX gates. Raises: QiskitError: if cliff is not Hadamard free. """ num_qubits = cliff.num_qubits destabx = cliff.destab_x destabz = cliff.destab_z stabx = cliff.stab_x if not (stabx == np.zeros((num_qubits, num_qubits))).all(): raise QiskitError("The given Clifford is not Hadamard-free.") destabz_update = binary_matmul(calc_inverse_matrix(destabx), destabz) # Assert that destabz_update is a symmetric matrix. if validate: if (destabz_update != destabz_update.T).any(): raise QiskitError( "The multiplication of the inverse of destabx and" "destabz is not a symmetric matrix." ) S2_circ = QuantumCircuit(num_qubits, name="S2") for i in range(0, num_qubits): if destabz_update[i][i]: S2_circ.s(i) if cx_cz_synth_func is not None: # The cx_cz_synth_func takes as input Mx/Mz representing a CX/CZ circuit # and returns the circuit -CZ-CX- implementing them both for i in range(num_qubits): destabz_update[i][i] = 0 mat_z = destabz_update mat_x = calc_inverse_matrix(destabx.transpose()) CXCZ_circ = cx_cz_synth_func(mat_x, mat_z) return S2_circ, QuantumCircuit(num_qubits), CXCZ_circ CZ2_circ = cz_synth_func(destabz_update) mat = destabx.transpose() if cz_func_reverse_qubits: mat = np.flip(mat, axis=0) CX_circ = cx_synth_func(mat) return S2_circ, CZ2_circ, CX_circ def _calc_pauli_diff(cliff, cliff_target): """Given two Cliffords that differ by a Pauli, we find this Pauli.""" num_qubits = cliff.num_qubits if cliff.num_qubits != cliff_target.num_qubits: raise QiskitError("num_qubits is not the same for the original clifford and the target.") # Compute the phase difference between the two Cliffords phase = [cliff.phase[k] ^ cliff_target.phase[k] for k in range(2 * num_qubits)] phase = np.array(phase, dtype=int) # compute inverse of our symplectic matrix A = cliff.symplectic_matrix Ainv = calc_inverse_matrix(A) # By carefully writing how X, Y, Z gates affect each qubit, all we need to compute # is A^{-1} * (phase) C = np.matmul(Ainv, phase) % 2 # Create the Pauli pauli_circ = QuantumCircuit(num_qubits, name="Pauli") for k in range(num_qubits): destab = C[k] stab = C[k + num_qubits] if stab and destab: pauli_circ.y(k) elif stab: pauli_circ.x(k) elif destab: pauli_circ.z(k) return pauli_circ def synth_clifford_depth_lnn(cliff): """Synthesis of a :class:`.Clifford` into layers for linear-nearest neighbor connectivity. The depth of the synthesized n-qubit circuit is bounded by :math:`7n+2`, which is not optimal. It should be replaced by a better algorithm that provides depth bounded by :math:`7n-4` [3]. Args: cliff (Clifford): a Clifford operator. Returns: 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. Dmitri Maslov, Martin Roetteler, *Shorter stabilizer circuits via Bruhat decomposition and quantum circuit transformations*, `arXiv:1705.09176 <https://arxiv.org/abs/1705.09176>`_. 3. Dmitri Maslov, Willers Yang, *CNOT circuits need little help to implement arbitrary Hadamard-free Clifford transformations they generate*, `arXiv:2210.16195 <https://arxiv.org/abs/2210.16195>`_. """ circ = synth_clifford_layers( cliff, cx_synth_func=synth_cnot_depth_line_kms, cz_synth_func=synth_cz_depth_line_mr, cx_cz_synth_func=synth_cx_cz_depth_line_my, cz_func_reverse_qubits=True, ) return circ
qiskit/qiskit/synthesis/clifford/clifford_decompose_layers.py/0
{ "file_path": "qiskit/qiskit/synthesis/clifford/clifford_decompose_layers.py", "repo_id": "qiskit", "token_count": 7451 }
210
# 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. """The Suzuki-Trotter product formula.""" from __future__ import annotations import inspect from collections.abc import Callable import numpy as np from qiskit.circuit.quantumcircuit import QuantumCircuit from qiskit.quantum_info.operators import SparsePauliOp, Pauli from qiskit.utils.deprecation import deprecate_arg from .product_formula import ProductFormula class SuzukiTrotter(ProductFormula): r"""The (higher order) Suzuki-Trotter product formula. The Suzuki-Trotter formulas improve the error of the Lie-Trotter approximation. For example, the second order decomposition is .. math:: e^{A + B} \approx e^{B/2} e^{A} e^{B/2}. Higher order decompositions are based on recursions, see Ref. [1] for more details. In this implementation, the operators are provided as sum terms of a Pauli operator. For example, in the second order Suzuki-Trotter decomposition we approximate .. math:: e^{-it(XX + ZZ)} = e^{-it/2 ZZ}e^{-it XX}e^{-it/2 ZZ} + \mathcal{O}(t^3). References: [1]: D. Berry, G. Ahokas, R. Cleve and B. Sanders, "Efficient quantum algorithms for simulating sparse Hamiltonians" (2006). `arXiv:quant-ph/0508139 <https://arxiv.org/abs/quant-ph/0508139>`_ [2]: N. Hatano and M. Suzuki, "Finding Exponential Product Formulas of Higher Orders" (2005). `arXiv:math-ph/0506007 <https://arxiv.org/pdf/math-ph/0506007.pdf>`_ """ @deprecate_arg( name="atomic_evolution", since="1.2", predicate=lambda callable: callable is not None and len(inspect.signature(callable).parameters) == 2, deprecation_description=( "The 'Callable[[Pauli | SparsePauliOp, float], QuantumCircuit]' signature of the " "'atomic_evolution' argument" ), additional_msg=( "Instead you should update your 'atomic_evolution' function to be of the following " "type: 'Callable[[QuantumCircuit, Pauli | SparsePauliOp, float], None]'." ), pending=True, ) def __init__( self, order: int = 2, reps: int = 1, insert_barriers: bool = False, cx_structure: str = "chain", atomic_evolution: ( Callable[[Pauli | SparsePauliOp, float], QuantumCircuit] | Callable[[QuantumCircuit, Pauli | SparsePauliOp, float], None] | None ) = None, wrap: bool = False, ) -> None: """ Args: order: The order of the product formula. reps: The number of time steps. insert_barriers: Whether to insert barriers between the atomic evolutions. cx_structure: How to arrange the CX gates for the Pauli evolutions, can be ``"chain"``, where next neighbor connections are used, or ``"fountain"``, where all qubits are connected to one. This only takes effect when ``atomic_evolution is None``. atomic_evolution: A function to apply the evolution of a single :class:`.Pauli`, or :class:`.SparsePauliOp` of only commuting terms, to a circuit. The function takes in three arguments: the circuit to append the evolution to, the Pauli operator to evolve, and the evolution time. By default, a single Pauli evolution is decomposed into a chain of ``CX`` gates and a single ``RZ`` gate. Alternatively, the function can also take Pauli operator and evolution time as inputs and returns the circuit that will be appended to the overall circuit being built. wrap: Whether to wrap the atomic evolutions into custom gate objects. This only takes effect when ``atomic_evolution is None``. Raises: ValueError: If order is not even """ if order % 2 == 1: raise ValueError( "Suzuki product formulae are symmetric and therefore only defined " "for even orders." ) super().__init__(order, reps, insert_barriers, cx_structure, atomic_evolution, wrap) def synthesize(self, evolution): # get operators and time to evolve operators = evolution.operator time = evolution.time if not isinstance(operators, list): pauli_list = [(Pauli(op), np.real(coeff)) for op, coeff in operators.to_list()] else: pauli_list = [(op, 1) for op in operators] ops_to_evolve = self._recurse(self.order, time / self.reps, pauli_list) # construct the evolution circuit single_rep = QuantumCircuit(operators[0].num_qubits) for i, (op, coeff) in enumerate(ops_to_evolve): self.atomic_evolution(single_rep, op, coeff) if self.insert_barriers and i != len(ops_to_evolve) - 1: single_rep.barrier() return single_rep.repeat(self.reps, insert_barriers=self.insert_barriers).decompose() @staticmethod def _recurse(order, time, pauli_list): if order == 1: return pauli_list elif order == 2: halves = [(op, coeff * time / 2) for op, coeff in pauli_list[:-1]] full = [(pauli_list[-1][0], time * pauli_list[-1][1])] return halves + full + list(reversed(halves)) else: reduction = 1 / (4 - 4 ** (1 / (order - 1))) outer = 2 * SuzukiTrotter._recurse( order - 2, time=reduction * time, pauli_list=pauli_list ) inner = SuzukiTrotter._recurse( order - 2, time=(1 - 4 * reduction) * time, pauli_list=pauli_list ) return outer + inner + outer
qiskit/qiskit/synthesis/evolution/suzuki_trotter.py/0
{ "file_path": "qiskit/qiskit/synthesis/evolution/suzuki_trotter.py", "repo_id": "qiskit", "token_count": 2582 }
211
# 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. """Depth-efficient synthesis algorithm for Permutation gates.""" from __future__ import annotations import numpy as np from qiskit.circuit.quantumcircuit import QuantumCircuit from qiskit._accelerate.synthesis.permutation import _synth_permutation_depth_lnn_kms def synth_permutation_depth_lnn_kms(pattern: list[int] | np.ndarray[int]) -> QuantumCircuit: """Synthesize a permutation circuit for a linear nearest-neighbor architecture using the Kutin, Moulton, Smithline method. This is the permutation synthesis algorithm from [1], section 6. It synthesizes any permutation of n qubits over linear nearest-neighbor architecture using SWAP gates with depth at most :math:`n` and size at most :math:`n(n-1)/2` (where both depth and size are measured with respect to SWAPs). Args: pattern: Permutation pattern, describing which qubits occupy the positions 0, 1, 2, etc. after applying the permutation. That is, ``pattern[k] = m`` when the permutation maps qubit ``m`` to position ``k``. As an example, the pattern ``[2, 4, 3, 0, 1]`` means that qubit ``2`` goes to position ``0``, qubit ``4`` goes to position ``1``, etc. Returns: The synthesized quantum circuit. References: 1. Samuel A. Kutin, David Petrie Moulton and Lawren M. Smithline. *Computation at a distance.*, `arXiv:quant-ph/0701194v1 <https://arxiv.org/abs/quant-ph/0701194>`_ """ # In Qiskit, the permutation pattern [2, 4, 3, 0, 1] means that # the permutation that maps qubit 2 to position 0, 4 to 1, 3 to 2, 0 to 3, and 1 to 4. # In the permutation synthesis code below the notation is opposite: # [2, 4, 3, 0, 1] means that 0 maps to 2, 1 to 3, 2 to 3, 3 to 0, and 4 to 1. # This is why we invert the pattern. return QuantumCircuit._from_circuit_data(_synth_permutation_depth_lnn_kms(pattern))
qiskit/qiskit/synthesis/permutation/permutation_lnn.py/0
{ "file_path": "qiskit/qiskit/synthesis/permutation/permutation_lnn.py", "repo_id": "qiskit", "token_count": 840 }
212
# 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 library of known embodiments of RXXGate in terms of other gates, for some generic or specific angles. TODO: discover these automatically from the gates' algebraic definition """ from __future__ import annotations import numpy as np from qiskit.circuit import QuantumCircuit, Parameter from qiskit.circuit.library.standard_gates import ( RXXGate, RZZGate, RZXGate, RYYGate, CRZGate, CRXGate, CRYGate, CPhaseGate, CZGate, CXGate, CYGate, CHGate, ECRGate, ) rxx_circuit = QuantumCircuit(2) theta = Parameter("ΞΈ") rxx_circuit.rxx(theta, 0, 1) rzz_circuit = QuantumCircuit(2) theta = Parameter("ΞΈ") rzz_circuit.h(0) rzz_circuit.h(1) rzz_circuit.rzz(theta, 0, 1) rzz_circuit.h(0) rzz_circuit.h(1) rzx_circuit = QuantumCircuit(2) rzx_circuit.h(0) rzx_circuit.rzx(theta, 0, 1) rzx_circuit.h(0) ryy_circuit = QuantumCircuit(2) ryy_circuit.s(0) ryy_circuit.s(1) ryy_circuit.ryy(theta, 0, 1) ryy_circuit.sdg(0) ryy_circuit.sdg(1) cphase_circuit = QuantumCircuit(2) cphase_circuit.h(0) cphase_circuit.h(1) cphase_circuit.cp(-2 * theta, 0, 1) cphase_circuit.rz(theta, 0) cphase_circuit.rz(theta, 1) cphase_circuit.h(0) cphase_circuit.h(1) cphase_circuit.global_phase += theta / 2 crz_circuit = QuantumCircuit(2) crz_circuit.h(0) crz_circuit.h(1) crz_circuit.crz(-2 * theta, 0, 1) crz_circuit.rz(theta, 1) crz_circuit.h(0) crz_circuit.h(1) crx_circuit = QuantumCircuit(2) crx_circuit.h(0) crx_circuit.crx(-2 * theta, 0, 1) crx_circuit.rx(theta, 1) crx_circuit.h(0) cry_circuit = QuantumCircuit(2) cry_circuit.h(0) cry_circuit.s(1) cry_circuit.cry(-2 * theta, 0, 1) cry_circuit.ry(theta, 1) cry_circuit.h(0) cry_circuit.sdg(1) cz_circuit = QuantumCircuit(2) cz_circuit.h(0) cz_circuit.h(1) cz_circuit.cz(0, 1) cz_circuit.s(0) cz_circuit.s(1) cz_circuit.h(0) cz_circuit.h(1) cz_circuit.global_phase -= np.pi / 4 cx_circuit = QuantumCircuit(2) cx_circuit.h(0) cx_circuit.cx(0, 1) cx_circuit.s(0) cx_circuit.sx(1) cx_circuit.h(0) cx_circuit.global_phase -= np.pi / 4 cy_circuit = QuantumCircuit(2) cy_circuit.h(0) cy_circuit.s(1) cy_circuit.cy(0, 1) cy_circuit.s(0) cy_circuit.sdg(1) cy_circuit.sx(1) cy_circuit.h(0) cy_circuit.global_phase -= np.pi / 4 ch_circuit = QuantumCircuit(2) ch_circuit.h(0) ch_circuit.tdg(1) ch_circuit.h(1) ch_circuit.sdg(1) ch_circuit.ch(0, 1) ch_circuit.s(0) ch_circuit.s(1) ch_circuit.h(1) ch_circuit.t(1) ch_circuit.sx(1) ch_circuit.h(0) ch_circuit.global_phase -= np.pi / 4 ecr_circuit = QuantumCircuit(2) ecr_circuit.h(0) ecr_circuit.s(0) ecr_circuit.x(0) ecr_circuit.x(1) ecr_circuit.ecr(0, 1) ecr_circuit.s(0) ecr_circuit.h(0) ecr_circuit.global_phase -= np.pi / 2 XXEmbodiments = { RXXGate: rxx_circuit, RYYGate: ryy_circuit, RZZGate: rzz_circuit, RZXGate: rzx_circuit, CRXGate: crx_circuit, CRYGate: cry_circuit, CRZGate: crz_circuit, CPhaseGate: cphase_circuit, CXGate: cx_circuit, CYGate: cy_circuit, CZGate: cz_circuit, CHGate: ch_circuit, ECRGate: ecr_circuit, }
qiskit/qiskit/synthesis/two_qubit/xx_decompose/embodiments.py/0
{ "file_path": "qiskit/qiskit/synthesis/two_qubit/xx_decompose/embodiments.py", "repo_id": "qiskit", "token_count": 1674 }
213
# 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. """ Layer classes for the fast gradient implementation. """ from __future__ import annotations from abc import abstractmethod, ABC from typing import Optional import numpy as np from .fast_grad_utils import ( bit_permutation_1q, reverse_bits, inverse_permutation, bit_permutation_2q, make_rz, make_ry, ) class LayerBase(ABC): """ Base class for any layer implementation. Each layer here is represented by a 2x2 or 4x4 gate matrix ``G`` (applied to 1 or 2 qubits respectively) interleaved with the identity ones: ``Layer = I kron I kron ... kron G kron ... kron I kron I`` """ @abstractmethod def set_from_matrix(self, mat: np.ndarray): """ Updates this layer from an external gate matrix. Args: mat: external gate matrix that initializes this layer's one. """ raise NotImplementedError() @abstractmethod def get_attr(self) -> tuple[np.ndarray, np.ndarray, np.ndarray]: """ Returns gate matrix, direct and inverse permutations. Returns: (1) gate matrix; (2) direct permutation; (3) inverse permutations. """ raise NotImplementedError() class Layer1Q(LayerBase): """ Layer represents a simple circuit where 1-qubit gate matrix (of size 2x2) interleaves with the identity ones. """ def __init__(self, num_qubits: int, k: int, g2x2: Optional[np.ndarray] = None): """ Args: num_qubits: number of qubits. k: index of the bit where gate is applied. g2x2: 2x2 matrix that makes up this layer along with identity ones, or None (should be set up later). """ super().__init__() # 2x2 gate matrix (1-qubit gate). self._gmat = np.full((2, 2), fill_value=0, dtype=np.complex128) if isinstance(g2x2, np.ndarray): np.copyto(self._gmat, g2x2) bit_flip = True dim = 2**num_qubits row_perm = reverse_bits( bit_permutation_1q(n=num_qubits, k=k), nbits=num_qubits, enable=bit_flip ) col_perm = reverse_bits(np.arange(dim, dtype=np.int64), nbits=num_qubits, enable=bit_flip) self._perm = np.full((dim,), fill_value=0, dtype=np.int64) self._perm[row_perm] = col_perm self._inv_perm = inverse_permutation(self._perm) def set_from_matrix(self, mat: np.ndarray): """See base class description.""" np.copyto(self._gmat, mat) def get_attr(self) -> tuple[np.ndarray, np.ndarray, np.ndarray]: """See base class description.""" return self._gmat, self._perm, self._inv_perm class Layer2Q(LayerBase): """ Layer represents a simple circuit where 2-qubit gate matrix (of size 4x4) interleaves with the identity ones. """ def __init__(self, num_qubits: int, j: int, k: int, g4x4: Optional[np.ndarray] = None): """ Args: num_qubits: number of qubits. j: index of the first (control) bit. k: index of the second (target) bit. g4x4: 4x4 matrix that makes up this layer along with identity ones, or None (should be set up later). """ super().__init__() # 4x4 gate matrix (2-qubit gate). self._gmat = np.full((4, 4), fill_value=0, dtype=np.complex128) if isinstance(g4x4, np.ndarray): np.copyto(self._gmat, g4x4) bit_flip = True dim = 2**num_qubits row_perm = reverse_bits( bit_permutation_2q(n=num_qubits, j=j, k=k), nbits=num_qubits, enable=bit_flip ) col_perm = reverse_bits(np.arange(dim, dtype=np.int64), nbits=num_qubits, enable=bit_flip) self._perm = np.full((dim,), fill_value=0, dtype=np.int64) self._perm[row_perm] = col_perm self._inv_perm = inverse_permutation(self._perm) def set_from_matrix(self, mat: np.ndarray): """See base class description.""" np.copyto(self._gmat, mat) def get_attr(self) -> tuple[np.ndarray, np.ndarray, np.ndarray]: """See base class description.""" return self._gmat, self._perm, self._inv_perm def init_layer1q_matrices(thetas: np.ndarray, dst: np.ndarray) -> np.ndarray: """ Initializes 4x4 matrices of 2-qubit gates defined in the paper. Args: thetas: depth x 4 matrix of gate parameters for every layer, where "depth" is the number of layers. dst: destination array of size depth x 4 x 4 that will receive gate matrices of each layer. Returns: Returns the "dst" array. """ n = thetas.shape[0] tmp = np.full((4, 2, 2), fill_value=0, dtype=np.complex128) for k in range(n): th = thetas[k] a = make_rz(th[0], out=tmp[0]) b = make_ry(th[1], out=tmp[1]) c = make_rz(th[2], out=tmp[2]) np.dot(np.dot(a, b, out=tmp[3]), c, out=dst[k]) return dst def init_layer1q_deriv_matrices(thetas: np.ndarray, dst: np.ndarray) -> np.ndarray: """ Initializes 4x4 derivative matrices of 2-qubit gates defined in the paper. Args: thetas: depth x 4 matrix of gate parameters for every layer, where "depth" is the number of layers. dst: destination array of size depth x 4 x 4 x 4 that will receive gate derivative matrices of each layer; there are 4 parameters per gate, hence, 4 derivative matrices per layer. Returns: Returns the "dst" array. """ n = thetas.shape[0] y = np.asarray([[0, -0.5], [0.5, 0]], dtype=np.complex128) z = np.asarray([[-0.5j, 0], [0, 0.5j]], dtype=np.complex128) tmp = np.full((5, 2, 2), fill_value=0, dtype=np.complex128) for k in range(n): th = thetas[k] a = make_rz(th[0], out=tmp[0]) b = make_ry(th[1], out=tmp[1]) c = make_rz(th[2], out=tmp[2]) za = np.dot(z, a, out=tmp[3]) np.dot(np.dot(za, b, out=tmp[4]), c, out=dst[k, 0]) yb = np.dot(y, b, out=tmp[3]) np.dot(a, np.dot(yb, c, out=tmp[4]), out=dst[k, 1]) zc = np.dot(z, c, out=tmp[3]) np.dot(a, np.dot(b, zc, out=tmp[4]), out=dst[k, 2]) return dst def init_layer2q_matrices(thetas: np.ndarray, dst: np.ndarray) -> np.ndarray: """ Initializes 4x4 matrices of 2-qubit gates defined in the paper. Args: thetas: depth x 4 matrix of gate parameters for every layer, where "depth" is the number of layers. dst: destination array of size depth x 4 x 4 that will receive gate matrices of each layer. Returns: Returns the "dst" array. """ depth = thetas.shape[0] for k in range(depth): th = thetas[k] cs0 = np.cos(0.5 * th[0]).item() sn0 = np.sin(0.5 * th[0]).item() ep1 = np.exp(0.5j * th[1]).item() en1 = np.exp(-0.5j * th[1]).item() cs2 = np.cos(0.5 * th[2]).item() sn2 = np.sin(0.5 * th[2]).item() cs3 = np.cos(0.5 * th[3]).item() sn3 = np.sin(0.5 * th[3]).item() ep1cs0 = ep1 * cs0 ep1sn0 = ep1 * sn0 en1cs0 = en1 * cs0 en1sn0 = en1 * sn0 sn2cs3 = sn2 * cs3 sn2sn3 = sn2 * sn3 cs2cs3 = cs2 * cs3 sn3cs2j = 1j * sn3 * cs2 sn2sn3j = 1j * sn2sn3 flat_dst = dst[k].ravel() flat_dst[:] = [ -(sn2sn3j - cs2cs3) * en1cs0, -(sn2cs3 + sn3cs2j) * en1cs0, (sn2cs3 + sn3cs2j) * en1sn0, (sn2sn3j - cs2cs3) * en1sn0, (sn2cs3 - sn3cs2j) * en1cs0, (sn2sn3j + cs2cs3) * en1cs0, -(sn2sn3j + cs2cs3) * en1sn0, (-sn2cs3 + sn3cs2j) * en1sn0, (-sn2sn3j + cs2cs3) * ep1sn0, -(sn2cs3 + sn3cs2j) * ep1sn0, -(sn2cs3 + sn3cs2j) * ep1cs0, (-sn2sn3j + cs2cs3) * ep1cs0, (sn2cs3 - sn3cs2j) * ep1sn0, (sn2sn3j + cs2cs3) * ep1sn0, (sn2sn3j + cs2cs3) * ep1cs0, (sn2cs3 - sn3cs2j) * ep1cs0, ] return dst def init_layer2q_deriv_matrices(thetas: np.ndarray, dst: np.ndarray) -> np.ndarray: """ Initializes 4 x 4 derivative matrices of 2-qubit gates defined in the paper. Args: thetas: depth x 4 matrix of gate parameters for every layer, where "depth" is the number of layers. dst: destination array of size depth x 4 x 4 x 4 that will receive gate derivative matrices of each layer; there are 4 parameters per gate, hence, 4 derivative matrices per layer. Returns: Returns the "dst" array. """ depth = thetas.shape[0] for k in range(depth): th = thetas[k] cs0 = np.cos(0.5 * th[0]).item() sn0 = np.sin(0.5 * th[0]).item() ep1 = np.exp(0.5j * th[1]).item() * 0.5 en1 = np.exp(-0.5j * th[1]).item() * 0.5 cs2 = np.cos(0.5 * th[2]).item() sn2 = np.sin(0.5 * th[2]).item() cs3 = np.cos(0.5 * th[3]).item() sn3 = np.sin(0.5 * th[3]).item() ep1cs0 = ep1 * cs0 ep1sn0 = ep1 * sn0 en1cs0 = en1 * cs0 en1sn0 = en1 * sn0 sn2cs3 = sn2 * cs3 sn2sn3 = sn2 * sn3 sn3cs2 = sn3 * cs2 cs2cs3 = cs2 * cs3 sn2cs3j = 1j * sn2cs3 sn2sn3j = 1j * sn2sn3 sn3cs2j = 1j * sn3cs2 cs2cs3j = 1j * cs2cs3 flat_dst = dst[k, 0].ravel() flat_dst[:] = [ (sn2sn3j - cs2cs3) * en1sn0, (sn2cs3 + sn3cs2j) * en1sn0, (sn2cs3 + sn3cs2j) * en1cs0, (sn2sn3j - cs2cs3) * en1cs0, (-sn2cs3 + sn3cs2j) * en1sn0, -(sn2sn3j + cs2cs3) * en1sn0, -(sn2sn3j + cs2cs3) * en1cs0, (-sn2cs3 + sn3cs2j) * en1cs0, (-sn2sn3j + cs2cs3) * ep1cs0, -(sn2cs3 + sn3cs2j) * ep1cs0, (sn2cs3 + sn3cs2j) * ep1sn0, (sn2sn3j - cs2cs3) * ep1sn0, (sn2cs3 - sn3cs2j) * ep1cs0, (sn2sn3j + cs2cs3) * ep1cs0, -(sn2sn3j + cs2cs3) * ep1sn0, (-sn2cs3 + sn3cs2j) * ep1sn0, ] flat_dst = dst[k, 1].ravel() flat_dst[:] = [ -(sn2sn3 + cs2cs3j) * en1cs0, (sn2cs3j - sn3cs2) * en1cs0, -(sn2cs3j - sn3cs2) * en1sn0, (sn2sn3 + cs2cs3j) * en1sn0, -(sn2cs3j + sn3cs2) * en1cs0, (sn2sn3 - cs2cs3j) * en1cs0, (-sn2sn3 + cs2cs3j) * en1sn0, (sn2cs3j + sn3cs2) * en1sn0, (sn2sn3 + cs2cs3j) * ep1sn0, (-sn2cs3j + sn3cs2) * ep1sn0, (-sn2cs3j + sn3cs2) * ep1cs0, (sn2sn3 + cs2cs3j) * ep1cs0, (sn2cs3j + sn3cs2) * ep1sn0, (-sn2sn3 + cs2cs3j) * ep1sn0, (-sn2sn3 + cs2cs3j) * ep1cs0, (sn2cs3j + sn3cs2) * ep1cs0, ] flat_dst = dst[k, 2].ravel() flat_dst[:] = [ -(sn2cs3 + sn3cs2j) * en1cs0, (sn2sn3j - cs2cs3) * en1cs0, -(sn2sn3j - cs2cs3) * en1sn0, (sn2cs3 + sn3cs2j) * en1sn0, (sn2sn3j + cs2cs3) * en1cs0, (-sn2cs3 + sn3cs2j) * en1cs0, (sn2cs3 - sn3cs2j) * en1sn0, -(sn2sn3j + cs2cs3) * en1sn0, -(sn2cs3 + sn3cs2j) * ep1sn0, (sn2sn3j - cs2cs3) * ep1sn0, (sn2sn3j - cs2cs3) * ep1cs0, -(sn2cs3 + sn3cs2j) * ep1cs0, (sn2sn3j + cs2cs3) * ep1sn0, (-sn2cs3 + sn3cs2j) * ep1sn0, (-sn2cs3 + sn3cs2j) * ep1cs0, (sn2sn3j + cs2cs3) * ep1cs0, ] flat_dst = dst[k, 3].ravel() flat_dst[:] = [ -(sn2cs3j + sn3cs2) * en1cs0, (sn2sn3 - cs2cs3j) * en1cs0, (-sn2sn3 + cs2cs3j) * en1sn0, (sn2cs3j + sn3cs2) * en1sn0, -(sn2sn3 + cs2cs3j) * en1cs0, (sn2cs3j - sn3cs2) * en1cs0, -(sn2cs3j - sn3cs2) * en1sn0, (sn2sn3 + cs2cs3j) * en1sn0, -(sn2cs3j + sn3cs2) * ep1sn0, (sn2sn3 - cs2cs3j) * ep1sn0, (sn2sn3 - cs2cs3j) * ep1cs0, -(sn2cs3j + sn3cs2) * ep1cs0, -(sn2sn3 + cs2cs3j) * ep1sn0, (sn2cs3j - sn3cs2) * ep1sn0, (sn2cs3j - sn3cs2) * ep1cs0, -(sn2sn3 + cs2cs3j) * ep1cs0, ] return dst
qiskit/qiskit/synthesis/unitary/aqc/fast_gradient/layer.py/0
{ "file_path": "qiskit/qiskit/synthesis/unitary/aqc/fast_gradient/layer.py", "repo_id": "qiskit", "token_count": 6961 }
214
# 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. """RZX calibration builders.""" from __future__ import annotations import enum import math import warnings from collections.abc import Sequence from math import pi, erf import numpy as np from qiskit.circuit import Instruction as CircuitInst from qiskit.circuit.library.standard_gates import RZXGate from qiskit.exceptions import QiskitError from qiskit.pulse import ( Play, Schedule, ScheduleBlock, ControlChannel, DriveChannel, GaussianSquare, Waveform, ) from qiskit.pulse import builder from qiskit.pulse.filters import filter_instructions from qiskit.pulse.instruction_schedule_map import InstructionScheduleMap from qiskit.transpiler.target import Target from .base_builder import CalibrationBuilder from .exceptions import CalibrationNotAvailable class CRCalType(enum.Enum): """Estimated calibration type of backend cross resonance operations.""" ECR_FORWARD = "Echoed Cross Resonance corresponding to native operation" ECR_REVERSE = "Echoed Cross Resonance reverse of native operation" ECR_CX_FORWARD = "Echoed Cross Resonance CX corresponding to native operation" ECR_CX_REVERSE = "Echoed Cross Resonance CX reverse of native operation" DIRECT_CX_FORWARD = "Direct CX corresponding to native operation" DIRECT_CX_REVERSE = "Direct CX reverse of native operation" class RZXCalibrationBuilder(CalibrationBuilder): """ Creates calibrations for RZXGate(theta) by stretching and compressing Gaussian square pulses in the CX gate. This is done by retrieving (for a given pair of qubits) the CX schedule in the instruction schedule map of the backend defaults. The CX schedule must be an echoed cross-resonance gate optionally with rotary tones. The cross-resonance drive tones and rotary pulses must be Gaussian square pulses. The width of the Gaussian square pulse is adjusted so as to match the desired rotation angle. If the rotation angle is small such that the width disappears then the amplitude of the zero width Gaussian square pulse (i.e. a Gaussian) is reduced to reach the target rotation angle. Additional details can be found in https://arxiv.org/abs/2012.11660. """ def __init__( self, instruction_schedule_map: InstructionScheduleMap = None, verbose: bool = True, target: Target = None, ): """ Initializes a RZXGate calibration builder. Args: instruction_schedule_map: The :obj:`InstructionScheduleMap` object representing the default pulse calibrations for the target backend verbose: Set True to raise a user warning when RZX schedule cannot be built. target: The :class:`~.Target` representing the target backend, if both ``instruction_schedule_map`` and this are specified then this argument will take precedence and ``instruction_schedule_map`` will be ignored. Raises: QiskitError: Instruction schedule map is not provided. """ super().__init__() self._inst_map = instruction_schedule_map self._verbose = verbose if target: self._inst_map = target.instruction_schedule_map() if self._inst_map is None: raise QiskitError("Calibrations can only be added to Pulse-enabled backends") def supported(self, node_op: CircuitInst, qubits: list) -> bool: """Determine if a given node supports the calibration. Args: node_op: Target instruction object. qubits: Integer qubit indices to check. Returns: Return ``True`` is calibration can be provided. """ return isinstance(node_op, RZXGate) and ( "cx" in self._inst_map.instructions or "ecr" in self._inst_map.instructions ) @staticmethod @builder.macro def rescale_cr_inst(instruction: Play, theta: float, sample_mult: int = 16) -> int: """A builder macro to play stretched pulse. Args: instruction: The instruction from which to create a new shortened or lengthened pulse. theta: desired angle, pi/2 is assumed to be the angle that the pulse in the given play instruction implements. sample_mult: All pulses must be a multiple of sample_mult. Returns: Duration of stretched pulse. Raises: QiskitError: if rotation angle is not assigned. """ try: theta = float(theta) except TypeError as ex: raise QiskitError("Target rotation angle is not assigned.") from ex # This method is called for instructions which are guaranteed to play GaussianSquare pulse params = instruction.pulse.parameters.copy() risefall_sigma_ratio = (params["duration"] - params["width"]) / params["sigma"] # The error function is used because the Gaussian may have chopped tails. # Area is normalized by amplitude. # This makes widths robust to the rounding error. risefall_area = params["sigma"] * math.sqrt(2 * pi) * erf(risefall_sigma_ratio) full_area = params["width"] + risefall_area # Get estimate of target area. Assume this is pi/2 controlled rotation. cal_angle = pi / 2 target_area = abs(theta) / cal_angle * full_area new_width = target_area - risefall_area if new_width >= 0: width = new_width params["amp"] *= np.sign(theta) else: width = 0 params["amp"] *= np.sign(theta) * target_area / risefall_area round_duration = ( round((width + risefall_sigma_ratio * params["sigma"]) / sample_mult) * sample_mult ) params["duration"] = round_duration params["width"] = width stretched_pulse = GaussianSquare(**params) builder.play(stretched_pulse, instruction.channel) return round_duration def get_calibration(self, node_op: CircuitInst, qubits: list) -> Schedule | ScheduleBlock: """Builds the calibration schedule for the RZXGate(theta) with echos. Args: node_op: Instruction of the RZXGate(theta). I.e. params[0] is theta. qubits: List of qubits for which to get the schedules. The first qubit is the control and the second is the target. Returns: schedule: The calibration schedule for the RZXGate(theta). Raises: QiskitError: if rotation angle is not assigned. QiskitError: If the control and target qubits cannot be identified. CalibrationNotAvailable: RZX schedule cannot be built for input node. """ theta = node_op.params[0] try: theta = float(theta) except TypeError as ex: raise QiskitError("Target rotation angle is not assigned.") from ex if np.isclose(theta, 0.0): return ScheduleBlock(name="rzx(0.000)") cal_type, cr_tones, comp_tones = _check_calibration_type(self._inst_map, qubits) if cal_type in [CRCalType.DIRECT_CX_FORWARD, CRCalType.DIRECT_CX_REVERSE]: if self._verbose: warnings.warn( f"CR instruction for qubits {qubits} is likely {cal_type.value} sequence. " "Pulse stretch for this calibration is not currently implemented. " "RZX schedule is not generated for this qubit pair.", UserWarning, ) raise CalibrationNotAvailable # The CR instruction is in the forward (native) direction if cal_type in [CRCalType.ECR_CX_FORWARD, CRCalType.ECR_FORWARD]: xgate = self._inst_map.get("x", qubits[0]) with builder.build( default_alignment="sequential", name=f"rzx({theta:.3f})" ) as rzx_theta_native: for cr_tone, comp_tone in zip(cr_tones, comp_tones): with builder.align_left(): self.rescale_cr_inst(cr_tone, theta) self.rescale_cr_inst(comp_tone, theta) builder.call(xgate) return rzx_theta_native # The direction is not native. Add Hadamard gates to flip the direction. xgate = self._inst_map.get("x", qubits[1]) szc = self._inst_map.get("rz", qubits[1], pi / 2) sxc = self._inst_map.get("sx", qubits[1]) szt = self._inst_map.get("rz", qubits[0], pi / 2) sxt = self._inst_map.get("sx", qubits[0]) with builder.build(name="hadamard") as hadamard: # Control qubit builder.call(szc, name="szc") builder.call(sxc, name="sxc") builder.call(szc, name="szc") # Target qubit builder.call(szt, name="szt") builder.call(sxt, name="sxt") builder.call(szt, name="szt") with builder.build( default_alignment="sequential", name=f"rzx({theta:.3f})" ) as rzx_theta_flip: builder.call(hadamard, name="hadamard") for cr_tone, comp_tone in zip(cr_tones, comp_tones): with builder.align_left(): self.rescale_cr_inst(cr_tone, theta) self.rescale_cr_inst(comp_tone, theta) builder.call(xgate) builder.call(hadamard, name="hadamard") return rzx_theta_flip class RZXCalibrationBuilderNoEcho(RZXCalibrationBuilder): """ Creates calibrations for RZXGate(theta) by stretching and compressing Gaussian square pulses in the CX gate. The ``RZXCalibrationBuilderNoEcho`` is a variation of the :class:`~qiskit.transpiler.passes.RZXCalibrationBuilder` pass that creates calibrations for the cross-resonance pulses without inserting the echo pulses in the pulse schedule. This enables exposing the echo in the cross-resonance sequence as gates so that the transpiler can simplify them. The ``RZXCalibrationBuilderNoEcho`` only supports the hardware-native direction of the CX gate. """ def get_calibration(self, node_op: CircuitInst, qubits: list) -> Schedule | ScheduleBlock: """Builds the calibration schedule for the RZXGate(theta) without echos. Args: node_op: Instruction of the RZXGate(theta). I.e. params[0] is theta. qubits: List of qubits for which to get the schedules. The first qubit is the control and the second is the target. Returns: schedule: The calibration schedule for the RZXGate(theta). Raises: QiskitError: if rotation angle is not assigned. QiskitError: If the control and target qubits cannot be identified, or the backend does not natively support the specified direction of the cx. CalibrationNotAvailable: RZX schedule cannot be built for input node. """ theta = node_op.params[0] try: theta = float(theta) except TypeError as ex: raise QiskitError("Target rotation angle is not assigned.") from ex if np.isclose(theta, 0.0): return ScheduleBlock(name="rzx(0.000)") cal_type, cr_tones, comp_tones = _check_calibration_type(self._inst_map, qubits) if cal_type in [CRCalType.DIRECT_CX_FORWARD, CRCalType.DIRECT_CX_REVERSE]: if self._verbose: warnings.warn( f"CR instruction for qubits {qubits} is likely {cal_type.value} sequence. " "Pulse stretch for this calibration is not currently implemented. " "RZX schedule is not generated for this qubit pair.", UserWarning, ) raise CalibrationNotAvailable # RZXCalibrationNoEcho only good for forward CR direction if cal_type in [CRCalType.ECR_CX_FORWARD, CRCalType.ECR_FORWARD]: with builder.build(default_alignment="left", name=f"rzx({theta:.3f})") as rzx_theta: stretched_dur = self.rescale_cr_inst(cr_tones[0], 2 * theta) self.rescale_cr_inst(comp_tones[0], 2 * theta) # Placeholder to make pulse gate work builder.delay(stretched_dur, DriveChannel(qubits[0])) return rzx_theta raise QiskitError("RZXCalibrationBuilderNoEcho only supports hardware-native RZX gates.") def _filter_cr_tone(time_inst_tup): """A helper function to filter pulses on control channels.""" valid_types = ["GaussianSquare"] _, inst = time_inst_tup if isinstance(inst, Play) and isinstance(inst.channel, ControlChannel): pulse = inst.pulse if isinstance(pulse, Waveform) or pulse.pulse_type in valid_types: return True return False def _filter_comp_tone(time_inst_tup): """A helper function to filter pulses on drive channels.""" valid_types = ["GaussianSquare"] _, inst = time_inst_tup if isinstance(inst, Play) and isinstance(inst.channel, DriveChannel): pulse = inst.pulse if isinstance(pulse, Waveform) or pulse.pulse_type in valid_types: return True return False def _check_calibration_type( inst_sched_map: InstructionScheduleMap, qubits: Sequence[int] ) -> tuple[CRCalType, list[Play], list[Play]]: """A helper function to check type of CR calibration. Args: inst_sched_map: instruction schedule map of the backends qubits: ordered tuple of qubits for cross resonance (q_control, q_target) Returns: Filtered instructions and most-likely type of calibration. Raises: QiskitError: Unknown calibration type is detected. """ cal_type = None if inst_sched_map.has("cx", qubits): cr_sched = inst_sched_map.get("cx", qubits=qubits) elif inst_sched_map.has("ecr", qubits): cr_sched = inst_sched_map.get("ecr", qubits=qubits) cal_type = CRCalType.ECR_FORWARD elif inst_sched_map.has("ecr", tuple(reversed(qubits))): cr_sched = inst_sched_map.get("ecr", tuple(reversed(qubits))) cal_type = CRCalType.ECR_REVERSE else: raise QiskitError( f"Native direction cannot be determined: operation on qubits {qubits} " f"for the following instruction schedule map:\n{inst_sched_map}" ) cr_tones = [t[1] for t in filter_instructions(cr_sched, [_filter_cr_tone]).instructions] comp_tones = [t[1] for t in filter_instructions(cr_sched, [_filter_comp_tone]).instructions] if cal_type is None: if len(comp_tones) == 0: raise QiskitError( f"{repr(cr_sched)} has no target compensation tones. " "Native ECR direction cannot be determined." ) # Determine native direction, assuming only single drive channel per qubit. # This guarantees channel and qubit index equality. if comp_tones[0].channel.index == qubits[1]: cal_type = CRCalType.ECR_CX_FORWARD else: cal_type = CRCalType.ECR_CX_REVERSE if len(cr_tones) == 2 and len(comp_tones) in (0, 2): # ECR can be implemented without compensation tone at price of lower fidelity. # Remarkable noisy terms are usually eliminated by echo. return cal_type, cr_tones, comp_tones if len(cr_tones) == 1 and len(comp_tones) == 1: # Direct CX must have compensation tone on target qubit. # Otherwise, it cannot eliminate IX interaction. if comp_tones[0].channel.index == qubits[1]: return CRCalType.DIRECT_CX_FORWARD, cr_tones, comp_tones else: return CRCalType.DIRECT_CX_REVERSE, cr_tones, comp_tones raise QiskitError( f"{repr(cr_sched)} is undefined pulse sequence. " "Check if this is a calibration for cross resonance operation." )
qiskit/qiskit/transpiler/passes/calibration/rzx_builder.py/0
{ "file_path": "qiskit/qiskit/transpiler/passes/calibration/rzx_builder.py", "repo_id": "qiskit", "token_count": 6739 }
215
# 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. """VF2PostLayout pass to find a layout after transpile using subgraph isomorphism""" from enum import Enum import logging import inspect import itertools import time from rustworkx import PyDiGraph, vf2_mapping, PyGraph from qiskit.transpiler.layout import Layout from qiskit.transpiler.basepasses import AnalysisPass from qiskit.transpiler.exceptions import TranspilerError from qiskit.providers.exceptions import BackendPropertyError from qiskit.transpiler.passes.layout import vf2_utils logger = logging.getLogger(__name__) class VF2PostLayoutStopReason(Enum): """Stop reasons for VF2PostLayout pass.""" SOLUTION_FOUND = "solution found" NO_BETTER_SOLUTION_FOUND = "no better solution found" NO_SOLUTION_FOUND = "nonexistent solution" MORE_THAN_2Q = ">2q gates in basis" def _target_match(node_a, node_b): # Node A is the set of operations in the target. Node B is the count dict # of operations on the node or edge in the circuit. if isinstance(node_a, set): return node_a.issuperset(node_b.keys()) # Node A is the count dict of operations on the node or edge in the circuit # Node B is the set of operations in the target on the same qubit(s). else: return set(node_a).issubset(node_b) class VF2PostLayout(AnalysisPass): """A pass for improving an existing Layout after transpilation of a circuit onto a Coupling graph, as a subgraph isomorphism problem, solved by VF2++. Unlike the :class:`~.VF2Layout` transpiler pass which is designed to find an initial layout for a circuit early in the transpilation pipeline this transpiler pass is designed to try and find a better layout after transpilation is complete. The initial layout phase of the transpiler doesn't have as much information available as we do after transpilation. This pass is designed to be paired in a similar pipeline as the layout passes. This pass will strip any idle wires from the circuit, use VF2 to find a subgraph in the coupling graph for the circuit to run on with better fidelity and then update the circuit layout to use the new qubits. The algorithm used in this pass is described in `arXiv:2209.15512 <https://arxiv.org/abs/2209.15512>`__. If a solution is found that means there is a lower error layout available for the circuit. If a solution is found the layout will be set in the property set as ``property_set['post_layout']``. However, if no solution or no better solution is found, no ``property_set['post_layout']`` is set. The stopping reason is set in ``property_set['VF2PostLayout_stop_reason']`` in all the cases and will be one of the values enumerated in ``VF2PostLayoutStopReason`` which has the following values: * ``"solution found"``: If a solution was found. * ``"no better solution found"``: If the initial layout of the circuit is the best solution. * ``"nonexistent solution"``: If no solution was found. * ``">2q gates in basis"``: If VF2PostLayout can't work with the basis of the circuit. By default, this pass will construct a heuristic scoring map based on the error rates in the provided ``target`` (or ``properties`` if ``target`` is not provided). However, analysis passes can be run prior to this pass and set ``vf2_avg_error_map`` in the property set with a :class:`~.ErrorMap` instance. If a value is ``NaN`` that is treated as an ideal edge For example if an error map is created as:: from qiskit.transpiler.passes.layout.vf2_utils import ErrorMap error_map = ErrorMap(3) error_map.add_error((0, 0), 0.0024) error_map.add_error((0, 1), 0.01) error_map.add_error((1, 1), 0.0032) that represents the error map for a 2 qubit target, where the avg 1q error rate is ``0.0024`` on qubit 0 and ``0.0032`` on qubit 1. Then the avg 2q error rate for gates that operate on (0, 1) is 0.01 and (1, 0) is not supported by the target. This will be used for scoring if it's set as the ``vf2_avg_error_map`` key in the property set when :class:`~.VF2PostLayout` is run. """ def __init__( self, target=None, coupling_map=None, properties=None, seed=None, call_limit=None, time_limit=None, strict_direction=True, max_trials=0, ): """Initialize a ``VF2PostLayout`` pass instance Args: target (Target): A target representing the backend device to run ``VF2PostLayout`` on. If specified it will supersede a set value for ``properties`` and ``coupling_map``. coupling_map (CouplingMap): Directed graph representing a coupling map. properties (BackendProperties): The backend properties for the backend. If :meth:`~qiskit.providers.models.BackendProperties.readout_error` is available it is used to score the layout. seed (int): Sets the seed of the PRNG. -1 Means no node shuffling. call_limit (int): The number of state visits to attempt in each execution of VF2. time_limit (float): The total time limit in seconds to run ``VF2PostLayout`` strict_direction (bool): Whether the pass is configured to follow the strict direction in the coupling graph. If this is set to false, the pass will treat any edge in the coupling graph as a weak edge and the interaction graph will be undirected. For the purposes of evaluating layouts the avg error rate for each qubit and 2q link will be used. This enables the pass to be run prior to basis translation and work with any 1q and 2q operations. However, if ``strict_direction=True`` the pass expects the input :class:`~.DAGCircuit` object to :meth:`~.VF2PostLayout.run` to be in the target set of instructions. max_trials (int): The maximum number of trials to run VF2 to find a layout. A value of ``0`` (the default) means 'unlimited'. Raises: TypeError: At runtime, if neither ``coupling_map`` or ``target`` are provided. """ super().__init__() self.target = target self.coupling_map = coupling_map self.properties = properties self.call_limit = call_limit self.time_limit = time_limit self.max_trials = max_trials self.seed = seed self.strict_direction = strict_direction self.avg_error_map = None def run(self, dag): """run the layout method""" if self.target is None and (self.coupling_map is None or self.properties is None): raise TranspilerError( "A target must be specified or a coupling map and properties must be provided" ) if not self.strict_direction: self.avg_error_map = self.property_set["vf2_avg_error_map"] if self.avg_error_map is None: self.avg_error_map = vf2_utils.build_average_error_map( self.target, self.properties, self.coupling_map ) result = vf2_utils.build_interaction_graph(dag, self.strict_direction) if result is None: self.property_set["VF2PostLayout_stop_reason"] = VF2PostLayoutStopReason.MORE_THAN_2Q return im_graph, im_graph_node_map, reverse_im_graph_node_map, free_nodes = result scoring_bit_list = vf2_utils.build_bit_list(im_graph, im_graph_node_map) scoring_edge_list = vf2_utils.build_edge_list(im_graph) if self.target is not None: # If qargs is None then target is global and ideal so no # scoring is needed if self.target.qargs is None: return if self.strict_direction: cm_graph = PyDiGraph(multigraph=False) else: cm_graph = PyGraph(multigraph=False) # If None is present in qargs there are globally defined ideal operations # we should add these to all entries based on the number of qubits, so we # treat that as a valid operation even if there is no scoring for the # strict direction case global_ops = None if None in self.target.qargs: global_ops = {1: [], 2: []} for op in self.target.operation_names_for_qargs(None): operation = self.target.operation_for_name(op) # If operation is a class this is a variable width ideal instruction # so we treat it as available on both 1 and 2 qubits if inspect.isclass(operation): global_ops[1].append(op) global_ops[2].append(op) else: num_qubits = operation.num_qubits if num_qubits in global_ops: global_ops[num_qubits].append(op) op_names = [] for i in range(self.target.num_qubits): try: entry = set(self.target.operation_names_for_qargs((i,))) except KeyError: entry = set() if global_ops is not None: entry.update(global_ops[1]) op_names.append(entry) cm_graph.add_nodes_from(op_names) for qargs in self.target.qargs: len_args = len(qargs) # If qargs == 1 we already populated it and if qargs > 2 there are no instructions # using those in the circuit because we'd have already returned by this point if len_args == 2: ops = set(self.target.operation_names_for_qargs(qargs)) if global_ops is not None: ops.update(global_ops[2]) cm_graph.add_edge(qargs[0], qargs[1], ops) cm_nodes = list(cm_graph.node_indexes()) # Filter qubits without any supported operations. If they # don't support any operations, they're not valid for layout selection. # This is only needed in the undirected case because in strict direction # mode the node matcher will not match since none of the circuit ops # will match the cmap ops. if not self.strict_direction: has_operations = set(itertools.chain.from_iterable(self.target.qargs)) to_remove = set(cm_graph.node_indices()).difference(has_operations) if to_remove: cm_graph.remove_nodes_from(list(to_remove)) else: cm_graph, cm_nodes = vf2_utils.shuffle_coupling_graph( self.coupling_map, self.seed, self.strict_direction ) logger.debug("Running VF2 to find post transpile mappings") if self.target and self.strict_direction: mappings = vf2_mapping( cm_graph, im_graph, node_matcher=_target_match, edge_matcher=_target_match, subgraph=True, id_order=False, induced=False, call_limit=self.call_limit, ) else: mappings = vf2_mapping( cm_graph, im_graph, subgraph=True, id_order=False, induced=False, call_limit=self.call_limit, ) chosen_layout = None try: if self.strict_direction: initial_layout = Layout({bit: index for index, bit in enumerate(dag.qubits)}) chosen_layout_score = self._score_layout( initial_layout, im_graph_node_map, reverse_im_graph_node_map, im_graph, ) else: initial_layout = { im_graph_node_map[bit]: index for index, bit in enumerate(dag.qubits) if bit in im_graph_node_map } chosen_layout_score = vf2_utils.score_layout( self.avg_error_map, initial_layout, im_graph_node_map, reverse_im_graph_node_map, im_graph, self.strict_direction, edge_list=scoring_edge_list, bit_list=scoring_bit_list, ) chosen_layout = initial_layout stop_reason = VF2PostLayoutStopReason.NO_BETTER_SOLUTION_FOUND # Circuit not in basis so we have nothing to compare against return here except KeyError: self.property_set["VF2PostLayout_stop_reason"] = ( VF2PostLayoutStopReason.NO_SOLUTION_FOUND ) return logger.debug("Initial layout has score %s", chosen_layout_score) start_time = time.time() trials = 0 for mapping in mappings: trials += 1 logger.debug("Running trial: %s", trials) layout_mapping = {im_i: cm_nodes[cm_i] for cm_i, im_i in mapping.items()} if self.strict_direction: layout = Layout( {reverse_im_graph_node_map[k]: v for k, v in layout_mapping.items()} ) layout_score = self._score_layout( layout, im_graph_node_map, reverse_im_graph_node_map, im_graph ) else: layout_score = vf2_utils.score_layout( self.avg_error_map, layout_mapping, im_graph_node_map, reverse_im_graph_node_map, im_graph, self.strict_direction, edge_list=scoring_edge_list, bit_list=scoring_bit_list, ) logger.debug("Trial %s has score %s", trials, layout_score) if layout_score < chosen_layout_score: layout = Layout( {reverse_im_graph_node_map[k]: v for k, v in layout_mapping.items()} ) logger.debug( "Found layout %s has a lower score (%s) than previous best %s (%s)", layout, layout_score, chosen_layout, chosen_layout_score, ) chosen_layout = layout chosen_layout_score = layout_score stop_reason = VF2PostLayoutStopReason.SOLUTION_FOUND if self.max_trials and trials >= self.max_trials: logger.debug("Trial %s is >= configured max trials %s", trials, self.max_trials) break elapsed_time = time.time() - start_time if self.time_limit is not None and elapsed_time >= self.time_limit: logger.debug( "VFPostLayout has taken %s which exceeds configured max time: %s", elapsed_time, self.time_limit, ) break if stop_reason == VF2PostLayoutStopReason.SOLUTION_FOUND: chosen_layout = vf2_utils.map_free_qubits( free_nodes, chosen_layout, cm_graph.num_nodes(), reverse_im_graph_node_map, self.avg_error_map, ) existing_layout = self.property_set["layout"] # If any ancillas in initial layout map them back to the final layout output if existing_layout is not None and len(existing_layout) > len(chosen_layout): virtual_bits = chosen_layout.get_virtual_bits() used_bits = set(virtual_bits.values()) num_qubits = len(cm_graph) for bit in dag.qubits: if len(chosen_layout) == len(existing_layout): break if bit not in virtual_bits: for i in range(num_qubits): if i not in used_bits: used_bits.add(i) chosen_layout.add(bit, i) break self.property_set["post_layout"] = chosen_layout else: if chosen_layout is None: stop_reason = VF2PostLayoutStopReason.NO_SOLUTION_FOUND # else the initial layout is optimal -> don't set post_layout, return 'no better solution' self.property_set["VF2PostLayout_stop_reason"] = stop_reason def _score_layout(self, layout, bit_map, reverse_bit_map, im_graph): bits = layout.get_virtual_bits() fidelity = 1 if self.target is not None: for bit, node_index in bit_map.items(): gate_counts = im_graph[node_index] for gate, count in gate_counts.items(): if self.target[gate] is not None and None not in self.target[gate]: props = self.target[gate][(bits[bit],)] if props is not None and props.error is not None: fidelity *= (1 - props.error) ** count for edge in im_graph.edge_index_map().values(): qargs = (bits[reverse_bit_map[edge[0]]], bits[reverse_bit_map[edge[1]]]) gate_counts = edge[2] for gate, count in gate_counts.items(): if self.target[gate] is not None and None not in self.target[gate]: props = self.target[gate][qargs] if props is not None and props.error is not None: fidelity *= (1 - props.error) ** count else: for bit, node_index in bit_map.items(): gate_counts = im_graph[node_index] for gate, count in gate_counts.items(): if gate == "measure": try: fidelity *= (1 - self.properties.readout_error(bits[bit])) ** count except BackendPropertyError: pass else: try: fidelity *= (1 - self.properties.gate_error(gate, bits[bit])) ** count except BackendPropertyError: pass for edge in im_graph.edge_index_map().values(): qargs = (bits[reverse_bit_map[edge[0]]], bits[reverse_bit_map[edge[1]]]) gate_counts = edge[2] for gate, count in gate_counts.items(): try: fidelity *= (1 - self.properties.gate_error(gate, qargs)) ** count except BackendPropertyError: pass return 1 - fidelity
qiskit/qiskit/transpiler/passes/layout/vf2_post_layout.py/0
{ "file_path": "qiskit/qiskit/transpiler/passes/layout/vf2_post_layout.py", "repo_id": "qiskit", "token_count": 9345 }
216
# This code is part of Qiskit. # # (C) Copyright IBM 2023 # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Remove any swap gates in the circuit by pushing it through into a qubit permutation.""" import logging from qiskit.circuit.library.standard_gates import SwapGate from qiskit.circuit.library.generalized_gates import PermutationGate from qiskit.transpiler.basepasses import TransformationPass from qiskit.transpiler.layout import Layout logger = logging.getLogger(__name__) class ElidePermutations(TransformationPass): r"""Remove permutation operations from a pre-layout circuit This pass is intended to be run before a layout (mapping virtual qubits to physical qubits) is set during the transpilation pipeline. This pass iterates over the :class:`~.DAGCircuit` and when a :class:`~.SwapGate` or :class:`~.PermutationGate` are encountered it permutes the virtual qubits in the circuit and removes the swap gate. This will effectively remove any :class:`~SwapGate`\s or :class:`~PermutationGate` in the circuit prior to running layout. If this pass is run after a layout has been set it will become a no-op (and log a warning) as this optimization is not sound after physical qubits are selected and there are connectivity constraints to adhere to. For tracking purposes this pass sets 3 values in the property set if there are any :class:`~.SwapGate` or :class:`~.PermutationGate` objects in the circuit and the pass isn't a no-op. * ``original_layout``: The trivial :class:`~.Layout` for the input to this pass being run * ``original_qubit_indices``: The mapping of qubit objects to positional indices for the state of the circuit as input to this pass. * ``virtual_permutation_layout``: A :class:`~.Layout` object mapping input qubits to the output state after eliding permutations. These three properties are needed for the transpiler to track the permutations in the out :attr:`.QuantumCircuit.layout` attribute. The elision of permutations is equivalent to a ``final_layout`` set by routing and all three of these attributes are needed in the case """ def run(self, dag): """Run the ElidePermutations pass on ``dag``. Args: dag (DAGCircuit): the DAG to be optimized. Returns: DAGCircuit: the optimized DAG. """ if self.property_set["layout"] is not None: logger.warning( "ElidePermutations is not valid after a layout has been set. This indicates " "an invalid pass manager construction." ) return dag op_count = dag.count_ops(recurse=False) if op_count.get("swap", 0) == 0 and op_count.get("permutation", 0) == 0: return dag new_dag = dag.copy_empty_like() qubit_mapping = list(range(len(dag.qubits))) def _apply_mapping(qargs): return tuple(dag.qubits[qubit_mapping[dag.find_bit(qubit).index]] for qubit in qargs) for node in dag.topological_op_nodes(): if not isinstance(node.op, (SwapGate, PermutationGate)): new_dag.apply_operation_back( node.op, _apply_mapping(node.qargs), node.cargs, check=False ) elif getattr(node.op, "condition", None) is not None: new_dag.apply_operation_back( node.op, _apply_mapping(node.qargs), node.cargs, check=False ) elif isinstance(node.op, SwapGate): index_0 = dag.find_bit(node.qargs[0]).index index_1 = dag.find_bit(node.qargs[1]).index qubit_mapping[index_1], qubit_mapping[index_0] = ( qubit_mapping[index_0], qubit_mapping[index_1], ) elif isinstance(node.op, PermutationGate): starting_indices = [qubit_mapping[dag.find_bit(qarg).index] for qarg in node.qargs] pattern = node.op.params[0] pattern_indices = [qubit_mapping[idx] for idx in pattern] for i, j in zip(starting_indices, pattern_indices): qubit_mapping[i] = j input_qubit_mapping = {qubit: index for index, qubit in enumerate(dag.qubits)} self.property_set["original_layout"] = Layout(input_qubit_mapping) if self.property_set["original_qubit_indices"] is None: self.property_set["original_qubit_indices"] = input_qubit_mapping new_layout = Layout({dag.qubits[out]: idx for idx, out in enumerate(qubit_mapping)}) if current_layout := self.property_set["virtual_permutation_layout"]: self.property_set["virtual_permutation_layout"] = new_layout.compose( current_layout.inverse(dag.qubits, dag.qubits), dag.qubits ) else: self.property_set["virtual_permutation_layout"] = new_layout return new_dag
qiskit/qiskit/transpiler/passes/optimization/elide_permutations.py/0
{ "file_path": "qiskit/qiskit/transpiler/passes/optimization/elide_permutations.py", "repo_id": "qiskit", "token_count": 2145 }
217
# 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. """ Template matching in the backward direction, it takes an initial match, a configuration of qubit, both circuit and template as inputs and the list obtained from forward match. The result is a list of matches between the template and the circuit. **Reference:** [1] Iten, R., Moyard, R., Metger, T., Sutter, D. and Woerner, S., 2020. Exact and practical pattern matching for quantum circuit optimization. `arXiv:1909.05270 <https://arxiv.org/abs/1909.05270>`_ """ import heapq from qiskit.circuit.controlledgate import ControlledGate class Match: """ Object to represent a match and its qubit configurations. """ def __init__(self, match, qubit, clbit): """ Create a Match class with necessary arguments. Args: match (list): list of matched gates. qubit (list): list of qubits configuration. clbit (list): list of clbits configuration. """ # Match list self.match = match # Qubits list for circuit self.qubit = [qubit] # Clbits for template self.clbit = [clbit] class MatchingScenarios: """ Class to represent a matching scenario. """ def __init__( self, circuit_matched, circuit_blocked, template_matched, template_blocked, matches, counter ): """ Create a MatchingScenarios class with necessary arguments. Args: circuit_matched (list): list of matchedwith attributes in the circuit. circuit_blocked (list): list of isblocked attributes in the circuit. template_matched (list): list of matchedwith attributes in the template. template_blocked (list): list of isblocked attributes in the template. matches (list): list of matches. counter (int): counter of the number of circuit gates already considered. """ self.circuit_matched = circuit_matched self.template_matched = template_matched self.circuit_blocked = circuit_blocked self.template_blocked = template_blocked self.matches = matches self.counter = counter class MatchingScenariosList: """ Object to define a list of MatchingScenarios, with method to append and pop elements. """ def __init__(self): """ Create an empty MatchingScenariosList. """ self.matching_scenarios_list = [] def append_scenario(self, matching): """ Append a scenario to the list. Args: matching (MatchingScenarios): a scenario of match. """ self.matching_scenarios_list.append(matching) def pop_scenario(self): """ Pop the first scenario of the list. Returns: MatchingScenarios: a scenario of match. """ # Pop the first MatchingScenario and returns it first = self.matching_scenarios_list[0] self.matching_scenarios_list.pop(0) return first class BackwardMatch: """ Class BackwardMatch allows to run backward direction part of template matching algorithm. """ def __init__( self, circuit_dag_dep, template_dag_dep, forward_matches, node_id_c, node_id_t, qubits, clbits=None, heuristics_backward_param=None, ): """ Create a ForwardMatch class with necessary arguments. Args: circuit_dag_dep (DAGDependency): circuit in the dag dependency form. template_dag_dep (DAGDependency): template in the dag dependency form. forward_matches (list): list of match obtained in the forward direction. node_id_c (int): index of the first gate matched in the circuit. node_id_t (int): index of the first gate matched in the template. qubits (list): list of considered qubits in the circuit. clbits (list): list of considered clbits in the circuit. heuristics_backward_param (list): list that contains the two parameters for applying the heuristics (length and survivor). """ self.circuit_dag_dep = circuit_dag_dep.copy() self.template_dag_dep = template_dag_dep.copy() self.qubits = qubits self.clbits = clbits if clbits is not None else [] self.node_id_c = node_id_c self.node_id_t = node_id_t self.forward_matches = forward_matches self.match_final = [] self.heuristics_backward_param = ( heuristics_backward_param if heuristics_backward_param is not None else [] ) self.matching_list = MatchingScenariosList() def _gate_indices(self): """ Function which returns the list of gates that are not match and not blocked for the first scenario. Returns: list: list of gate id. """ gate_indices = [] current_dag = self.circuit_dag_dep for node in current_dag.get_nodes(): if (not node.matchedwith) and (not node.isblocked): gate_indices.append(node.node_id) gate_indices.reverse() return gate_indices def _find_backward_candidates(self, template_blocked, matches): """ Function which returns the list possible backward candidates in the template dag. Args: template_blocked (list): list of attributes isblocked in the template circuit. matches (list): list of matches. Returns: list: list of backward candidates (id). """ template_block = [] for node_id in range(self.node_id_t, self.template_dag_dep.size()): if template_blocked[node_id]: template_block.append(node_id) matches_template = sorted(match[0] for match in matches) successors = self.template_dag_dep.get_node(self.node_id_t).successors potential = [] for index in range(self.node_id_t + 1, self.template_dag_dep.size()): if (index not in successors) and (index not in template_block): potential.append(index) candidates_indices = list(set(potential) - set(matches_template)) candidates_indices = sorted(candidates_indices) candidates_indices.reverse() return candidates_indices def _update_qarg_indices(self, qarg): """ Change qubits indices of the current circuit node in order to be comparable the indices of the template qubits list. Args: qarg (list): list of qubits indices from the circuit for a given gate. Returns: list: circuit indices update for qubits. """ qarg_indices = [] for q in qarg: if q in self.qubits: qarg_indices.append(self.qubits.index(q)) if len(qarg) != len(qarg_indices): qarg_indices = [] return qarg_indices def _update_carg_indices(self, carg): """ Change clbits indices of the current circuit node in order to be comparable the indices of the template qubits list. Args: carg (list): list of clbits indices from the circuit for a given gate. Returns: list: circuit indices update for clbits. """ carg_indices = [] if carg: for q in carg: if q in self.clbits: carg_indices.append(self.clbits.index(q)) if len(carg) != len(carg_indices): carg_indices = [] return carg_indices def _is_same_op(self, node_circuit, node_template): """ Check if two instructions are the same. Args: node_circuit (DAGDepNode): node in the circuit. node_template (DAGDepNode): node in the template. Returns: bool: True if the same, False otherwise. """ return node_circuit.op == node_template.op def _is_same_q_conf(self, node_circuit, node_template, qarg_circuit): """ Check if the qubits configurations are compatible. Args: node_circuit (DAGDepNode): node in the circuit. node_template (DAGDepNode): node in the template. qarg_circuit (list): qubits configuration for the Instruction in the circuit. Returns: bool: True if possible, False otherwise. """ # If the gate is controlled, then the control qubits have to be compared as sets. if isinstance(node_circuit.op, ControlledGate): c_template = node_template.op.num_ctrl_qubits if c_template == 1: return qarg_circuit == node_template.qindices else: control_qubits_template = node_template.qindices[:c_template] control_qubits_circuit = qarg_circuit[:c_template] if set(control_qubits_circuit) == set(control_qubits_template): target_qubits_template = node_template.qindices[c_template::] target_qubits_circuit = qarg_circuit[c_template::] if node_template.op.base_gate.name in [ "rxx", "ryy", "rzz", "swap", "iswap", "ms", ]: return set(target_qubits_template) == set(target_qubits_circuit) else: return target_qubits_template == target_qubits_circuit else: return False # For non controlled gates, the qubits indices for symmetric gates can be compared as sets # But for non-symmetric gates the qubits indices have to be compared as lists. else: if node_template.op.name in ["rxx", "ryy", "rzz", "swap", "iswap", "ms"]: return set(qarg_circuit) == set(node_template.qindices) else: return qarg_circuit == node_template.qindices def _is_same_c_conf(self, node_circuit, node_template, carg_circuit): """ Check if the clbits configurations are compatible. Args: node_circuit (DAGDepNode): node in the circuit. node_template (DAGDepNode): node in the template. carg_circuit (list): clbits configuration for the Instruction in the circuit. Returns: bool: True if possible, False otherwise. """ if ( node_circuit.type == "op" and getattr(node_circuit.op, "condition", None) and node_template.type == "op" and getattr(node_template.op, "condition", None) ): if set(carg_circuit) != set(node_template.cindices): return False if ( getattr(node_circuit.op, "condition", None)[1] != getattr(node_template.op, "condition", None)[1] ): return False return True def _init_matched_blocked_list(self): """ Initialize the list of blocked and matchedwith attributes. Returns: Tuple[list, list, list, list]: First list contains the attributes matchedwith in the circuit, second list contains the attributes isblocked in the circuit, third list contains the attributes matchedwith in the template, fourth list contains the attributes isblocked in the template. """ circuit_matched = [] circuit_blocked = [] for node in self.circuit_dag_dep.get_nodes(): circuit_matched.append(node.matchedwith) circuit_blocked.append(node.isblocked) template_matched = [] template_blocked = [] for node in self.template_dag_dep.get_nodes(): template_matched.append(node.matchedwith) template_blocked.append(node.isblocked) return circuit_matched, circuit_blocked, template_matched, template_blocked def _backward_heuristics(self, gate_indices, length, survivor): """ Heuristics to cut the tree in the backward match algorithm Args: gate_indices (list): list of candidates in the circuit. length (int): depth for cutting the tree, cutting operation is repeated every length. survivor (int): number of survivor branches. """ # Set the list of the counter for the different scenarios. list_counter = [] for scenario in self.matching_list.matching_scenarios_list: list_counter.append(scenario.counter) metrics = [] # If all scenarios have the same counter and the counter is divisible by length. if list_counter.count(list_counter[0]) == len(list_counter) and list_counter[0] <= len( gate_indices ): if (list_counter[0] - 1) % length == 0: # The list metrics contains metric results for each scenarios. for scenario in self.matching_list.matching_scenarios_list: metrics.append(self._backward_metrics(scenario)) # Select only the scenarios with higher metrics for the given number of survivors. largest = heapq.nlargest(survivor, range(len(metrics)), key=lambda x: metrics[x]) self.matching_list.matching_scenarios_list = [ i for j, i in enumerate(self.matching_list.matching_scenarios_list) if j in largest ] def _backward_metrics(self, scenario): """ Heuristics to cut the tree in the backward match algorithm. Args: scenario (MatchingScenarios): scenario for the given match. Returns: int: length of the match for the given scenario. """ return len(scenario.matches) def run_backward_match(self): """ Apply the forward match algorithm and returns the list of matches given an initial match and a circuit qubits configuration. """ match_store_list = [] counter = 1 # Initialize the list of attributes matchedwith and isblocked. ( circuit_matched, circuit_blocked, template_matched, template_blocked, ) = self._init_matched_blocked_list() # First Scenario is stored in the MatchingScenariosList(). first_match = MatchingScenarios( circuit_matched, circuit_blocked, template_matched, template_blocked, self.forward_matches, counter, ) self.matching_list = MatchingScenariosList() self.matching_list.append_scenario(first_match) # Set the circuit indices that can be matched. gate_indices = self._gate_indices() number_of_gate_to_match = ( self.template_dag_dep.size() - (self.node_id_t - 1) - len(self.forward_matches) ) # While the scenario stack is not empty. while self.matching_list.matching_scenarios_list: # If parameters are given, the heuristics is applied. if self.heuristics_backward_param: self._backward_heuristics( gate_indices, self.heuristics_backward_param[0], self.heuristics_backward_param[1], ) scenario = self.matching_list.pop_scenario() circuit_matched = scenario.circuit_matched circuit_blocked = scenario.circuit_blocked template_matched = scenario.template_matched template_blocked = scenario.template_blocked matches_scenario = scenario.matches counter_scenario = scenario.counter # Part of the match list coming from the backward match. match_backward = [ match for match in matches_scenario if match not in self.forward_matches ] # Matches are stored if the counter is bigger than the length of the list of # candidates in the circuit. Or if number of gate left to match is the same as # the length of the backward part of the match. if ( counter_scenario > len(gate_indices) or len(match_backward) == number_of_gate_to_match ): matches_scenario.sort(key=lambda x: x[0]) match_store_list.append(Match(matches_scenario, self.qubits, self.clbits)) continue # First circuit candidate. circuit_id = gate_indices[counter_scenario - 1] node_circuit = self.circuit_dag_dep.get_node(circuit_id) # If the circuit candidate is blocked, only the counter is changed. if circuit_blocked[circuit_id]: matching_scenario = MatchingScenarios( circuit_matched, circuit_blocked, template_matched, template_blocked, matches_scenario, counter_scenario + 1, ) self.matching_list.append_scenario(matching_scenario) continue # The candidates in the template. candidates_indices = self._find_backward_candidates(template_blocked, matches_scenario) # Update of the qubits/clbits indices in the circuit in order to be # comparable with the one in the template. qarg1 = node_circuit.qindices carg1 = node_circuit.cindices qarg1 = self._update_qarg_indices(qarg1) carg1 = self._update_carg_indices(carg1) global_match = False global_broken = [] # Loop over the template candidates. for template_id in candidates_indices: node_template = self.template_dag_dep.get_node(template_id) qarg2 = self.template_dag_dep.get_node(template_id).qindices # Necessary but not sufficient conditions for a match to happen. if ( len(qarg1) != len(qarg2) or set(qarg1) != set(qarg2) or node_circuit.name != node_template.name ): continue # Check if the qubit, clbit configuration are compatible for a match, # also check if the operation are the same. if ( self._is_same_q_conf(node_circuit, node_template, qarg1) and self._is_same_c_conf(node_circuit, node_template, carg1) and self._is_same_op(node_circuit, node_template) ): # If there is a match the attributes are copied. circuit_matched_match = circuit_matched.copy() circuit_blocked_match = circuit_blocked.copy() template_matched_match = template_matched.copy() template_blocked_match = template_blocked.copy() matches_scenario_match = matches_scenario.copy() block_list = [] broken_matches_match = [] # Loop to check if the match is not connected, in this case # the successors matches are blocked and unmatched. for potential_block in self.template_dag_dep.successors(template_id): if not template_matched_match[potential_block]: template_blocked_match[potential_block] = True block_list.append(potential_block) for block_id in block_list: for succ_id in self.template_dag_dep.successors(block_id): template_blocked_match[succ_id] = True if template_matched_match[succ_id]: new_id = template_matched_match[succ_id][0] circuit_matched_match[new_id] = [] template_matched_match[succ_id] = [] broken_matches_match.append(succ_id) if broken_matches_match: global_broken.append(True) else: global_broken.append(False) new_matches_scenario_match = [ elem for elem in matches_scenario_match if elem[0] not in broken_matches_match ] condition = True for back_match in match_backward: if back_match not in new_matches_scenario_match: condition = False break # First option greedy match. if ([self.node_id_t, self.node_id_c] in new_matches_scenario_match) and ( condition or not match_backward ): template_matched_match[template_id] = [circuit_id] circuit_matched_match[circuit_id] = [template_id] new_matches_scenario_match.append([template_id, circuit_id]) new_matching_scenario = MatchingScenarios( circuit_matched_match, circuit_blocked_match, template_matched_match, template_blocked_match, new_matches_scenario_match, counter_scenario + 1, ) self.matching_list.append_scenario(new_matching_scenario) global_match = True if global_match: circuit_matched_block_s = circuit_matched.copy() circuit_blocked_block_s = circuit_blocked.copy() template_matched_block_s = template_matched.copy() template_blocked_block_s = template_blocked.copy() matches_scenario_block_s = matches_scenario.copy() circuit_blocked_block_s[circuit_id] = True broken_matches = [] # Second option, not a greedy match, block all successors (push the gate # to the right). for succ in self.circuit_dag_dep.get_node(circuit_id).successors: circuit_blocked_block_s[succ] = True if circuit_matched_block_s[succ]: broken_matches.append(succ) new_id = circuit_matched_block_s[succ][0] template_matched_block_s[new_id] = [] circuit_matched_block_s[succ] = [] new_matches_scenario_block_s = [ elem for elem in matches_scenario_block_s if elem[1] not in broken_matches ] condition_not_greedy = True for back_match in match_backward: if back_match not in new_matches_scenario_block_s: condition_not_greedy = False break if ([self.node_id_t, self.node_id_c] in new_matches_scenario_block_s) and ( condition_not_greedy or not match_backward ): new_matching_scenario = MatchingScenarios( circuit_matched_block_s, circuit_blocked_block_s, template_matched_block_s, template_blocked_block_s, new_matches_scenario_block_s, counter_scenario + 1, ) self.matching_list.append_scenario(new_matching_scenario) # Third option: if blocking the successors breaks a match, we consider # also the possibility to block all predecessors (push the gate to the left). if broken_matches and all(global_broken): circuit_matched_block_p = circuit_matched.copy() circuit_blocked_block_p = circuit_blocked.copy() template_matched_block_p = template_matched.copy() template_blocked_block_p = template_blocked.copy() matches_scenario_block_p = matches_scenario.copy() circuit_blocked_block_p[circuit_id] = True for pred in self.circuit_dag_dep.get_node(circuit_id).predecessors: circuit_blocked_block_p[pred] = True matching_scenario = MatchingScenarios( circuit_matched_block_p, circuit_blocked_block_p, template_matched_block_p, template_blocked_block_p, matches_scenario_block_p, counter_scenario + 1, ) self.matching_list.append_scenario(matching_scenario) # If there is no match then there are three options. if not global_match: circuit_blocked[circuit_id] = True following_matches = [] successors = self.circuit_dag_dep.get_node(circuit_id).successors for succ in successors: if circuit_matched[succ]: following_matches.append(succ) # First option, the circuit gate is not disturbing because there are no # following match and no predecessors. predecessors = self.circuit_dag_dep.get_node(circuit_id).predecessors if not predecessors or not following_matches: matching_scenario = MatchingScenarios( circuit_matched, circuit_blocked, template_matched, template_blocked, matches_scenario, counter_scenario + 1, ) self.matching_list.append_scenario(matching_scenario) else: circuit_matched_nomatch = circuit_matched.copy() circuit_blocked_nomatch = circuit_blocked.copy() template_matched_nomatch = template_matched.copy() template_blocked_nomatch = template_blocked.copy() matches_scenario_nomatch = matches_scenario.copy() # Second option, all predecessors are blocked (circuit gate is # moved to the left). for pred in predecessors: circuit_blocked[pred] = True matching_scenario = MatchingScenarios( circuit_matched, circuit_blocked, template_matched, template_blocked, matches_scenario, counter_scenario + 1, ) self.matching_list.append_scenario(matching_scenario) # Third option, all successors are blocked (circuit gate is # moved to the right). broken_matches = [] successors = self.circuit_dag_dep.get_node(circuit_id).successors for succ in successors: circuit_blocked_nomatch[succ] = True if circuit_matched_nomatch[succ]: broken_matches.append(succ) circuit_matched_nomatch[succ] = [] new_matches_scenario_nomatch = [ elem for elem in matches_scenario_nomatch if elem[1] not in broken_matches ] condition_block = True for back_match in match_backward: if back_match not in new_matches_scenario_nomatch: condition_block = False break if ([self.node_id_t, self.node_id_c] in matches_scenario_nomatch) and ( condition_block or not match_backward ): new_matching_scenario = MatchingScenarios( circuit_matched_nomatch, circuit_blocked_nomatch, template_matched_nomatch, template_blocked_nomatch, new_matches_scenario_nomatch, counter_scenario + 1, ) self.matching_list.append_scenario(new_matching_scenario) length = max(len(m.match) for m in match_store_list) # Store the matches with maximal length. for scenario in match_store_list: if (len(scenario.match) == length) and not any( scenario.match == x.match for x in self.match_final ): self.match_final.append(scenario)
qiskit/qiskit/transpiler/passes/optimization/template_matching/backward_match.py/0
{ "file_path": "qiskit/qiskit/transpiler/passes/optimization/template_matching/backward_match.py", "repo_id": "qiskit", "token_count": 14741 }
218
# 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. """Defines a swap strategy class.""" from __future__ import annotations from typing import Any import copy import numpy as np from qiskit.exceptions import QiskitError from qiskit.transpiler.coupling import CouplingMap class SwapStrategy: """A class representing swap strategies for coupling maps. A swap strategy is a tuple of swap layers to apply to the coupling map to route blocks of commuting two-qubit gates. Each swap layer is specified by a set of tuples which correspond to the edges of the coupling map that are swapped. At each swap layer SWAP gates are applied to the corresponding edges. These SWAP gates must be executable in parallel. This means that a qubit can only be present once in a swap layer. For example, the following swap layers represent the optimal swap strategy for a line with five qubits .. parsed-literal:: ( ((0, 1), (2, 3)), # Swap layer no. 1 ((1, 2), (3, 4)), # Swap layer no. 2 ((0, 1), (2, 3)), # Swap layer no. 3 ) This strategy is optimal in the sense that it reaches full qubit-connectivity in the least amount of swap gates. More generally, a swap strategy is optimal for a given block of commuting two-qubit gates and a given coupling map if it minimizes the number of gates applied when routing the commuting two-qubit gates to the coupling map. Finding the optimal swap strategy is a non-trivial problem but can be done for certain coupling maps such as a line coupling map. This class stores the permutations of the qubits resulting from the swap strategy. See https://arxiv.org/abs/2202.03459 for more details. """ def __init__( self, coupling_map: CouplingMap, swap_layers: tuple[tuple[tuple[int, int], ...], ...] ) -> None: """ Args: coupling_map: The coupling map the strategy is implemented for. swap_layers: The swap layers of the strategy, specified as tuple of swap layers. Each swap layer is a tuple of edges to which swaps are applied simultaneously. Each swap is specified as an edge which is a tuple of two integers. Raises: QiskitError: If the coupling map is not specified. QiskitError: if the swap strategy is not valid. A swap strategy is valid if all swap gates, specified as tuples, are contained in the edge set of the coupling map. A swap strategy is also invalid if a layer has multiple swaps on the same qubit. """ self._coupling_map = coupling_map self._num_vertices = coupling_map.size() self._swap_layers = swap_layers self._distance_matrix: np.ndarray | None = None self._possible_edges: set[tuple[int, int]] | None = None self._missing_couplings: set[tuple[int, int]] | None = None self._inverse_composed_permutation = {0: list(range(self._num_vertices))} edge_set = set(self._coupling_map.get_edges()) for i, layer in enumerate(self._swap_layers): for edge in layer: if edge not in edge_set: raise QiskitError( f"The {i}th swap layer contains the edge {edge} which is not " f"part of the underlying coupling map with {edge_set} edges." ) layer_qubits = [qubit for edge in layer for qubit in edge] if len(layer_qubits) != len(set(layer_qubits)): raise QiskitError(f"The {i}th swap layer contains a qubit with multiple swaps.") @classmethod def from_line(cls, line: list[int], num_swap_layers: int | None = None) -> "SwapStrategy": """Creates a swap strategy for a line graph with the specified number of SWAP layers. This SWAP strategy will use the full line if instructed to do so (i.e. num_variables is None or equal to num_vertices). If instructed otherwise then the first num_variables nodes of the line will be used in the swap strategy. Args: line: A line given as a list of nodes, e.g. ``[0, 2, 3, 4]``. num_swap_layers: Number of swap layers the swap manager should be initialized with. Returns: A swap strategy that reaches full connectivity on a linear coupling map. Raises: ValueError: If the ``num_swap_layers`` is negative. ValueError: If the ``line`` has less than 2 elements and no swap strategy can be applied. """ if len(line) < 2: raise ValueError(f"The line cannot have less than two elements, but is {line}") if num_swap_layers is None: num_swap_layers = len(line) - 2 elif num_swap_layers < 0: raise ValueError(f"Negative number {num_swap_layers} passed for number of swap layers.") swap_layer0 = tuple((line[i], line[i + 1]) for i in range(0, len(line) - 1, 2)) swap_layer1 = tuple((line[i], line[i + 1]) for i in range(1, len(line) - 1, 2)) base_layers = [swap_layer0, swap_layer1] swap_layers = tuple(base_layers[i % 2] for i in range(num_swap_layers)) couplings = [] for idx in range(len(line) - 1): couplings.append((line[idx], line[idx + 1])) couplings.append((line[idx + 1], line[idx])) return cls(coupling_map=CouplingMap(couplings), swap_layers=tuple(swap_layers)) def __len__(self) -> int: """Return the length of the strategy as the number of layers. Returns: The number of layers of the swap strategy. """ return len(self._swap_layers) def __repr__(self) -> str: """Representation of the swap strategy. Returns: The representation of the swap strategy. """ description = [f"{self.__class__.__name__} with swap layers:\n"] for layer in self._swap_layers: description.append(f"{layer},\n") description.append(f"on {self._coupling_map} coupling map.") description = "".join(description) return description def swap_layer(self, idx: int) -> list[tuple[int, int]]: """Return the layer of swaps at the given index. Args: idx: The index of the returned swap layer. Returns: A copy of the swap layer at ``idx`` to avoid any unintentional modification to the swap strategy. """ return list(self._swap_layers[idx]) @property def distance_matrix(self) -> np.ndarray: """A matrix describing when qubits become adjacent in the swap strategy. Returns: The distance matrix for the SWAP strategy as an array that cannot be written to. Here, the entry (i, j) corresponds to the number of SWAP layers that need to be applied to obtain a connection between physical qubits i and j. """ if self._distance_matrix is None: self._distance_matrix = np.full((self._num_vertices, self._num_vertices), -1, dtype=int) for i in range(self._num_vertices): self._distance_matrix[i, i] = 0 for i in range(len(self._swap_layers) + 1): for j, k in self.swapped_coupling_map(i).get_edges(): # This if ensures that the smallest distance is used. if self._distance_matrix[j, k] == -1: self._distance_matrix[j, k] = i self._distance_matrix[k, j] = i self._distance_matrix.setflags(write=False) return self._distance_matrix def new_connections(self, idx: int) -> list[set[int]]: """ Returns the new connections obtained after applying the SWAP layer specified by idx, i.e. a list of qubit pairs that are adjacent to one another after idx steps of the SWAP strategy. Args: idx: The index of the SWAP layer. 1 refers to the first SWAP layer whereas an ``idx`` of 0 will return the connections present in the original coupling map. Returns: A list of edges representing the new qubit connections. """ connections = [] for i in range(self._num_vertices): for j in range(i): if self.distance_matrix[i, j] == idx: connections.append({i, j}) return connections def _build_edges(self) -> set[tuple[int, int]]: """Build the possible edges that the swap strategy accommodates.""" possible_edges = set() for swap_layer_idx in range(len(self) + 1): for edge in self.swapped_coupling_map(swap_layer_idx).get_edges(): possible_edges.add(edge) possible_edges.add(edge[::-1]) return possible_edges @property def possible_edges(self) -> set[tuple[int, int]]: """Return the qubit connections that can be generated. Returns: The qubit connections that can be accommodated by the swap strategy. """ if self._possible_edges is None: self._possible_edges = self._build_edges() return self._possible_edges @property def missing_couplings(self) -> set[tuple[int, int]]: """Return the set of couplings that cannot be reached. Returns: The couplings that cannot be reached as a set of Tuples of int. Here, each int corresponds to a qubit in the coupling map. """ if self._missing_couplings is None: self._missing_couplings = set(zip(*(self.distance_matrix == -1).nonzero())) return self._missing_couplings def swapped_coupling_map(self, idx: int) -> CouplingMap: """Returns the coupling map after applying ``idx`` swap layers of strategy. Args: idx: The number of swap layers to apply. For idx = 0, the original coupling map is returned. Returns: The swapped coupling map. """ permutation = self.inverse_composed_permutation(idx) edges = [[permutation[i], permutation[j]] for i, j in self._coupling_map.get_edges()] return CouplingMap(couplinglist=edges) def apply_swap_layer( self, list_to_swap: list[Any], idx: int, inplace: bool = False ) -> list[Any]: """Permute the elements of ``list_to_swap`` based on layer indexed by ``idx``. Args: list_to_swap: The list of elements to swap. idx: The index of the swap layer to apply. inplace: A boolean which if set to True will modify the list inplace. By default this value is False. Returns: The list with swapped elements """ if inplace: x = list_to_swap else: x = copy.copy(list_to_swap) for i, j in self._swap_layers[idx]: x[i], x[j] = x[j], x[i] return x def inverse_composed_permutation(self, idx: int) -> list[int]: """ Returns the inversed composed permutation of all swap layers applied up to layer ``idx``. Permutations are represented by list of integers where the ith element corresponds to the mapping of i under the permutation. Args: idx: The number of swap layers to apply. Returns: The inversed permutation as a list of integer values. """ # Only compute the inverse permutation if it has not been computed before if idx not in self._inverse_composed_permutation: self._inverse_composed_permutation[idx] = self.apply_swap_layer( self.inverse_composed_permutation(idx - 1), idx - 1 ) return self._inverse_composed_permutation[idx]
qiskit/qiskit/transpiler/passes/routing/commuting_2q_gate_routing/swap_strategy.py/0
{ "file_path": "qiskit/qiskit/transpiler/passes/routing/commuting_2q_gate_routing/swap_strategy.py", "repo_id": "qiskit", "token_count": 5029 }
219
# This code is part of Qiskit. # # (C) Copyright IBM 2021, 2024. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Dynamical Decoupling insertion pass.""" import itertools import numpy as np from qiskit.circuit import Gate, Delay, Reset from qiskit.circuit.library.standard_gates import IGate, UGate, U3Gate from qiskit.dagcircuit import DAGOpNode, DAGInNode from qiskit.quantum_info.operators.predicates import matrix_equal from qiskit.synthesis.one_qubit import OneQubitEulerDecomposer from qiskit.transpiler.basepasses import TransformationPass from qiskit.transpiler.exceptions import TranspilerError from qiskit.transpiler.instruction_durations import InstructionDurations from qiskit.transpiler.passes.optimization import Optimize1qGates from qiskit.utils.deprecation import deprecate_func class DynamicalDecoupling(TransformationPass): """Dynamical decoupling insertion pass. This pass works on a scheduled, physical circuit. It scans the circuit for idle periods of time (i.e. those containing delay instructions) and inserts a DD sequence of gates in those spots. These gates amount to the identity, so do not alter the logical action of the circuit, but have the effect of mitigating decoherence in those idle periods. As a special case, the pass allows a length-1 sequence (e.g. [XGate()]). In this case the DD insertion happens only when the gate inverse can be absorbed into a neighboring gate in the circuit (so we would still be replacing Delay with something that is equivalent to the identity). This can be used, for instance, as a Hahn echo. This pass ensures that the inserted sequence preserves the circuit exactly (including global phase). .. plot:: :include-source: import numpy as np from qiskit.circuit import QuantumCircuit from qiskit.circuit.library import XGate from qiskit.transpiler import PassManager, InstructionDurations from qiskit.transpiler.passes import ALAPSchedule, DynamicalDecoupling from qiskit.visualization import timeline_drawer # Because the legacy passes do not propagate the scheduling information correctly, it is # necessary to run a no-op "re-schedule" before the output circuits can be drawn. def draw(circuit): from qiskit import transpile scheduled = transpile( circuit, optimization_level=0, instruction_durations=InstructionDurations(), scheduling_method="alap", ) return timeline_drawer(scheduled) circ = QuantumCircuit(4) circ.h(0) circ.cx(0, 1) circ.cx(1, 2) circ.cx(2, 3) circ.measure_all() durations = InstructionDurations( [("h", 0, 50), ("cx", [0, 1], 700), ("reset", None, 10), ("cx", [1, 2], 200), ("cx", [2, 3], 300), ("x", None, 50), ("measure", None, 1000)] ) # balanced X-X sequence on all qubits dd_sequence = [XGate(), XGate()] pm = PassManager([ALAPSchedule(durations), DynamicalDecoupling(durations, dd_sequence)]) circ_dd = pm.run(circ) draw(circ_dd) # Uhrig sequence on qubit 0 n = 8 dd_sequence = [XGate()] * n def uhrig_pulse_location(k): return np.sin(np.pi * (k + 1) / (2 * n + 2)) ** 2 spacing = [] for k in range(n): spacing.append(uhrig_pulse_location(k) - sum(spacing)) spacing.append(1 - sum(spacing)) pm = PassManager( [ ALAPSchedule(durations), DynamicalDecoupling(durations, dd_sequence, qubits=[0], spacing=spacing), ] ) circ_dd = pm.run(circ) draw(circ_dd) """ @deprecate_func( additional_msg=( "Instead, use :class:`~.PadDynamicalDecoupling`, which performs the same " "function but requires scheduling and alignment analysis passes to run prior to it." ), since="1.1.0", ) def __init__( self, durations, dd_sequence, qubits=None, spacing=None, skip_reset_qubits=True, target=None ): """Dynamical decoupling initializer. Args: durations (InstructionDurations): Durations of instructions to be used in scheduling. dd_sequence (list[Gate]): sequence of gates to apply in idle spots. qubits (list[int]): physical qubits on which to apply DD. If None, all qubits will undergo DD (when possible). spacing (list[float]): a list of spacings between the DD gates. The available slack will be divided according to this. The list length must be one more than the length of dd_sequence, and the elements must sum to 1. If None, a balanced spacing will be used [d/2, d, d, ..., d, d, d/2]. skip_reset_qubits (bool): if True, does not insert DD on idle periods that immediately follow initialized/reset qubits (as qubits in the ground state are less susceptible to decoherence). target (Target): The :class:`~.Target` representing the target backend, if both ``durations`` and this are specified then this argument will take precedence and ``durations`` will be ignored. """ super().__init__() self._durations = durations self._dd_sequence = dd_sequence self._qubits = qubits self._spacing = spacing self._skip_reset_qubits = skip_reset_qubits self._target = target if target is not None: self._durations = target.durations() for gate in dd_sequence: if gate.name not in target.operation_names: raise TranspilerError( f"{gate.name} in dd_sequence is not supported in the target" ) def run(self, dag): """Run the DynamicalDecoupling pass on dag. Args: dag (DAGCircuit): a scheduled DAG. Returns: DAGCircuit: equivalent circuit with delays interrupted by DD, where possible. Raises: TranspilerError: if the circuit is not mapped on physical qubits. """ if len(dag.qregs) != 1 or dag.qregs.get("q", None) is None: raise TranspilerError("DD runs on physical circuits only.") if dag.duration is None: raise TranspilerError("DD runs after circuit is scheduled.") durations = self._update_inst_durations(dag) num_pulses = len(self._dd_sequence) sequence_gphase = 0 if num_pulses != 1: if num_pulses % 2 != 0: raise TranspilerError("DD sequence must contain an even number of gates (or 1).") noop = np.eye(2) for gate in self._dd_sequence: noop = noop.dot(gate.to_matrix()) if not matrix_equal(noop, IGate().to_matrix(), ignore_phase=True): raise TranspilerError("The DD sequence does not make an identity operation.") sequence_gphase = np.angle(noop[0][0]) if self._qubits is None: self._qubits = set(range(dag.num_qubits())) else: self._qubits = set(self._qubits) if self._spacing: if sum(self._spacing) != 1 or any(a < 0 for a in self._spacing): raise TranspilerError( "The spacings must be given in terms of fractions " "of the slack period and sum to 1." ) else: # default to balanced spacing mid = 1 / num_pulses end = mid / 2 self._spacing = [end] + [mid] * (num_pulses - 1) + [end] for qarg in list(self._qubits): for gate in self._dd_sequence: if not self.__gate_supported(gate, qarg): self._qubits.discard(qarg) break index_sequence_duration_map = {} for physical_qubit in self._qubits: dd_sequence_duration = 0 for index, gate in enumerate(self._dd_sequence): gate = gate.to_mutable() self._dd_sequence[index] = gate gate.duration = durations.get(gate, physical_qubit) dd_sequence_duration += gate.duration index_sequence_duration_map[physical_qubit] = dd_sequence_duration new_dag = dag.copy_empty_like() for nd in dag.topological_op_nodes(): if not isinstance(nd.op, Delay): new_dag.apply_operation_back(nd.op, nd.qargs, nd.cargs, check=False) continue dag_qubit = nd.qargs[0] physical_qubit = dag.find_bit(dag_qubit).index if physical_qubit not in self._qubits: # skip unwanted qubits new_dag.apply_operation_back(nd.op, nd.qargs, nd.cargs, check=False) continue pred = next(dag.predecessors(nd)) succ = next(dag.successors(nd)) if self._skip_reset_qubits: # discount initial delays if isinstance(pred, DAGInNode) or isinstance(pred.op, Reset): new_dag.apply_operation_back(nd.op, nd.qargs, nd.cargs, check=False) continue dd_sequence_duration = index_sequence_duration_map[physical_qubit] slack = nd.op.duration - dd_sequence_duration if slack <= 0: # dd doesn't fit new_dag.apply_operation_back(nd.op, nd.qargs, nd.cargs, check=False) continue if num_pulses == 1: # special case of using a single gate for DD u_inv = self._dd_sequence[0].inverse().to_matrix() theta, phi, lam, phase = OneQubitEulerDecomposer().angles_and_phase(u_inv) # absorb the inverse into the successor (from left in circuit) if isinstance(succ, DAGOpNode) and isinstance(succ.op, (UGate, U3Gate)): theta_r, phi_r, lam_r = succ.op.params succ.op.params = Optimize1qGates.compose_u3( theta_r, phi_r, lam_r, theta, phi, lam ) sequence_gphase += phase # absorb the inverse into the predecessor (from right in circuit) elif isinstance(pred, DAGOpNode) and isinstance(pred.op, (UGate, U3Gate)): theta_l, phi_l, lam_l = pred.op.params pred.op.params = Optimize1qGates.compose_u3( theta, phi, lam, theta_l, phi_l, lam_l ) sequence_gphase += phase # don't do anything if there's no single-qubit gate to absorb the inverse else: new_dag.apply_operation_back(nd.op, nd.qargs, nd.cargs, check=False) continue # insert the actual DD sequence taus = [int(slack * a) for a in self._spacing] unused_slack = slack - sum(taus) # unused, due to rounding to int multiples of dt middle_index = int((len(taus) - 1) / 2) # arbitrary: redistribute to middle taus[middle_index] += unused_slack # now we add up to original delay duration for tau, gate in itertools.zip_longest(taus, self._dd_sequence): if tau > 0: new_dag.apply_operation_back(Delay(tau), [dag_qubit], check=False) if gate is not None: new_dag.apply_operation_back(gate, [dag_qubit], check=False) new_dag.global_phase = new_dag.global_phase + sequence_gphase return new_dag def _update_inst_durations(self, dag): """Update instruction durations with circuit information. If the dag contains gate calibrations and no instruction durations were provided through the target or as a standalone input, the circuit calibration durations will be used. The priority order for instruction durations is: target > standalone > circuit. """ circ_durations = InstructionDurations() if dag.calibrations: cal_durations = [] for gate, gate_cals in dag.calibrations.items(): for (qubits, parameters), schedule in gate_cals.items(): cal_durations.append((gate, qubits, parameters, schedule.duration)) circ_durations.update(cal_durations, circ_durations.dt) if self._durations is not None: circ_durations.update(self._durations, getattr(self._durations, "dt", None)) return circ_durations def __gate_supported(self, gate: Gate, qarg: int) -> bool: """A gate is supported on the qubit (qarg) or not.""" if self._target is None or self._target.instruction_supported(gate.name, qargs=(qarg,)): return True return False
qiskit/qiskit/transpiler/passes/scheduling/dynamical_decoupling.py/0
{ "file_path": "qiskit/qiskit/transpiler/passes/scheduling/dynamical_decoupling.py", "repo_id": "qiskit", "token_count": 6013 }
220
# 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. """ ==================================================================== Synthesis Plugins (:mod:`qiskit.transpiler.passes.synthesis.plugin`) ==================================================================== .. currentmodule:: qiskit.transpiler.passes.synthesis.plugin This module defines the plugin interfaces for the synthesis transpiler passes in Qiskit. These provide a hook point for external python packages to implement their own synthesis techniques and have them seamlessly exposed as opt-in options to users when they run :func:`~qiskit.compiler.transpile`. The plugin interfaces are built using setuptools `entry points <https://setuptools.readthedocs.io/en/latest/userguide/entry_point.html>`__ which enable packages external to qiskit to advertise they include a synthesis plugin. See :mod:`qiskit.transpiler.preset_passmanagers.plugin` for details on how to write plugins for transpiler stages. Synthesis Plugin API ==================== Unitary Synthesis Plugin API ---------------------------- .. autosummary:: :toctree: ../stubs/ UnitarySynthesisPlugin UnitarySynthesisPluginManager unitary_synthesis_plugin_names High-Level Synthesis Plugin API ------------------------------- .. autosummary:: :toctree: ../stubs/ HighLevelSynthesisPlugin HighLevelSynthesisPluginManager high_level_synthesis_plugin_names Writing Plugins =============== Unitary Synthesis Plugins ------------------------- To write a unitary synthesis plugin there are 2 main steps. The first step is to create a subclass of the abstract plugin class: :class:`~qiskit.transpiler.passes.synthesis.plugin.UnitarySynthesisPlugin`. The plugin class defines the interface and contract for unitary synthesis plugins. The primary method is :meth:`~qiskit.transpiler.passes.synthesis.plugin.UnitarySynthesisPlugin.run` which takes in a single positional argument, a unitary matrix as a numpy array, and is expected to return a :class:`~qiskit.dagcircuit.DAGCircuit` object representing the synthesized circuit from that unitary matrix. Then to inform the Qiskit transpiler about what information is necessary for the pass there are several required property methods that need to be implemented such as ``supports_basis_gates`` and ``supports_coupling_map`` depending on whether the plugin supports and/or requires that input to perform synthesis. For the full details refer to the :class:`~qiskit.transpiler.passes.synthesis.plugin.UnitarySynthesisPlugin` documentation for all the required fields. An example plugin class would look something like:: from qiskit.transpiler.passes.synthesis import plugin from qiskit_plugin_pkg.synthesis import generate_dag_circuit_from_matrix class SpecialUnitarySynthesis(plugin.UnitarySynthesisPlugin): @property def supports_basis_gates(self): return True @property def supports_coupling_map(self): return False @property def supports_natural_direction(self): return False @property def supports_pulse_optimize(self): return False @property def supports_gate_lengths(self): return False @property def supports_gate_errors(self): return False @property def supports_gate_lengths_by_qubit(self): return False @property def supports_gate_errors_by_qubit(self): return False @property def min_qubits(self): return None @property def max_qubits(self): return None @property def supported_bases(self): return None def run(self, unitary, **options): basis_gates = options['basis_gates'] dag_circuit = generate_dag_circuit_from_matrix(unitary, basis_gates) return dag_circuit If for some reason the available inputs to the :meth:`~qiskit.transpiler.passes.synthesis.plugin.UnitarySynthesisPlugin.run` method are insufficient please open an issue and we can discuss expanding the plugin interface with new opt-in inputs that can be added in a backwards compatible manner for future releases. Do note though that this plugin interface is considered stable and guaranteed to not change in a breaking manner. If changes are needed (for example to expand the available optional input options) it will be done in a way that will **not** require changes from existing plugins. .. note:: All methods prefixed with ``supports_`` are reserved on a ``UnitarySynthesisPlugin`` derived class for part of the interface. You should not define any custom ``supports_*`` methods on a subclass that are not defined in the abstract class. The second step is to expose the :class:`~qiskit.transpiler.passes.synthesis.plugin.UnitarySynthesisPlugin` as a setuptools entry point in the package metadata. This is done by simply adding an ``entry-points`` table in ``pyproject.toml`` for the plugin package with the necessary entry points under the ``qiskit.unitary_synthesis`` namespace. For example: .. code-block:: toml [project.entry-points."qiskit.unitary_synthesis"] "special" = "qiskit_plugin_pkg.module.plugin:SpecialUnitarySynthesis" There isn't a limit to the number of plugins a single package can include as long as each plugin has a unique name. So a single package can expose multiple plugins if necessary. The name ``default`` is used by Qiskit itself and can't be used in a plugin. Unitary Synthesis Plugin Configuration '''''''''''''''''''''''''''''''''''''' For some unitary synthesis plugins that expose multiple options and tunables the plugin interface has an option for users to provide a free form configuration dictionary. This will be passed through to the ``run()`` method as the ``options`` kwarg. If your plugin has these configuration options you should clearly document how a user should specify these configuration options and how they're used as it's a free form field. High-Level Synthesis Plugins ---------------------------- Writing a high-level synthesis plugin is conceptually similar to writing a unitary synthesis plugin. The first step is to create a subclass of the abstract plugin class: :class:`~qiskit.transpiler.passes.synthesis.plugin.HighLevelSynthesisPlugin`, which defines the interface and contract for high-level synthesis plugins. The primary method is :meth:`~qiskit.transpiler.passes.synthesis.plugin.HighLevelSynthesisPlugin.run`. The positional argument ``high_level_object`` specifies the "higher-level-object" to be synthesized, which is any object of type :class:`~qiskit.circuit.Operation` (including, for example, :class:`~qiskit.circuit.library.generalized_gates.linear_function.LinearFunction` or :class:`~qiskit.quantum_info.operators.symplectic.clifford.Clifford`). The keyword argument ``target`` specifies the target backend, allowing the plugin to access all target-specific information, such as the coupling map, the supported gate set, and so on. The keyword argument ``coupling_map`` only specifies the coupling map, and is only used when ``target`` is not specified. The keyword argument ``qubits`` specifies the list of qubits over which the higher-level-object is defined, in case the synthesis is done on the physical circuit. The value of ``None`` indicates that the layout has not yet been chosen and the physical qubits in the target or coupling map that this operation is operating on has not yet been determined. Additionally, plugin-specific options and tunables can be specified via ``options``, which is a free form configuration dictionary. If your plugin has these configuration options you should clearly document how a user should specify these configuration options and how they're used as it's a free form field. The method :meth:`~qiskit.transpiler.passes.synthesis.plugin.HighLevelSynthesisPlugin.run` is expected to return a :class:`~qiskit.circuit.QuantumCircuit` object representing the synthesized circuit from that higher-level-object. It is also allowed to return ``None`` representing that the synthesis method is unable to synthesize the given higher-level-object. The actual synthesis of higher-level objects is performed by :class:`~qiskit.transpiler.passes.synthesis.high_level_synthesis.HighLevelSynthesis` transpiler pass. For the full details refer to the :class:`~qiskit.transpiler.passes.synthesis.plugin.HighLevelSynthesisPlugin` documentation for all the required fields. An example plugin class would look something like:: from qiskit.transpiler.passes.synthesis.plugin import HighLevelSynthesisPlugin from qiskit.synthesis.clifford import synth_clifford_bm class SpecialSynthesisClifford(HighLevelSynthesisPlugin): def run(self, high_level_object, coupling_map=None, target=None, qubits=None, **options): if higher_level_object.num_qubits <= 3: return synth_clifford_bm(high_level_object) else: return None The above example creates a plugin to synthesize objects of type :class:`.Clifford` that have at most 3 qubits, using the method ``synth_clifford_bm``. The second step is to expose the :class:`~qiskit.transpiler.passes.synthesis.plugin.HighLevelSynthesisPlugin` as a setuptools entry point in the package metadata. This is done by adding an ``entry-points`` table in ``pyproject.toml`` for the plugin package with the necessary entry points under the ``qiskit.synthesis`` namespace. For example: .. code-block:: toml [project.entry-points."qiskit.synthesis"] "clifford.special" = "qiskit_plugin_pkg.module.plugin:SpecialSynthesisClifford" The ``name`` consists of two parts separated by dot ".": the name of the type of :class:`~qiskit.circuit.Operation` to which the synthesis plugin applies (``clifford``), and the name of the plugin (``special``). There isn't a limit to the number of plugins a single package can include as long as each plugin has a unique name. Using Plugins ============= Unitary Synthesis Plugins ------------------------- To use a plugin all you need to do is install the package that includes a synthesis plugin. Then Qiskit will automatically discover the installed plugins and expose them as valid options for the appropriate :func:`~qiskit.compiler.transpile` kwargs and pass constructors. If there are any installed plugins which can't be loaded/imported this will be logged to Python logging. To get the installed list of installed unitary synthesis plugins you can use the :func:`qiskit.transpiler.passes.synthesis.plugin.unitary_synthesis_plugin_names` function. .. _using-high-level-synthesis-plugins: High-level Synthesis Plugins ---------------------------- To use a high-level synthesis plugin, you first instantiate an :class:`.HLSConfig` to store the names of the plugins to use for various high-level objects. For example:: HLSConfig(permutation=["acg"], clifford=["layers"], linear_function=["pmh"]) creates a high-level synthesis configuration that uses the ``acg`` plugin for synthesizing :class:`.PermutationGate` objects, the ``layers`` plugin for synthesizing :class:`.Clifford` objects, and the ``pmh`` plugin for synthesizing :class:`.LinearFunction` objects. The keyword arguments are the :attr:`.Operation.name` fields of the relevant objects. For example, all :class:`.Clifford` operations have the :attr:`~.Operation.name` ``clifford``, so this is used as the keyword argument. You can specify any keyword argument here that you have installed plugins to handle, including custom user objects if you have plugins installed for them. See :class:`.HLSConfig` for more detail on alternate formats for configuring the plugins within each argument. For each high-level object, the list of given plugins are tried in sequence until one of them succeeds (in the example above, each list only contains a single plugin). In addition to specifying a plugin by its name, you can instead pass a ``(name, options)`` tuple, where the second element of the tuple is a dictionary containing options for the plugin. Once created you then pass this :class:`.HLSConfig` object into the ``hls_config`` argument for :func:`.transpile` or :func:`.generate_preset_pass_manager` which will use the specified plugins as part of the larger compilation workflow. To get a list of installed high level synthesis plugins for any given :attr:`.Operation.name`, you can use the :func:`.high_level_synthesis_plugin_names` function, passing the desired ``name`` as the argument:: high_level_synthesis_plugin_names("clifford") will return a list of all the installed Clifford synthesis plugins. Available Plugins ================= High-level synthesis plugins that are directly available in Qiskit include plugins for synthesizing :class:`.Clifford` objects, :class:`.LinearFunction` objects, and :class:`.PermutationGate` objects. Some of these plugins implicitly target all-to-all connectivity. This is not a practical limitation since :class:`~qiskit.transpiler.passes.synthesis.high_level_synthesis.HighLevelSynthesis` typically runs before layout and routing, which will ensure that the final circuit adheres to the device connectivity by inserting additional SWAP gates. A good example is the permutation synthesis plugin ``ACGSynthesisPermutation`` which can synthesize any permutation with at most 2 layers of SWAP gates. On the other hand, some plugins implicitly target linear connectivity. Typically, the synthesizing circuits have larger depth and the number of gates, however no additional SWAP gates would be inserted if the following layout pass chose a consecutive line of qubits inside the topology of the device. A good example of this is the permutation synthesis plugin ``KMSSynthesisPermutation`` which can synthesize any permutation of ``n`` qubits in depth ``n``. Typically, it is difficult to know in advance which of the two approaches: synthesizing circuits for all-to-all connectivity and inserting SWAP gates vs. synthesizing circuits for linear connectivity and inserting less or no SWAP gates lead a better final circuit, so it likely makes sense to try both and see which gives better results. Finally, some plugins can target a given connectivity, and hence should be run after the layout is set. In this case the synthesized circuit automatically adheres to the topology of the device. A good example of this is the permutation synthesis plugin ``TokenSwapperSynthesisPermutation`` which is able to synthesize arbitrary permutations with respect to arbitrary coupling maps. For more detail, please refer to description of each individual plugin. Below are the synthesis plugin classes available in Qiskit. These classes should not be used directly, but instead should be used through the plugin interface documented above. The classes are listed here to ease finding the documentation for each of the included plugins and to ease the comparison between different synthesis methods for a given object. Unitary Synthesis Plugins ------------------------- .. automodule:: qiskit.transpiler.passes.synthesis.aqc_plugin :no-members: :no-inherited-members: :no-special-members: .. automodule:: qiskit.transpiler.passes.synthesis.unitary_synthesis :no-members: :no-inherited-members: :no-special-members: .. automodule:: qiskit.transpiler.passes.synthesis.solovay_kitaev_synthesis :no-members: :no-inherited-members: :no-special-members: High Level Synthesis -------------------- For each high-level object we give a table that lists all of its plugins available directly in Qiskit. We include the name of the plugin, the class of the plugin, the targeted connectivity map and optionally additional information. Recall the plugins should be used via the previously described :class:`.HLSConfig`, for example:: HLSConfig(permutation=["kms"]) creates a high-level synthesis configuration that uses the ``kms`` plugin for synthesizing :class:`.PermutationGate` objects -- i.e. those with ``name = "permutation"``. In this case, the plugin name is "kms", the plugin class is :class:`~.KMSSynthesisPermutation`. This particular synthesis algorithm created a circuit adhering to the linear nearest-neighbor connectivity. .. automodule:: qiskit.transpiler.passes.synthesis.hls_plugins :no-members: :no-inherited-members: :no-special-members: """ import abc from typing import List import stevedore class UnitarySynthesisPlugin(abc.ABC): """Abstract unitary synthesis plugin class This abstract class defines the interface for unitary synthesis plugins. """ @property @abc.abstractmethod def max_qubits(self): """Return the maximum number of qubits the unitary synthesis plugin supports. If the size of the unitary to be synthesized exceeds this value the ``default`` plugin will be used. If there is no upper bound return ``None`` and all unitaries (``>= min_qubits`` if it's defined) will be passed to this plugin when it's enabled. """ pass @property @abc.abstractmethod def min_qubits(self): """Return the minimum number of qubits the unitary synthesis plugin supports. If the size of the unitary to be synthesized is below this value the ``default`` plugin will be used. If there is no lower bound return ``None`` and all unitaries (``<= max_qubits`` if it's defined) will be passed to this plugin when it's enabled. """ pass @property @abc.abstractmethod def supports_basis_gates(self): """Return whether the plugin supports taking ``basis_gates`` If this returns ``True`` the plugin's ``run()`` method will be passed a ``basis_gates`` kwarg with a list of gate names the target backend supports. For example, ``['sx', 'x', 'cx', 'id', 'rz']``.""" pass @property @abc.abstractmethod def supports_coupling_map(self): """Return whether the plugin supports taking ``coupling_map`` If this returns ``True`` the plugin's ``run()`` method will receive one kwarg ``coupling_map``. The ``coupling_map`` kwarg will be set to a tuple with the first element being a :class:`~qiskit.transpiler.CouplingMap` object representing the qubit connectivity of the target backend, the second element will be a list of integers that represent the qubit indices in the coupling map that unitary is on. Note that if the target backend doesn't have a coupling map set, the ``coupling_map`` kwarg's value will be ``(None, qubit_indices)``. """ pass @property @abc.abstractmethod def supports_natural_direction(self): """Return whether the plugin supports a toggle for considering directionality of 2-qubit gates as ``natural_direction``. Refer to the documentation for :class:`~qiskit.transpiler.passes.UnitarySynthesis` for the possible values and meaning of these values. """ pass @property @abc.abstractmethod def supports_pulse_optimize(self): """Return whether the plugin supports a toggle to optimize pulses during synthesis as ``pulse_optimize``. Refer to the documentation for :class:`~qiskit.transpiler.passes.UnitarySynthesis` for the possible values and meaning of these values. """ pass @property def supports_gate_lengths_by_qubit(self): """Return whether the plugin supports taking ``gate_lengths_by_qubit`` This differs from ``supports_gate_lengths``/``gate_lengths`` by using a different view of the same data. Instead of being keyed by gate name this is keyed by qubit and uses :class:`~.Gate` instances to represent gates (instead of gate names) ``gate_lengths_by_qubit`` will be a dictionary in the form of ``{(qubits,): [Gate, length]}``. For example:: { (0,): [SXGate(): 0.0006149355812506126, RZGate(): 0.0], (0, 1): [CXGate(): 0.012012477900732316] } where the ``length`` value is in units of seconds. Do note that this dictionary might not be complete or could be empty as it depends on the target backend reporting gate lengths on every gate for each qubit. This defaults to False """ return False @property def supports_gate_errors_by_qubit(self): """Return whether the plugin supports taking ``gate_errors_by_qubit`` This differs from ``supports_gate_errors``/``gate_errors`` by using a different view of the same data. Instead of being keyed by gate name this is keyed by qubit and uses :class:`~.Gate` instances to represent gates (instead of gate names). ``gate_errors_by_qubit`` will be a dictionary in the form of ``{(qubits,): [Gate, error]}``. For example:: { (0,): [SXGate(): 0.0006149355812506126, RZGate(): 0.0], (0, 1): [CXGate(): 0.012012477900732316] } Do note that this dictionary might not be complete or could be empty as it depends on the target backend reporting gate errors on every gate for each qubit. The gate error rates reported in ``gate_errors`` are provided by the target device ``Backend`` object and the exact meaning might be different depending on the backend. This defaults to False """ return False @property @abc.abstractmethod def supports_gate_lengths(self): """Return whether the plugin supports taking ``gate_lengths`` ``gate_lengths`` will be a dictionary in the form of ``{gate_name: {(qubit_1, qubit_2): length}}``. For example:: { 'sx': {(0,): 0.0006149355812506126, (1,): 0.0006149355812506126}, 'cx': {(0, 1): 0.012012477900732316, (1, 0): 5.191111111111111e-07} } where the ``length`` value is in units of seconds. Do note that this dictionary might not be complete or could be empty as it depends on the target backend reporting gate lengths on every gate for each qubit. """ pass @property @abc.abstractmethod def supports_gate_errors(self): """Return whether the plugin supports taking ``gate_errors`` ``gate_errors`` will be a dictionary in the form of ``{gate_name: {(qubit_1, qubit_2): error}}``. For example:: { 'sx': {(0,): 0.0006149355812506126, (1,): 0.0006149355812506126}, 'cx': {(0, 1): 0.012012477900732316, (1, 0): 5.191111111111111e-07} } Do note that this dictionary might not be complete or could be empty as it depends on the target backend reporting gate errors on every gate for each qubit. The gate error rates reported in ``gate_errors`` are provided by the target device ``Backend`` object and the exact meaning might be different depending on the backend. """ pass @property @abc.abstractmethod def supported_bases(self): """Returns a dictionary of supported bases for synthesis This is expected to return a dictionary where the key is a string basis and the value is a list of gate names that the basis works in. If the synthesis method doesn't support multiple bases this should return ``None``. For example:: { "XZX": ["rz", "rx"], "XYX": ["rx", "ry"], } If a dictionary is returned by this method the run kwargs will be passed a parameter ``matched_basis`` which contains a list of the basis strings (i.e. keys in the dictionary) which match the target basis gate set for the transpilation. If no entry in the dictionary matches the target basis gate set then the ``matched_basis`` kwarg will be set to an empty list, and a plugin can choose how to deal with the target basis gate set not matching the plugin's capabilities. """ pass @property def supports_target(self): """Whether the plugin supports taking ``target`` as an option ``target`` will be a :class:`~.Target` object representing the target device for the output of the synthesis pass. By default this will be ``False`` since the plugin interface predates the :class:`~.Target` class. If a plugin returns ``True`` for this attribute, it is expected that the plugin will use the :class:`~.Target` instead of the values passed if any of ``supports_gate_lengths``, ``supports_gate_errors``, ``supports_coupling_map``, and ``supports_basis_gates`` are set (although ideally all those parameters should contain duplicate information). """ return False @abc.abstractmethod def run(self, unitary, **options): """Run synthesis for the given unitary matrix Args: unitary (numpy.ndarray): The unitary matrix to synthesize to a :class:`~qiskit.dagcircuit.DAGCircuit` object options: The optional kwargs that are passed based on the output the ``support_*`` methods on the class. Refer to the documentation for these methods on :class:`~qiskit.transpiler.passes.synthesis.plugin.UnitarySynthesisPlugin` to see what the keys and values are. Returns: DAGCircuit: The dag circuit representation of the unitary. Alternatively, you can return a tuple of the form ``(dag, wires)`` where ``dag`` is the dag circuit representation of the circuit representation of the unitary and ``wires`` is the mapping wires to use for :meth:`qiskit.dagcircuit.DAGCircuit.substitute_node_with_dag`. If you return a tuple and ``wires`` is ``None`` this will behave just as if only a :class:`~qiskit.dagcircuit.DAGCircuit` was returned. Additionally if this returns ``None`` no substitution will be made. """ pass class UnitarySynthesisPluginManager: """Unitary Synthesis plugin manager class This class tracks the installed plugins, it has a single property, ``ext_plugins`` which contains a list of stevedore plugin objects. """ def __init__(self): self.ext_plugins = stevedore.ExtensionManager( "qiskit.unitary_synthesis", invoke_on_load=True, propagate_map_exceptions=True ) def unitary_synthesis_plugin_names(): """Return a list of installed unitary synthesis plugin names Returns: list: A list of the installed unitary synthesis plugin names. The plugin names are valid values for the :func:`~qiskit.compiler.transpile` kwarg ``unitary_synthesis_method``. """ # NOTE: This is not a shared global instance to avoid an import cycle # at load time for the default plugin. plugins = UnitarySynthesisPluginManager() return plugins.ext_plugins.names() class HighLevelSynthesisPlugin(abc.ABC): """Abstract high-level synthesis plugin class. This abstract class defines the interface for high-level synthesis plugins. """ @abc.abstractmethod def run(self, high_level_object, coupling_map=None, target=None, qubits=None, **options): """Run synthesis for the given Operation. Args: high_level_object (Operation): The Operation to synthesize to a :class:`~qiskit.dagcircuit.DAGCircuit` object. coupling_map (CouplingMap): The coupling map of the backend in case synthesis is done on a physical circuit. target (Target): A target representing the target backend. qubits (list): List of qubits over which the operation is defined in case synthesis is done on a physical circuit. options: Additional method-specific optional kwargs. Returns: QuantumCircuit: The quantum circuit representation of the Operation when successful, and ``None`` otherwise. """ pass class HighLevelSynthesisPluginManager: """Class tracking the installed high-level-synthesis plugins.""" def __init__(self): self.plugins = stevedore.ExtensionManager( "qiskit.synthesis", invoke_on_load=True, propagate_map_exceptions=True ) # The registered plugin names should be of the form <OperationName.SynthesisMethodName>. # Create a dict, mapping <OperationName> to the list of its <SynthesisMethodName>s. self.plugins_by_op = {} for plugin_name in self.plugins.names(): op_name, method_name = plugin_name.split(".") if op_name not in self.plugins_by_op: self.plugins_by_op[op_name] = [] self.plugins_by_op[op_name].append(method_name) def method_names(self, op_name): """Returns plugin methods for op_name.""" if op_name in self.plugins_by_op: return self.plugins_by_op[op_name] else: return [] def method(self, op_name, method_name): """Returns the plugin for ``op_name`` and ``method_name``.""" plugin_name = op_name + "." + method_name return self.plugins[plugin_name].obj def high_level_synthesis_plugin_names(op_name: str) -> List[str]: """Return a list of plugin names installed for a given high level object name Args: op_name: The operation name to find the installed plugins for. For example, if you provide ``"clifford"`` as the input it will find all the installed clifford synthesis plugins that can synthesize :class:`.Clifford` objects. The name refers to the :attr:`.Operation.name` attribute of the relevant objects. Returns: A list of installed plugin names for the specified high level operation """ # NOTE: This is not a shared global instance to avoid an import cycle # at load time for the default plugins. plugin_manager = HighLevelSynthesisPluginManager() return plugin_manager.method_names(op_name)
qiskit/qiskit/transpiler/passes/synthesis/plugin.py/0
{ "file_path": "qiskit/qiskit/transpiler/passes/synthesis/plugin.py", "repo_id": "qiskit", "token_count": 10086 }
221
# 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. """Check if all gates in the DAGCircuit are in the specified basis gates.""" from qiskit.converters import circuit_to_dag from qiskit.transpiler.basepasses import AnalysisPass class GatesInBasis(AnalysisPass): """Check if all gates in a DAG are in a given set of gates""" def __init__(self, basis_gates=None, target=None): """Initialize the GatesInBasis pass. Args: basis_gates (list): The list of strings representing the set of basis gates. target (Target): The target representing the backend. If specified this will be used instead of the ``basis_gates`` parameter """ super().__init__() self._basis_gates = None if basis_gates is not None: self._basis_gates = set(basis_gates).union( {"measure", "reset", "barrier", "snapshot", "delay", "store"} ) self._target = target def run(self, dag): """Run the GatesInBasis pass on `dag`.""" if self._basis_gates is None and self._target is None: self.property_set["all_gates_in_basis"] = True return gates_out_of_basis = False if self._target is not None: def _visit_target(dag, wire_map): for gate in dag.op_nodes(): # Barrier and store are assumed universal and supported by all backends if gate.name in ("barrier", "store"): continue if not self._target.instruction_supported( gate.name, tuple(wire_map[bit] for bit in gate.qargs) ): return True # Control-flow ops still need to be supported, so don't skip them in the # previous checks. if gate.is_control_flow(): for block in gate.op.blocks: inner_wire_map = { inner: wire_map[outer] for outer, inner in zip(gate.qargs, block.qubits) } if _visit_target(circuit_to_dag(block), inner_wire_map): return True return False qubit_map = {qubit: index for index, qubit in enumerate(dag.qubits)} gates_out_of_basis = _visit_target(dag, qubit_map) else: for gate in dag.count_ops(recurse=True): if gate not in self._basis_gates: gates_out_of_basis = True break self.property_set["all_gates_in_basis"] = not gates_out_of_basis
qiskit/qiskit/transpiler/passes/utils/gates_basis.py/0
{ "file_path": "qiskit/qiskit/transpiler/passes/utils/gates_basis.py", "repo_id": "qiskit", "token_count": 1504 }
222
# 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. """ ======================================================================================= Transpiler Stage Plugin Interface (:mod:`qiskit.transpiler.preset_passmanagers.plugin`) ======================================================================================= .. currentmodule:: qiskit.transpiler.preset_passmanagers.plugin This module defines the plugin interface for providing custom stage implementations for the preset pass managers and the :func:`~.transpile` function. This enables external Python packages to provide :class:`~.PassManager` objects that can be used for each named stage. The plugin interfaces are built using setuptools `entry points <https://setuptools.readthedocs.io/en/latest/userguide/entry_point.html>`__ which enable packages external to Qiskit to advertise they include a transpiler stage(s). For details on how to instead write plugins for transpiler synthesis methods, see :mod:`qiskit.transpiler.passes.synthesis.plugin`. .. _stage_table: Plugin Stages ============= Currently, there are 6 stages in the preset pass managers, all of which actively load external plugins via corresponding entry points. .. list-table:: Stages :header-rows: 1 * - Stage Name - Entry Point - Reserved Names - Description and expectations * - ``init`` - ``qiskit.transpiler.init`` - ``default`` - This stage runs first and is typically used for any initial logical optimization. Because most layout and routing algorithms are only designed to work with 1 and 2 qubit gates, this stage is also used to translate any gates that operate on more than 2 qubits into gates that only operate on 1 or 2 qubits. * - ``layout`` - ``qiskit.transpiler.layout`` - ``trivial``, ``dense``, ``sabre``, ``default`` - The output from this stage is expected to have the ``layout`` property set field set with a :class:`~.Layout` object. Additionally, the circuit is typically expected to be embedded so that it is expanded to include all qubits and the :class:`~.ApplyLayout` pass is expected to be run to apply the layout. The embedding of the :class:`~.Layout` can be generated with :func:`~.generate_embed_passmanager`. * - ``routing`` - ``qiskit.transpiler.routing`` - ``basic``, ``stochastic``, ``lookahead``, ``sabre`` - The output from this stage is expected to have the circuit match the connectivity constraints of the target backend. This does not necessarily need to match the directionality of the edges in the target as a later stage typically will adjust directional gates to match that constraint (but there is no penalty for doing that in the ``routing`` stage). The output of this stage is also expected to have the ``final_layout`` property set field set with a :class:`~.Layout` object that maps the :class:`.Qubit` to the output final position of that qubit in the circuit. If there is an existing ``final_layout`` entry in the property set (such as might be set by an optimization pass that introduces a permutation) it is expected that the final layout will be the composition of the two layouts (this can be computed using :meth:`.DAGCircuit.compose`, for example: ``second_final_layout.compose(first_final_layout, dag.qubits)``). * - ``translation`` - ``qiskit.transpiler.translation`` - ``translator``, ``synthesis``, ``unroller`` - The output of this stage is expected to have every operation be a native instruction on the target backend. * - ``optimization`` - ``qiskit.transpiler.optimization`` - ``default`` - This stage is expected to perform optimization and simplification. The constraints from earlier stages still apply to the output of this stage. After the ``optimization`` stage is run we expect the circuit to still be executable on the target. * - ``scheduling`` - ``qiskit.transpiler.scheduling`` - ``alap``, ``asap``, ``default`` - This is the last stage run and it is expected to output a scheduled circuit such that all idle periods in the circuit are marked by explicit :class:`~qiskit.circuit.Delay` instructions. Writing Plugins =============== To write a pass manager stage plugin there are 2 main steps. The first step is to create a subclass of the abstract plugin class :class:`~.PassManagerStagePlugin` which is used to define how the :class:`~.PassManager` for the stage will be constructed. For example, to create a ``layout`` stage plugin that just runs :class:`~.VF2Layout` (with increasing amount of trials, depending on the optimization level) and falls back to using :class:`~.TrivialLayout` if :class:`~VF2Layout` is unable to find a perfect layout:: from qiskit.transpiler.preset_passmanagers.plugin import PassManagerStagePlugin from qiskit.transpiler.preset_passmanagers import common from qiskit.transpiler import PassManager from qiskit.transpiler.passes import VF2Layout, TrivialLayout from qiskit.transpiler.passes.layout.vf2_layout import VF2LayoutStopReason def _vf2_match_not_found(property_set): return property_set["layout"] is None or ( property_set["VF2Layout_stop_reason"] is not None and property_set["VF2Layout_stop_reason"] is not VF2LayoutStopReason.SOLUTION_FOUND class VF2LayoutPlugin(PassManagerStagePlugin): def pass_manager(self, pass_manager_config, optimization_level): layout_pm = PassManager( [ VF2Layout( coupling_map=pass_manager_config.coupling_map, properties=pass_manager_config.backend_properties, max_trials=optimization_level * 10 + 1 target=pass_manager_config.target ) ] ) layout_pm.append( TrivialLayout(pass_manager_config.coupling_map), condition=_vf2_match_not_found, ) layout_pm += common.generate_embed_passmanager(pass_manager_config.coupling_map) return layout_pm The second step is to expose the :class:`~.PassManagerStagePlugin` subclass as a setuptools entry point in the package metadata. This can be done an ``entry-points`` table in ``pyproject.toml`` for the plugin package with the necessary entry points under the appropriate namespace for the stage your plugin is for. You can see the list of stages, entry points, and expectations from the stage in :ref:`stage_table`. For example, continuing from the example plugin above:: .. code-block:: toml [project.entry-points."qiskit.transpiler.layout"] "vf2" = "qiskit_plugin_pkg.module.plugin:VF2LayoutPlugin" There isn't a limit to the number of plugins a single package can include as long as each plugin has a unique name. So a single package can expose multiple plugins if necessary. Refer to :ref:`stage_table` for a list of reserved names for each stage. Plugin API ========== .. autosummary:: :toctree: ../stubs/ PassManagerStagePlugin PassManagerStagePluginManager .. autofunction:: list_stage_plugins .. autofunction:: passmanager_stage_plugins """ import abc from typing import List, Optional, Dict import stevedore from qiskit.transpiler.passmanager import PassManager from qiskit.transpiler.exceptions import TranspilerError from qiskit.transpiler.passmanager_config import PassManagerConfig class PassManagerStagePlugin(abc.ABC): """A ``PassManagerStagePlugin`` is a plugin interface object for using custom stages in :func:`~.transpile`. A ``PassManagerStagePlugin`` object can be added to an external package and integrated into the :func:`~.transpile` function with an entry point. This will enable users to use the output of :meth:`.pass_manager` to implement a stage in the compilation process. """ @abc.abstractmethod def pass_manager( self, pass_manager_config: PassManagerConfig, optimization_level: Optional[int] = None ) -> PassManager: """This method is designed to return a :class:`~.PassManager` for the stage this implements Args: pass_manager_config: A configuration object that defines all the target device specifications and any user specified options to :func:`~.transpile` or :func:`~.generate_preset_pass_manager` optimization_level: The optimization level of the transpilation, if set this should be used to set values for any tunable parameters to trade off runtime for potential optimization. Valid values should be ``0``, ``1``, ``2``, or ``3`` and the higher the number the more optimization is expected. """ pass class PassManagerStagePluginManager: """Manager class for preset pass manager stage plugins.""" def __init__(self): super().__init__() self.init_plugins = stevedore.ExtensionManager( "qiskit.transpiler.init", invoke_on_load=True, propagate_map_exceptions=True ) self.layout_plugins = stevedore.ExtensionManager( "qiskit.transpiler.layout", invoke_on_load=True, propagate_map_exceptions=True ) self.routing_plugins = stevedore.ExtensionManager( "qiskit.transpiler.routing", invoke_on_load=True, propagate_map_exceptions=True ) self.translation_plugins = stevedore.ExtensionManager( "qiskit.transpiler.translation", invoke_on_load=True, propagate_map_exceptions=True ) self.optimization_plugins = stevedore.ExtensionManager( "qiskit.transpiler.optimization", invoke_on_load=True, propagate_map_exceptions=True ) self.scheduling_plugins = stevedore.ExtensionManager( "qiskit.transpiler.scheduling", invoke_on_load=True, propagate_map_exceptions=True ) def get_passmanager_stage( self, stage_name: str, plugin_name: str, pm_config: PassManagerConfig, optimization_level=None, ) -> PassManager: """Get a stage""" if stage_name == "init": return self._build_pm( self.init_plugins, stage_name, plugin_name, pm_config, optimization_level ) elif stage_name == "layout": return self._build_pm( self.layout_plugins, stage_name, plugin_name, pm_config, optimization_level ) elif stage_name == "routing": return self._build_pm( self.routing_plugins, stage_name, plugin_name, pm_config, optimization_level ) elif stage_name == "translation": return self._build_pm( self.translation_plugins, stage_name, plugin_name, pm_config, optimization_level ) elif stage_name == "optimization": return self._build_pm( self.optimization_plugins, stage_name, plugin_name, pm_config, optimization_level ) elif stage_name == "scheduling": return self._build_pm( self.scheduling_plugins, stage_name, plugin_name, pm_config, optimization_level ) else: raise TranspilerError(f"Invalid stage name: {stage_name}") def _build_pm( self, stage_obj: stevedore.ExtensionManager, stage_name: str, plugin_name: str, pm_config: PassManagerConfig, optimization_level: Optional[int] = None, ): if plugin_name not in stage_obj: raise TranspilerError(f"Invalid plugin name {plugin_name} for stage {stage_name}") plugin_obj = stage_obj[plugin_name] return plugin_obj.obj.pass_manager(pm_config, optimization_level) def list_stage_plugins(stage_name: str) -> List[str]: """Get a list of installed plugins for a stage. Args: stage_name: The stage name to get the plugin names for Returns: plugins: The list of installed plugin names for the specified stages Raises: TranspilerError: If an invalid stage name is specified. """ plugin_mgr = PassManagerStagePluginManager() if stage_name == "init": return plugin_mgr.init_plugins.names() elif stage_name == "layout": return plugin_mgr.layout_plugins.names() elif stage_name == "routing": return plugin_mgr.routing_plugins.names() elif stage_name == "translation": return plugin_mgr.translation_plugins.names() elif stage_name == "optimization": return plugin_mgr.optimization_plugins.names() elif stage_name == "scheduling": return plugin_mgr.scheduling_plugins.names() else: raise TranspilerError(f"Invalid stage name: {stage_name}") def passmanager_stage_plugins(stage: str) -> Dict[str, PassManagerStagePlugin]: """Return a dict with, for each stage name, the class type of the plugin. This function is useful for getting more information about a plugin: .. code-block:: python from qiskit.transpiler.preset_passmanagers.plugin import passmanager_stage_plugins routing_plugins = passmanager_stage_plugins('routing') basic_plugin = routing_plugins['basic'] help(basic_plugin) .. code-block:: text Help on BasicSwapPassManager in module ...preset_passmanagers.builtin_plugins object: class BasicSwapPassManager(...preset_passmanagers.plugin.PassManagerStagePlugin) | Plugin class for routing stage with :class:`~.BasicSwap` | | Method resolution order: | BasicSwapPassManager | ...preset_passmanagers.plugin.PassManagerStagePlugin | abc.ABC | builtins.object ... Args: stage: The stage name to get Returns: dict: the key is the name of the plugin and the value is the class type for each. Raises: TranspilerError: If an invalid stage name is specified. """ plugin_mgr = PassManagerStagePluginManager() try: manager = getattr(plugin_mgr, f"{stage}_plugins") except AttributeError as exc: raise TranspilerError(f"Passmanager stage {stage} not found") from exc return {name: manager[name].obj for name in manager.names()}
qiskit/qiskit/transpiler/preset_passmanagers/plugin.py/0
{ "file_path": "qiskit/qiskit/transpiler/preset_passmanagers/plugin.py", "repo_id": "qiskit", "token_count": 5389 }
223
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=unused-argument """ A collection of functions that decide the layout of an output image. See :py:mod:`~qiskit.visualization.pulse_v2.types` for more info on the required data. There are 3 types of layout functions in this module. 1. layout.chart_channel_map An end-user can write arbitrary functions that output the custom channel ordering associated with group name. Layout function in this module are called with the `formatter` and `device` kwargs. These data provides stylesheet configuration and backend system configuration. The layout function is restricted to: ```python def my_channel_layout(channels: List[pulse.channels.Channel], formatter: Dict[str, Any], device: DrawerBackendInfo ) -> Iterator[Tuple[str, List[pulse.channels.Channel]]]: ordered_channels = [] # arrange order of channels for key, channels in my_ordering_dict.items(): yield key, channels ``` 2. layout.time_axis_map An end-user can write arbitrary functions that output the `HorizontalAxis` data set that will be later consumed by the plotter API to update the horizontal axis appearance. Layout function in this module are called with the `time_window`, `axis_breaks`, and `dt` kwargs. These data provides horizontal axis limit, axis break position, and time resolution, respectively. See py:mod:`qiskit.visualization.pulse_v2.types` for more info on the required data. ```python def my_horizontal_axis(time_window: Tuple[int, int], axis_breaks: List[Tuple[int, int]], dt: Optional[float] = None) -> HorizontalAxis: # write horizontal axis configuration return horizontal_axis ``` 3. layout.figure_title An end-user can write arbitrary functions that output the string data that will be later consumed by the plotter API to output the figure title. Layout functions in this module are called with the `program` and `device` kwargs. This data provides input program and backend system configurations. ```python def my_figure_title(program: Union[pulse.Waveform, pulse.Schedule], device: DrawerBackendInfo) -> str: return 'title' ``` An arbitrary layout function satisfying the above format can be accepted. """ from collections import defaultdict from typing import List, Dict, Any, Tuple, Iterator, Optional, Union import numpy as np from qiskit import pulse from qiskit.visualization.pulse_v2 import types from qiskit.visualization.pulse_v2.device_info import DrawerBackendInfo def channel_type_grouped_sort( channels: List[pulse.channels.Channel], formatter: Dict[str, Any], device: DrawerBackendInfo ) -> Iterator[Tuple[str, List[pulse.channels.Channel]]]: """Layout function for the channel assignment to the chart instance. Assign single channel per chart. Channels are grouped by type and sorted by index in ascending order. Stylesheet key: `chart_channel_map` For example: [D0, D2, C0, C2, M0, M2, A0, A2] -> [D0, D2, C0, C2, M0, M2, A0, A2] Args: channels: Channels to show. formatter: Dictionary of stylesheet settings. device: Backend configuration. Yields: Tuple of chart name and associated channels. """ chan_type_dict = defaultdict(list) for chan in channels: chan_type_dict[type(chan)].append(chan) ordered_channels = [] # drive channels d_chans = chan_type_dict.get(pulse.DriveChannel, []) ordered_channels.extend(sorted(d_chans, key=lambda x: x.index)) # control channels c_chans = chan_type_dict.get(pulse.ControlChannel, []) ordered_channels.extend(sorted(c_chans, key=lambda x: x.index)) # measure channels m_chans = chan_type_dict.get(pulse.MeasureChannel, []) ordered_channels.extend(sorted(m_chans, key=lambda x: x.index)) # acquire channels if formatter["control.show_acquire_channel"]: a_chans = chan_type_dict.get(pulse.AcquireChannel, []) ordered_channels.extend(sorted(a_chans, key=lambda x: x.index)) for chan in ordered_channels: yield chan.name.upper(), [chan] def channel_index_grouped_sort( channels: List[pulse.channels.Channel], formatter: Dict[str, Any], device: DrawerBackendInfo ) -> Iterator[Tuple[str, List[pulse.channels.Channel]]]: """Layout function for the channel assignment to the chart instance. Assign single channel per chart. Channels are grouped by the same index and sorted by type. Stylesheet key: `chart_channel_map` For example: [D0, D2, C0, C2, M0, M2, A0, A2] -> [D0, D2, C0, C2, M0, M2, A0, A2] Args: channels: Channels to show. formatter: Dictionary of stylesheet settings. device: Backend configuration. Yields: Tuple of chart name and associated channels. """ chan_type_dict = defaultdict(list) inds = set() for chan in channels: chan_type_dict[type(chan)].append(chan) inds.add(chan.index) d_chans = chan_type_dict.get(pulse.DriveChannel, []) d_chans = sorted(d_chans, key=lambda x: x.index, reverse=True) u_chans = chan_type_dict.get(pulse.ControlChannel, []) u_chans = sorted(u_chans, key=lambda x: x.index, reverse=True) m_chans = chan_type_dict.get(pulse.MeasureChannel, []) m_chans = sorted(m_chans, key=lambda x: x.index, reverse=True) a_chans = chan_type_dict.get(pulse.AcquireChannel, []) a_chans = sorted(a_chans, key=lambda x: x.index, reverse=True) ordered_channels = [] for ind in sorted(inds): # drive channel if len(d_chans) > 0 and d_chans[-1].index == ind: ordered_channels.append(d_chans.pop()) # control channel if len(u_chans) > 0 and u_chans[-1].index == ind: ordered_channels.append(u_chans.pop()) # measure channel if len(m_chans) > 0 and m_chans[-1].index == ind: ordered_channels.append(m_chans.pop()) # acquire channel if formatter["control.show_acquire_channel"]: if len(a_chans) > 0 and a_chans[-1].index == ind: ordered_channels.append(a_chans.pop()) for chan in ordered_channels: yield chan.name.upper(), [chan] def channel_index_grouped_sort_u( channels: List[pulse.channels.Channel], formatter: Dict[str, Any], device: DrawerBackendInfo ) -> Iterator[Tuple[str, List[pulse.channels.Channel]]]: """Layout function for the channel assignment to the chart instance. Assign single channel per chart. Channels are grouped by the same index and sorted by type except for control channels. Control channels are added to the end of other channels. Stylesheet key: `chart_channel_map` For example: [D0, D2, C0, C2, M0, M2, A0, A2] -> [D0, D2, C0, C2, M0, M2, A0, A2] Args: channels: Channels to show. formatter: Dictionary of stylesheet settings. device: Backend configuration. Yields: Tuple of chart name and associated channels. """ chan_type_dict = defaultdict(list) inds = set() for chan in channels: chan_type_dict[type(chan)].append(chan) inds.add(chan.index) d_chans = chan_type_dict.get(pulse.DriveChannel, []) d_chans = sorted(d_chans, key=lambda x: x.index, reverse=True) m_chans = chan_type_dict.get(pulse.MeasureChannel, []) m_chans = sorted(m_chans, key=lambda x: x.index, reverse=True) a_chans = chan_type_dict.get(pulse.AcquireChannel, []) a_chans = sorted(a_chans, key=lambda x: x.index, reverse=True) u_chans = chan_type_dict.get(pulse.ControlChannel, []) u_chans = sorted(u_chans, key=lambda x: x.index) ordered_channels = [] for ind in sorted(inds): # drive channel if len(d_chans) > 0 and d_chans[-1].index == ind: ordered_channels.append(d_chans.pop()) # measure channel if len(m_chans) > 0 and m_chans[-1].index == ind: ordered_channels.append(m_chans.pop()) # acquire channel if formatter["control.show_acquire_channel"]: if len(a_chans) > 0 and a_chans[-1].index == ind: ordered_channels.append(a_chans.pop()) # control channels ordered_channels.extend(u_chans) for chan in ordered_channels: yield chan.name.upper(), [chan] def qubit_index_sort( channels: List[pulse.channels.Channel], formatter: Dict[str, Any], device: DrawerBackendInfo ) -> Iterator[Tuple[str, List[pulse.channels.Channel]]]: """Layout function for the channel assignment to the chart instance. Assign multiple channels per chart. Channels associated with the same qubit are grouped in the same chart and sorted by qubit index in ascending order. Acquire channels are not shown. Stylesheet key: `chart_channel_map` For example: [D0, D2, C0, C2, M0, M2, A0, A2] -> [Q0, Q1, Q2] Args: channels: Channels to show. formatter: Dictionary of stylesheet settings. device: Backend configuration. Yields: Tuple of chart name and associated channels. """ _removed = ( pulse.channels.AcquireChannel, pulse.channels.MemorySlot, pulse.channels.RegisterSlot, ) qubit_channel_map = defaultdict(list) for chan in channels: if isinstance(chan, _removed): continue qubit_channel_map[device.get_qubit_index(chan)].append(chan) sorted_map = sorted(qubit_channel_map.items(), key=lambda x: x[0]) for qind, chans in sorted_map: yield f"Q{qind:d}", chans def time_map_in_ns( time_window: Tuple[int, int], axis_breaks: List[Tuple[int, int]], dt: Optional[float] = None ) -> types.HorizontalAxis: """Layout function for the horizontal axis formatting. Calculate axis break and map true time to axis labels. Generate equispaced 6 horizontal axis ticks. Convert into seconds if ``dt`` is provided. Args: time_window: Left and right edge of this graph. axis_breaks: List of axis break period. dt: Time resolution of system. Returns: Axis formatter object. """ # shift time axis t0, t1 = time_window t0_shift = t0 t1_shift = t1 axis_break_pos = [] offset_accumulation = 0 for t0b, t1b in axis_breaks: if t1b < t0 or t0b > t1: continue if t0 > t1b: t0_shift -= t1b - t0b if t1 > t1b: t1_shift -= t1b - t0b axis_break_pos.append(t0b - offset_accumulation) offset_accumulation += t1b - t0b # axis label axis_loc = np.linspace(max(t0_shift, 0), t1_shift, 6) axis_label = axis_loc.copy() for t0b, t1b in axis_breaks: offset = t1b - t0b axis_label = np.where(axis_label > t0b, axis_label + offset, axis_label) # consider time resolution if dt: label = "Time (ns)" axis_label *= dt * 1e9 else: label = "System cycle time (dt)" formatted_label = [f"{val:.0f}" for val in axis_label] return types.HorizontalAxis( window=(t0_shift, t1_shift), axis_map=dict(zip(axis_loc, formatted_label)), axis_break_pos=axis_break_pos, label=label, ) def detail_title(program: Union[pulse.Waveform, pulse.Schedule], device: DrawerBackendInfo) -> str: """Layout function for generating figure title. This layout writes program name, program duration, and backend name in the title. """ title_str = [] # add program name title_str.append(f"Name: {program.name}") # add program duration dt = device.dt * 1e9 if device.dt else 1.0 title_str.append(f"Duration: {program.duration * dt:.1f} {'ns' if device.dt else 'dt'}") # add device name if device.backend_name != "no-backend": title_str.append(f"Backend: {device.backend_name}") return ", ".join(title_str) def empty_title(program: Union[pulse.Waveform, pulse.Schedule], device: DrawerBackendInfo) -> str: """Layout function for generating an empty figure title.""" return ""
qiskit/qiskit/visualization/pulse_v2/layouts.py/0
{ "file_path": "qiskit/qiskit/visualization/pulse_v2/layouts.py", "repo_id": "qiskit", "token_count": 5070 }
224
# 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. """ Stylesheet for timeline drawer. # TODO merge this docstring with pulse drawer. The stylesheet `QiskitTimelineStyle` is initialized with the hard-corded default values in `default_style`. The `QiskitTimelineStyle` is a wrapper class of python dictionary with the nested keys written such as `<type>.<group>.<item>` to represent a specific item from many configuration options. This key representation is imitative of `rcParams` of `matplotlib`. However, the `QiskitTimelineStyle` does not need to be compatible with the `rcParams` because the timeline stylesheet is heavily specialized to the context of the scheduled circuit visualization. Type of stylesheet is broadly separated into `formatter`, `generator` and `layout`. The formatter is a nested dictionary of drawing parameters to control the appearance of each visualization element. This data structure is similar to the `rcParams` of `matplotlib`. The generator is a list of callback functions that generates drawings from a given data source and the formatter. Each item can take multiple functions so that several drawing data, for example, box, text, etc..., are generated from the single data source. The layout is a callback function that determines the appearance of the output image. Because a single stylesheet doesn't generate multiple images with different appearance, only one layout function can be chosen for each stylesheet. """ from typing import Dict, Any, Mapping from qiskit.visualization.timeline import generators, layouts class QiskitTimelineStyle(dict): """Stylesheet for pulse drawer.""" def __init__(self): super().__init__() # to inform which stylesheet is applied. some plotter may not support specific style. self.stylesheet = None self.update(default_style()) def update(self, __m: Mapping[str, Any], **kwargs) -> None: super().update(__m, **kwargs) for key, value in __m.items(): self.__setitem__(key, value) self.stylesheet = __m.__class__.__name__ @property def formatter(self): """Return formatter field of style dictionary.""" sub_dict = {} for key, value in self.items(): sub_keys = key.split(".") if sub_keys[0] == "formatter": sub_dict[".".join(sub_keys[1:])] = value return sub_dict @property def generator(self): """Return generator field of style dictionary.""" sub_dict = {} for key, value in self.items(): sub_keys = key.split(".") if sub_keys[0] == "generator": sub_dict[".".join(sub_keys[1:])] = value return sub_dict @property def layout(self): """Return layout field of style dictionary.""" sub_dict = {} for key, value in self.items(): sub_keys = key.split(".") if sub_keys[0] == "layout": sub_dict[".".join(sub_keys[1:])] = value return sub_dict class IQXStandard(dict): """Standard timeline stylesheet. - Show time buckets. - Show only operand name. - Show bit name. - Show barriers. - Show idle timeline. - Show gate link. - Remove classical bits. """ def __init__(self, **kwargs): super().__init__() style = { "formatter.control.show_idle": True, "formatter.control.show_clbits": False, "formatter.control.show_barriers": True, "formatter.control.show_delays": False, "generator.gates": [generators.gen_sched_gate, generators.gen_short_gate_name], "generator.bits": [generators.gen_bit_name, generators.gen_timeslot], "generator.barriers": [generators.gen_barrier], "generator.gate_links": [generators.gen_gate_link], "layout.bit_arrange": layouts.qreg_creg_ascending, "layout.time_axis_map": layouts.time_map_in_dt, } style.update(**kwargs) self.update(style) def __repr__(self): return "Standard timeline style sheet." class IQXSimple(dict): """Simple timeline stylesheet. - Show time buckets. - Show bit name. - Show gate link. - Remove idle timeline. - Remove classical bits. """ def __init__(self, **kwargs): super().__init__() style = { "formatter.control.show_idle": False, "formatter.control.show_clbits": False, "formatter.control.show_barriers": False, "formatter.control.show_delays": False, "generator.gates": [generators.gen_sched_gate], "generator.bits": [generators.gen_bit_name, generators.gen_timeslot], "generator.barriers": [generators.gen_barrier], "generator.gate_links": [generators.gen_gate_link], "layout.bit_arrange": layouts.qreg_creg_ascending, "layout.time_axis_map": layouts.time_map_in_dt, } style.update(**kwargs) self.update(style) def __repr__(self): return "Simplified timeline style sheet." class IQXDebugging(dict): """Timeline stylesheet for programmers. Show details of instructions. - Show time buckets. - Show operand name, qubits, and parameters. - Show barriers. - Show delays. - Show idle timeline. - Show bit name. - Show gate link. """ def __init__(self, **kwargs): super().__init__() style = { "formatter.control.show_idle": True, "formatter.control.show_clbits": True, "formatter.control.show_barriers": True, "formatter.control.show_delays": True, "generator.gates": [generators.gen_sched_gate, generators.gen_full_gate_name], "generator.bits": [generators.gen_bit_name, generators.gen_timeslot], "generator.barriers": [generators.gen_barrier], "generator.gate_links": [generators.gen_gate_link], "layout.bit_arrange": layouts.qreg_creg_ascending, "layout.time_axis_map": layouts.time_map_in_dt, } style.update(**kwargs) self.update(style) def __repr__(self): return "Timeline style sheet for timeline programmers." def default_style() -> Dict[str, Any]: """Define default values of the timeline stylesheet.""" return { "formatter.general.fig_width": 14, "formatter.general.fig_unit_height": 0.8, "formatter.general.dpi": 150, "formatter.margin.top": 0.5, "formatter.margin.bottom": 0.5, "formatter.margin.left_percent": 0.02, "formatter.margin.right_percent": 0.02, "formatter.margin.link_interval_percent": 0.01, "formatter.margin.minimum_duration": 50, "formatter.time_bucket.edge_dt": 10, "formatter.color.background": "#FFFFFF", "formatter.color.timeslot": "#DDDDDD", "formatter.color.gate_name": "#000000", "formatter.color.bit_name": "#000000", "formatter.color.barrier": "#222222", "formatter.color.gates": { "u0": "#FA74A6", "u1": "#000000", "u2": "#FA74A6", "u3": "#FA74A6", "id": "#05BAB6", "sx": "#FA74A6", "sxdg": "#FA74A6", "x": "#05BAB6", "y": "#05BAB6", "z": "#05BAB6", "h": "#6FA4FF", "cx": "#6FA4FF", "cy": "#6FA4FF", "cz": "#6FA4FF", "swap": "#6FA4FF", "s": "#6FA4FF", "sdg": "#6FA4FF", "dcx": "#6FA4FF", "iswap": "#6FA4FF", "t": "#BB8BFF", "tdg": "#BB8BFF", "r": "#BB8BFF", "rx": "#BB8BFF", "ry": "#BB8BFF", "rz": "#000000", "reset": "#808080", "measure": "#808080", }, "formatter.color.default_gate": "#BB8BFF", "formatter.latex_symbol.gates": { "u0": r"{\rm U}_0", "u1": r"{\rm U}_1", "u2": r"{\rm U}_2", "u3": r"{\rm U}_3", "id": r"{\rm Id}", "x": r"{\rm X}", "y": r"{\rm Y}", "z": r"{\rm Z}", "h": r"{\rm H}", "cx": r"{\rm CX}", "cy": r"{\rm CY}", "cz": r"{\rm CZ}", "swap": r"{\rm SWAP}", "s": r"{\rm S}", "sdg": r"{\rm S}^\dagger", "sx": r"{\rm √X}", "sxdg": r"{\rm √X}^\dagger", "dcx": r"{\rm DCX}", "iswap": r"{\rm iSWAP}", "t": r"{\rm T}", "tdg": r"{\rm T}^\dagger", "r": r"{\rm R}", "rx": r"{\rm R}_x", "ry": r"{\rm R}_y", "rz": r"{\rm R}_z", "reset": r"|0\rangle", "measure": r"{\rm Measure}", }, "formatter.latex_symbol.frame_change": r"\circlearrowleft", "formatter.unicode_symbol.frame_change": "\u21BA", "formatter.box_height.gate": 0.5, "formatter.box_height.timeslot": 0.6, "formatter.layer.gate": 3, "formatter.layer.timeslot": 0, "formatter.layer.gate_name": 5, "formatter.layer.bit_name": 5, "formatter.layer.frame_change": 4, "formatter.layer.barrier": 1, "formatter.layer.gate_link": 2, "formatter.alpha.gate": 1.0, "formatter.alpha.timeslot": 0.7, "formatter.alpha.barrier": 0.5, "formatter.alpha.gate_link": 0.8, "formatter.line_width.gate": 0, "formatter.line_width.timeslot": 0, "formatter.line_width.barrier": 3, "formatter.line_width.gate_link": 3, "formatter.line_style.barrier": "-", "formatter.line_style.gate_link": "-", "formatter.text_size.gate_name": 12, "formatter.text_size.bit_name": 15, "formatter.text_size.frame_change": 18, "formatter.text_size.axis_label": 13, "formatter.label_offset.frame_change": 0.25, "formatter.control.show_idle": True, "formatter.control.show_clbits": True, "formatter.control.show_barriers": True, "formatter.control.show_delays": True, "generator.gates": [], "generator.bits": [], "generator.barriers": [], "generator.gate_links": [], "layout.bit_arrange": None, "layout.time_axis_map": None, }
qiskit/qiskit/visualization/timeline/stylesheet.py/0
{ "file_path": "qiskit/qiskit/visualization/timeline/stylesheet.py", "repo_id": "qiskit", "token_count": 5032 }
225
--- features: - | Initial support for executing experiments on ion trap backends has been added. - | An Rxx gate (rxx) and a global MΓΈlmer–SΓΈrensen gate (ms) have been added to the standard gate set. - | A Cnot to Rxx/Rx/Ry decomposer ``cnot_rxx_decompose`` and a single qubit Euler angle decomposer ``OneQubitEulerDecomposer`` have been added to the ``quantum_info.synthesis`` module. - | A transpiler pass ``MSBasisDecomposer`` has been added to unroll circuits defined over U3 and Cnot gates into a circuit defined over Rxx,Ry and Rx. This pass will be included in preset pass managers for backends which include the 'rxx' gate in their supported basis gates.
qiskit/releasenotes/notes/0.10/initial-ion-trap-support-33686980aa9ec3ae.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.10/initial-ion-trap-support-33686980aa9ec3ae.yaml", "repo_id": "qiskit", "token_count": 244 }
226
--- features: - | The ``latex`` output mode for ``qiskit.visualization.circuit_drawer()`` and the ``qiskit.circuit.QuantumCircuit.draw()`` method now has a mode to passthrough raw latex from gate labels and parameters. The syntax for doing this mirrors matplotlib's `mathtext mode <https://matplotlib.org/tutorials/text/mathtext.html>`__ syntax. Any portion of a label string between a pair of '$' characters will be treated as raw latex and passed directly into the generated output latex. This can be leveraged to add more advanced formatting to circuit diagrams generated with the latex drawer. Prior to this release all gate labels were run through a utf8 -> latex conversion to make sure that the output latex would compile the string as expected. This is still what happens for all portions of a label outside the '$' pair. Also if you want to use a dollar sign in your label make sure you escape it in the label string (ie ``'\$'``). You can mix and match this passthrough with the utf8 to latex conversion to create the exact label you want, for example:: from qiskit import circuit circ = circuit.QuantumCircuit(2) circ.h([0, 1]) circ.append(circuit.Gate(name='Ξ±_gate', num_qubits=1, params=[0]), [0]) circ.append(circuit.Gate(name='Ξ±_gate$_2$', num_qubits=1, params=[0]), [1]) circ.append(circuit.Gate(name='\$Ξ±\$_gate', num_qubits=1, params=[0]), [1]) circ.draw(output='latex') will now render the first custom gate's label as ``Ξ±_gate``, the second will be ``Ξ±_gate`` with a 2 subscript, and the last custom gate's label will be ``$Ξ±$_gate``.
qiskit/releasenotes/notes/0.11/add-latex-passthrough-cbdacd24d9db9918.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.11/add-latex-passthrough-cbdacd24d9db9918.yaml", "repo_id": "qiskit", "token_count": 568 }
227
--- features: - | When ``passmanager.run(...)`` is invoked with more than one circuit, the transpilation of these circuits will run in parallel. upgrade: - | `dill <https://pypi.org/project/dill/>`__ was added as a requirement. This is needed to enable running ``passmanager.run()`` in parallel for more than one circuit. issues: - | The feature for transpiling in parallel when ``passmanager.run(...)`` is invoked with more than one circuit is not supported under Windows. See `#2988 <https://github.com/Qiskit/qiskit-terra/issues/2988>`__ for more details.
qiskit/releasenotes/notes/0.11/parallel_passmanager_run-1d2173d33854e288.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.11/parallel_passmanager_run-1d2173d33854e288.yaml", "repo_id": "qiskit", "token_count": 199 }
228
--- features: - | :class:`qiskit.pulse.Acquire` can now be applied to a single qubit. This makes pulse programming more consistent and easier to reason about, as now all operations in now apply to a single channel. For example:: acquire = Acquire(duration=10) schedule = Schedule() schedule.insert(60, acquire(AcquireChannel(0), MemorySlot(0), RegisterSlot(0))) schedule.insert(60, acquire(AcquireChannel(1), MemorySlot(1), RegisterSlot(1))) deprecations: - | Running :class:`qiskit.pulse.Acquire` on multiple qubits has been deprecated and will be removed in a future release. Additionally, the :class:`qiskit.pulse.AcquireInstruction` parameters ``mem_slots`` and ``reg_slots`` have been deprecated. Instead ``reg_slot`` and ``mem_slot`` should be used instead.
qiskit/releasenotes/notes/0.12/acquire-single-channel-ea83cef8d991f945.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.12/acquire-single-channel-ea83cef8d991f945.yaml", "repo_id": "qiskit", "token_count": 276 }
229
--- features: - | In the preset pass manager for optimization level 1, :func:`qiskit.transpiler.preset_passmanagers.level_1_pass_manager` if :class:`qiskit.transpiler.passes.TrivialLayout` layout pass is not a perfect match for a particular circuit, then :class:`qiskit.transpiler.passes.DenseLayout` layout pass is used instead.
qiskit/releasenotes/notes/0.12/level1_trivial_dense_layout-7b6be7221b18af0c.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.12/level1_trivial_dense_layout-7b6be7221b18af0c.yaml", "repo_id": "qiskit", "token_count": 129 }
230
--- features: - | A new instruction :py:class:`~qiskit.pulse.SetFrequency` which allows users to change the frequency of the :class:`~qiskit.pulse.PulseChannel`. This is done in the following way:: from qiskit.pulse import Schedule from qiskit.pulse import SetFrequency sched = pulse.Schedule() sched += SetFrequency(5.5e9, DriveChannel(0)) In this example, the frequency of all pulses before the ``SetFrequency`` command will be the default frequency and all pulses applied to drive channel zero after the ``SetFrequency`` command will be at 5.5 GHz. Users of ``SetFrequency`` should keep in mind any hardware limitations.
qiskit/releasenotes/notes/0.13/add-set-frequency-instruction-18a43ad97a5c6f7f.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.13/add-set-frequency-instruction-18a43ad97a5c6f7f.yaml", "repo_id": "qiskit", "token_count": 228 }
231
--- features: - | The :meth:`qiskit.result.Result` method :meth:`~qiskit.result.Result.get_counts` will now return a list of all the counts available when there are multiple circuits in a job. This works when ``get_counts()`` is called with no arguments. The main consideration for this feature was for drawing all the results from multiple circuits in the same histogram. For example it is now possible to do something like: .. code-block:: from qiskit import execute from qiskit import QuantumCircuit from qiskit.providers.basicaer import BasicAer from qiskit.visualization import plot_histogram sim = BasicAer.get_backend('qasm_simulator') qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) qc.measure_all() result = execute([qc, qc, qc], sim).result() plot_histogram(result.get_counts())
qiskit/releasenotes/notes/0.13/get_counts-returns-also-dict_list-fcd23da8f3757105.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.13/get_counts-returns-also-dict_list-fcd23da8f3757105.yaml", "repo_id": "qiskit", "token_count": 356 }
232
--- upgrade: - | `fastjsonschema <https://pypi.org/project/fastjsonschema/>`_ is added as a dependency. This is used for much faster validation of qobj dictionaries against the JSON schema when the ``to_dict()`` method is called on qobj objects with the ``validate`` keyword argument set to ``True``. - | The qobj construction classes in :mod:`qiskit.qobj` will no longer validate against the qobj jsonschema by default. These include the following classes: * :class:`qiskit.qobj.QasmQobjInstruction` * :class:`qiskit.qobj.QobjExperimentHeader` * :class:`qiskit.qobj.QasmQobjExperimentConfig` * :class:`qiskit.qobj.QasmQobjExperiment` * :class:`qiskit.qobj.QasmQobjConfig` * :class:`qiskit.qobj.QobjHeader` * :class:`qiskit.qobj.PulseQobjInstruction` * :class:`qiskit.qobj.PulseQobjExperimentConfig` * :class:`qiskit.qobj.PulseQobjExperiment` * :class:`qiskit.qobj.PulseQobjConfig` * :class:`qiskit.qobj.QobjMeasurementOption` * :class:`qiskit.qobj.PulseLibraryItem` * :class:`qiskit.qobj.QasmQobjInstruction` * :class:`qiskit.qobj.QasmQobjExperimentConfig` * :class:`qiskit.qobj.QasmQobjExperiment` * :class:`qiskit.qobj.QasmQobjConfig` * :class:`qiskit.qobj.QasmQobj` * :class:`qiskit.qobj.PulseQobj` If you were relying on this validation or would like to validate them against the qobj schema this can be done by setting the ``validate`` kwarg to ``True`` on :meth:`~qiskit.qobj.QasmQobj.to_dict` method from either of the top level Qobj classes :class:`~qiskit.qobj.QasmQobj` or :class:`~qiskit.qobj.PulseQobj`. For example: .. code-block: from qiskit import qobj my_qasm = qobj.QasmQobj( qobj_id='12345', header=qobj.QobjHeader(), config=qobj.QasmQobjConfig(shots=1024, memory_slots=2, max_credits=10), experiments=[ qobj.QasmQobjExperiment(instructions=[ qobj.QasmQobjInstruction(name='u1', qubits=[1], params=[0.4]), qobj.QasmQobjInstruction(name='u2', qubits=[1], params=[0.4, 0.2]) ]) ] ) qasm_dict = my_qasm.to_dict(validate=True) which will validate the output dictionary against the Qobj jsonschema. - | The output dictionary from :meth:`qiskit.qobj.QasmQobj.to_dict` and :meth:`qiskit.qobj.PulseQobj.to_dict` is no longer in a format for direct json serialization as expected by IBMQ's API. These Qobj objects are the current format we use for passing experiments to providers/backends and while having a dictionary format that could just be passed to the IBMQ API directly was moderately useful for ``qiskit-ibmq-provider``, it made things more difficult for other providers. Especially for providers that wrap local simulators. Moving forward the definitions of what is passed between providers and the IBMQ API request format will be further decoupled (in a backwards compatible manner) which should ease the burden of writing providers and backends. In practice, the only functional difference between the output of these methods now and previous releases is that complex numbers are represented with the ``complex`` type and numpy arrays are not silently converted to list anymore. If you were previously calling ``json.dumps()`` directly on the output of ``to_dict()`` after this release a custom json encoder will be needed to handle these cases. For example:: import json from qiskit.circuit import ParameterExpression from qiskit import qobj my_qasm = qobj.QasmQobj( qobj_id='12345', header=qobj.QobjHeader(), config=qobj.QasmQobjConfig(shots=1024, memory_slots=2, max_credits=10), experiments=[ qobj.QasmQobjExperiment(instructions=[ qobj.QasmQobjInstruction(name='u1', qubits=[1], params=[0.4]), qobj.QasmQobjInstruction(name='u2', qubits=[1], params=[0.4, 0.2]) ]) ] ) qasm_dict = my_qasm.to_dict() class QobjEncoder(json.JSONEncoder): """A json encoder for pulse qobj""" def default(self, obj): # Convert numpy arrays: if hasattr(obj, 'tolist'): return obj.tolist() # Use Qobj complex json format: if isinstance(obj, complex): return (obj.real, obj.imag) if isinstance(obj, ParameterExpression): return float(obj) return json.JSONEncoder.default(self, obj) json_str = json.dumps(qasm_dict, cls=QobjEncoder) will generate a json string in the same exact manner that ``json.dumps(my_qasm.to_dict())`` did in previous releases. other: - | The qasm and pulse qobj classes: * :class:`~qiskit.qobj.QasmQobjInstruction` * :class:`~qiskit.qobj.QobjExperimentHeader` * :class:`~qiskit.qobj.QasmQobjExperimentConfig` * :class:`~qiskit.qobj.QasmQobjExperiment` * :class:`~qiskit.qobj.QasmQobjConfig` * :class:`~qiskit.qobj.QobjHeader` * :class:`~qiskit.qobj.PulseQobjInstruction` * :class:`~qiskit.qobj.PulseQobjExperimentConfig` * :class:`~qiskit.qobj.PulseQobjExperiment` * :class:`~qiskit.qobj.PulseQobjConfig` * :class:`~qiskit.qobj.QobjMeasurementOption` * :class:`~qiskit.qobj.PulseLibraryItem` * :class:`~qiskit.qobj.QasmQobjInstruction` * :class:`~qiskit.qobj.QasmQobjExperimentConfig` * :class:`~qiskit.qobj.QasmQobjExperiment` * :class:`~qiskit.qobj.QasmQobjConfig` * :class:`~qiskit.qobj.QasmQobj` * :class:`~qiskit.qobj.PulseQobj` from :mod:`qiskit.qobj` have all been reimplemented without using the marsmallow library. These new implementations are designed to be drop-in replacement (except for as noted in the upgrade release notes) but specifics inherited from marshmallow may not work. Please file issues for any incompatibilities found.
qiskit/releasenotes/notes/0.13/qobj-no-marshmallow-3f2b3c7b10584b02.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.13/qobj-no-marshmallow-3f2b3c7b10584b02.yaml", "repo_id": "qiskit", "token_count": 2875 }
233
--- features: - | :class:`qiskit.circuit.library.Diagonal` circuits have been added to the circuit library. These circuits implement diagonal quantum operators (consisting of non-zero elements only on the diagonal). They are more efficiently simulated by the Aer simulator than dense matrices.
qiskit/releasenotes/notes/0.14/circuit-lib-diagonal-a4cdeafce1edd0c6.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.14/circuit-lib-diagonal-a4cdeafce1edd0c6.yaml", "repo_id": "qiskit", "token_count": 83 }
234
--- fixes: - | Improve performance of :class:`qiskit.quantum_info.Statevector` and :class:`qiskit.quantum_info.DensityMatrix` for low-qubit circuit simulations by optimizing the class ``__init__`` methods. Fixes `#4281 <https://github.com/Qiskit/qiskit-terra/issues/4281>`_
qiskit/releasenotes/notes/0.14/statevector-init-91805b2f81f8e8c1.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.14/statevector-init-91805b2f81f8e8c1.yaml", "repo_id": "qiskit", "token_count": 110 }
235
--- fixes: - | When accessing a bit from a :class:`qiskit.circuit.QuantumRegister` or :class:`qiskit.circuit.ClassicalRegister` by index when using numpy `integer types` <https://numpy.org/doc/stable/user/basics.types.html>`__ would previously raise a ``CircuitError`` exception. This has been resolved so numpy types can be used in addition to Python's built-in ``int`` type. Fixes `#3929 <https://github.com/Qiskit/qiskit-terra/issues/3929>`__.
qiskit/releasenotes/notes/0.15/allowIntegerforQuantumRegisterSize-2e9a6cc033bc962e.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.15/allowIntegerforQuantumRegisterSize-2e9a6cc033bc962e.yaml", "repo_id": "qiskit", "token_count": 182 }
236
--- upgrade: - | :class:`~qiskit.pulse.Schedule` plotting with :py:meth:`qiskit.pulse.Schedule.draw` and :func:`qiskit.visualization.pulse_drawer` will no longer display the event table by default. This can be reenabled by setting the ``table`` kwarg to ``True``.
qiskit/releasenotes/notes/0.15/disable-default-plot-table-330705e3118fac6a.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.15/disable-default-plot-table-330705e3118fac6a.yaml", "repo_id": "qiskit", "token_count": 113 }
237
--- features: - | The :mod:`qiskit.visualization` function :func:`~qiskit.visualization.plot_state_qsphere` has a new kwarg ``show_state_labels`` which is used to control whether each blob in the qsphere visualization is labeled. By default this kwarg is set to ``True`` and shows the basis states next to each blob by default. This feature can be disabled, reverting to the previous behavior, by setting the ``show_state_labels`` kwarg to ``False``. - | The :mod:`qiskit.visualization` function :func:`~qiskit.visualization.plot_state_qsphere` has a new kwarg ``show_state_phases`` which is set to ``False`` by default. When set to ``True`` it displays the phase of each basis state. - | The :mod:`qiskit.visualization` function :func:`~qiskit.visualization.plot_state_qsphere` has a new kwarg ``use_degrees`` which is set to ``False`` by default. When set to ``True`` it displays the phase of each basis state in degrees, along with the phase circle at the bottom right.
qiskit/releasenotes/notes/0.15/qsphere-state-display-819cc1e3e61314a2.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.15/qsphere-state-display-819cc1e3e61314a2.yaml", "repo_id": "qiskit", "token_count": 355 }
238
--- features: - | Two new passes, :class:`~qiskit.transpiler.passes.SabreLayout` and :class:`~qiskit.transpiler.passes.SabreSwap` for layout and routing have been added to :mod:`qiskit.transpiler.passes`. These new passes are based on the algorithm presented in Li et al., "Tackling the Qubit Mapping Problem for NISQ-Era Quantum Devices", ASPLOS 2019. They can also be selected when using the :func:`~qiskit.compiler.transpile` function by setting the ``layout_method`` kwarg to ``'sabre'`` and/or the ``routing_method`` to ``'sabre'`` to use :class:`~qiskit.transpiler.passes.SabreLayout` and :class:`~qiskit.transpiler.passes.SabreSwap` respectively.
qiskit/releasenotes/notes/0.15/sabre-2a3bba505e48ee82.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.15/sabre-2a3bba505e48ee82.yaml", "repo_id": "qiskit", "token_count": 263 }
239
--- features: - | Global R gates have been added to :mod:`qiskit.circuit.library`. This includes the global R gate (:class:`~qiskit.circuit.library.GR`), global Rx (:class:`~qiskit.circuit.library.GRX`) and global Ry (:class:`~qiskit.circuit.library.GRY`) gates which are derived from the :class:`~qiskit.circuit.library.GR` gate, and global Rz ( :class:`~qiskit.circuit.library.GRZ`) that is defined in a similar way to the :class:`~qiskit.circuit.library.GR` gates. The global R gates are defined on a number of qubits simultaneously, and act as a direct sum of R gates on each qubit. For example: .. code-block :: python from qiskit import QuantumCircuit, QuantumRegister import numpy as np num_qubits = 3 qr = QuantumRegister(num_qubits) qc = QuantumCircuit(qr) qc.compose(GR(num_qubits, theta=np.pi/3, phi=2*np.pi/3), inplace=True) will create a :class:`~qiskit.circuit.QuantumCircuit` on a :class:`~qiskit.circuit.QuantumRegister` of 3 qubits and perform a :class:`~qiskit.circuit.library.RGate` of an angle :math:`\theta = \frac{\pi}{3}` about an axis in the xy-plane of the Bloch spheres that makes an angle of :math:`\phi = \frac{2\pi}{3}` with the x-axis on each qubit.
qiskit/releasenotes/notes/0.16/add-globalR-gates-13dd2860618e5c3f.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.16/add-globalR-gates-13dd2860618e5c3f.yaml", "repo_id": "qiskit", "token_count": 530 }
240
--- fixes: - | Fixed an issue when creating a :class:`qiskit.result.Counts` object from an empty data dictionary. Now this will create an empty :class:`~qiskit.result.Counts` object. The :meth:`~qiskit.result.Counts.most_frequent` method is also updated to raise a more descriptive exception when the object is empty. Fixes `#5017 <https://github.com/Qiskit/qiskit-terra/issues/5017>`__
qiskit/releasenotes/notes/0.16/empty-counts-00438f695cac2438.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.16/empty-counts-00438f695cac2438.yaml", "repo_id": "qiskit", "token_count": 148 }
241
--- upgrade: - | The previously deprecated support for passing in a dictionary as the first positional argument to :class:`~qiskit.dagcircuit.DAGNode` constructor has been removed. Using a dictionary for the first positional argument was deprecated in the 0.13.0 release. To create a :class:`~qiskit.dagcircuit.DAGNode` object now you should directly pass the attributes as kwargs on the constructor.
qiskit/releasenotes/notes/0.16/remove-dagnode-dict-32fa35479c0a8331.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.16/remove-dagnode-dict-32fa35479c0a8331.yaml", "repo_id": "qiskit", "token_count": 128 }
242
--- features: - | A new class, :py:class:`~qiskit.pulse.ScheduleBlock`, has been added to the :class:`qiskit.pulse` module. This class provides a new representation of a pulse program. This representation is best suited for the pulse builder syntax and is based on relative instruction ordering. This representation takes ``alignment_context`` instead of specifying starting time ``t0`` for each instruction. The start time of instruction is implicitly allocated with the specified transformation and relative position of instructions. The :py:class:`~qiskit.pulse.ScheduleBlock` allows for lazy instruction scheduling, meaning we can assign arbitrary parameters to the duration of instructions. For example: .. code-block:: python from qiskit.pulse import ScheduleBlock, DriveChannel, Gaussian from qiskit.pulse.instructions import Play, Call from qiskit.pulse.transforms import AlignRight from qiskit.circuit import Parameter dur = Parameter('rabi_duration') block = ScheduleBlock(alignment_context=AlignRight()) block += Play(Gaussian(dur, 0.1, dur/4), DriveChannel(0)) block += Call(measure_sched) # subroutine defined elsewhere this code defines an experiment scanning a Gaussian pulse's duration followed by a measurement ``measure_sched``, i.e. a Rabi experiment. You can reuse the ``block`` object for every scanned duration by assigning a target duration value. deprecations: - | The :meth:`~qiskit.pulse.channels.Channel.assign_parameters` for the following classes: * :py:class:`qiskit.pulse.channels.Channel`, * :py:class:`qiskit.pulse.library.Pulse`, * :py:class:`qiskit.pulse.instructions.Instruction`, and all their subclasses is now deprecated and will be removed in a future release. This functionality has been subsumed :py:class:`~qiskit.pulse.ScheduleBlock` which is the future direction for constructing parameterized pulse programs. - | The :attr:`~qiskit.pulse.channels.Channel.parameters` attribute for the following classes: * :py:class:`~qiskit.pulse.channels.Channel` * :py:class:`~qiskit.pulse.instructions.Instruction`. is deprecated and will be removed in a future release. This functionality has been subsumed :py:class:`~qiskit.pulse.ScheduleBlock` which is the future direction for constructing parameterized pulse programs.
qiskit/releasenotes/notes/0.17/add-schedule-block-c37527f3205b7b62.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.17/add-schedule-block-c37527f3205b7b62.yaml", "repo_id": "qiskit", "token_count": 809 }
243
--- features: - | Add a new operator class :class:`~qiskit.quantum_info.CNOTDihedral` has been added to the :mod:`qiskit.quantum_info` module. This class is used to represent the CNOT-Dihedral group, which is generated by the quantum gates :class:`~qiskit.circuit.library.CXGate`, :class:`~qiskit.circuit.library.TGate`, and :class:`~qiskit.circuit.library.XGate`.
qiskit/releasenotes/notes/0.17/cnot-dihedral-op-518a51b2827cd291.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.17/cnot-dihedral-op-518a51b2827cd291.yaml", "repo_id": "qiskit", "token_count": 151 }
244
--- fixes: - | Fixed the ``'circular'`` entanglement in the :class:`qiskit.circuit.library.NLocal` circuit class for the edge case where the circuit has the same size as the entanglement block (e.g. a two-qubit circuit and CZ entanglement gates). In this case there should only be one entanglement gate, but there was accidentally added a second one in the inverse direction as the first. Fixed `Qiskit/qiskit-aqua#1452 <https://github.com/Qiskit/qiskit-aqua/issues/1452>`__
qiskit/releasenotes/notes/0.17/fix-nlocal-circular-entanglement-0acf0195138b6aa2.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.17/fix-nlocal-circular-entanglement-0acf0195138b6aa2.yaml", "repo_id": "qiskit", "token_count": 174 }
245
--- features: - | The kwarg, ``template_list``, for the constructor of the :class:`qiskit.transpiler.passes.TemplateOptimization` transpiler pass now supports taking in a list of both :class:`~qiskit.circuit.QuantumCircuit` and :class:`~qiskit.dagcircuit.DAGDependency` objects. Previously, only :class:`~qiskit.circuit.QuantumCircuit` were accepted (which were internally converted to :class:`~qiskit.dagcircuit.DAGDependency` objects) in the input list.
qiskit/releasenotes/notes/0.17/issue-5549-0b4e71d44dc13ce5.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.17/issue-5549-0b4e71d44dc13ce5.yaml", "repo_id": "qiskit", "token_count": 184 }
246
--- features: - | A new class, :class:`~qiskit.circuit.library.PiecewisePolynomialPauliRotations`, has been added to the :mod:`qiskit.circuit.library` module. This circuit library element is used for mapping a piecewise polynomial function, :math:`f(x)`, which is defined through breakpoints and coefficients, on qubit amplitudes. The breakpoints :math:`(x_0, ..., x_J)` are a subset of :math:`[0, 2^n-1]`, where :math:`n` is the number of state qubits. The corresponding coefficients :math:`[a_{j,1},...,a_{j,d}]`, where :math:`d` is the highest degree among all polynomials. Then :math:`f(x)` is defined as: .. math:: f(x) = \begin{cases} 0, x < x_0 \\ \sum_{i=0}^{i=d}a_{j,i} x^i, x_j \leq x < x_{j+1} \end{cases} where we implicitly assume :math:`x_{J+1} = 2^n`. And the mapping applied to the amplitudes is given by .. math:: F|x\rangle |0\rangle = \cos(p_j(x))|x\rangle |0\rangle + \sin(p_j(x))|x\rangle |1\rangle This mapping is based on controlled Pauli Y-rotations and constructed using the :class:`~qiskit.circuit.library.PolynomialPauliRotations`.
qiskit/releasenotes/notes/0.17/piecewise-polynomial-and-inverse-chebyshev-e3c4e0765b628c9f.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.17/piecewise-polynomial-and-inverse-chebyshev-e3c4e0765b628c9f.yaml", "repo_id": "qiskit", "token_count": 507 }
247
--- features: - | Adds a :meth:`~qiskit.quantum_info.Statevector.reverse_qargs` method to the :class:`qiskit.quantum_info.Statevector` and :class:`qiskit.quantum_info.DensityMatrix` classes. This method reverses the order of subsystems in the states and is equivalent to the :meth:`qiskit.circuit.QuantumCircuit.reverse_bits` method for N-qubit states. For example: .. code-block:: from qiskit.circuit.library import QFT from qiskit.quantum_info import Statevector circ = QFT(3) state1 = Statevector.from_instruction(circ) state2 = Statevector.from_instruction(circ.reverse_bits()) state1.reverse_qargs() == state2 - | Adds a :meth:`~qiskit.quantum_info.Operator.reverse_qargs` method to the :class:`qiskit.quantum_info.Operator` class. This method reverses the order of subsystems in the operator and is equivalent to the :meth:`qiskit.circuit.QuantumCircuit.reverse_bits` method for N-qubit operators. For example: .. code-block:: from qiskit.circuit.library import QFT from qiskit.quantum_info import Operator circ = QFT(3) op1 = Operator(circ) op2 = Operator(circ.reverse_bits()) op1.reverse_qargs() == op2
qiskit/releasenotes/notes/0.17/reverse_qargs-f2f3c9a3e1c3aaa0.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.17/reverse_qargs-f2f3c9a3e1c3aaa0.yaml", "repo_id": "qiskit", "token_count": 538 }
248
--- features: - | A new constructor method :meth:`~qiskit.pulse.Schedule.initialize_from` was added to the :class:`~qiskit.pulse.Schedule` and :class:`~qiskit.pulse.ScheduleBlock` classes. This method initializes a new empty schedule which takes the attributes from other schedule. For example: .. code-block:: python sched = Schedule(name='my_sched') new_sched = Schedule.initialize_from(sched) assert sched.name == new_sched.name
qiskit/releasenotes/notes/0.18/add-initialize-from-method-to-schedules-ce86083b5bd39e6b.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.18/add-initialize-from-method-to-schedules-ce86083b5bd39e6b.yaml", "repo_id": "qiskit", "token_count": 182 }
249
--- fixes: - | When loading an OpenQASM2 file or string with the :meth:`~qiskit.circuitQuantumCircuit.from_qasm_file` or :meth:`~qiskit.circuitQuantumCircuit.from_qasm_str` constructors for the :class:`~qiskit.circuit.QuantumCircuit` class, if the OpenQASM2 circuit contains an instruction with the name ``delay`` this will be mapped to a :class:`qiskit.circuit.Delay` instruction. For example: .. code-block:: from qiskit import QuantumCircuit qasm = """OPENQASM 2.0; include "qelib1.inc"; opaque delay(time) q; qreg q[1]; delay(172) q[0]; u3(0.1,0.2,0.3) q[0]; """ circuit = QuantumCircuit.from_qasm_str(qasm) circuit.draw() Fixed `#6510 <https://github.com/Qiskit/qiskit-terra/issues/6510>`__
qiskit/releasenotes/notes/0.18/delay_from_qasm-a6ad4f1fe3f49041.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.18/delay_from_qasm-a6ad4f1fe3f49041.yaml", "repo_id": "qiskit", "token_count": 364 }
250
--- fixes: - | Fixed the bug that caused :meth:`~qiskit.opflow.PauliOp.to_circuit` to fail when :class:`~qiskit.opflow.PauliOp` had a phase. At the same time, it was made more efficient to use :class:`~qiskit.circuit.library.generalized_gates.PauliGate`.
qiskit/releasenotes/notes/0.18/fix-pauli-op-to-circuit-2ace141cac0dd97a.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.18/fix-pauli-op-to-circuit-2ace141cac0dd97a.yaml", "repo_id": "qiskit", "token_count": 107 }
251
--- features: - | The :class:`~qiskit.circuit.Delay` class now can accept a :class:`~qiskit.circuit.ParameterExpression` or :class:`~qiskit.circuit.Parameter` value for the ``duration`` kwarg on its constructor and for its :attr:`~qiskit.circuit.Delay.duration` attribute. For example:: idle_dur = Parameter('t') qc = QuantumCircuit(1, 1) qc.x(0) qc.delay(idle_dur, 0, 'us') qc.measure(0, 0) print(qc) # parameterized delay in us (micro seconds) # assign before transpilation assigned = qc.assign_parameters({idle_dur: 0.1}) print(assigned) # delay in us transpiled = transpile(assigned, some_backend_with_dt) print(transpiled) # delay in dt # assign after transpilation transpiled = transpile(qc, some_backend_with_dt) print(transpiled) # parameterized delay in dt assigned = transpiled.assign_parameters({idle_dur: 0.1}) print(assigned) # delay in dt
qiskit/releasenotes/notes/0.18/parameterized-delay-3d55448e5cbc5269.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.18/parameterized-delay-3d55448e5cbc5269.yaml", "repo_id": "qiskit", "token_count": 458 }
252
--- prelude: | The Qiskit Terra 0.19 release highlights are: * A new version of the abstract Qiskit/hardware interface, in the form of :class:`.BackendV2`, which comes with a new data structure :class:`~.transpiler.Target` to allow backends to better model their constraints for the :ref:`transpiler <qiskit-transpiler>`. * An :ref:`extensible plugin interface <qiskit-transpiler-plugins>` to the :class:`~.passes.UnitarySynthesis` transpiler pass, allowing users or other packages to extend Qiskit Terra's synthesis routines with new methods. * Control-flow instructions, for representing ``for`` and ``while`` loops and ``if``/``else`` statements in :class:`.QuantumCircuit`. The simulators in Qiskit Aer will soon be able to work with these new instructions, allowing you to write more dynamic quantum programs. * Preliminary support for the evolving `OpenQASM 3 specification`_. You can use the new :mod:`qiskit.qasm3` module to serialize your :class:`.QuantumCircuit`\ s into OpenQASM 3, including the new control-flow constructs. .. _OpenQASM 3 specification: https://qiskit.github.io/openqasm/ This release marks the end of support for Python 3.6 in Qiskit. This release of Qiskit Terra, and any subsequent bugfix releases in the 0.19.x series, will be the last to work with Python 3.6. Starting from the next minor release (0.20.0) of Qiskit Terra, the minimum required Python version will be 3.7. As always, there are many more features and fixes in this release as well, which you can read about below.
qiskit/releasenotes/notes/0.19/0.19-prelude-65c295aa9497ed48.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.19/0.19-prelude-65c295aa9497ed48.yaml", "repo_id": "qiskit", "token_count": 540 }
253
--- features: - | A new transpiler pass, :class:`.PulseGates`, was added, which automatically extracts user-provided calibrations from the instruction schedule map and attaches the gate schedule to the given (transpiled) quantum circuit as a pulse gate. The :class:`.PulseGates` transpiler pass is applied to all optimization levels from 0 to 3. No gate implementation is updated unless the end-user explicitly overrides the ``backend.defaults().instruction_schedule_map``. This pass saves users from individually calling :meth:`.QuantumCircuit.add_calibration` for every circuit run on the hardware. To supplement this new pass, a schedule was added to :class:`~qiskit.pulse.InstructionScheduleMap` and is implicitly updated with a metadata field ``"publisher"``. Backend-calibrated gate schedules have a special publisher kind to avoid overriding circuits with calibrations of already known schedules. Usually, end-users don't need to take care of this metadata as it is applied automatically. You can call :meth:`.InstructionScheduleMap.has_custom_gate` to check if the map has custom gate calibration. See the below code example to learn how to apply custom gate implementation for all circuits under execution. .. code-block:: python from qiskit.test.mock import FakeGuadalupe from qiskit import pulse, circuit, transpile backend = FakeGuadalupe() with pulse.build(backend, name="x") as x_q0: pulse.play(pulse.Constant(160, 0.1), pulse.drive_channel(0)) backend.defaults().instruction_schedule_map.add("x", (0,), x_q0) circs = [] for _ in range(100): circ = circuit.QuantumCircuit(1) circ.sx(0) circ.rz(1.57, 0) circ.x(0) circ.measure_active() circs.append(circ) circs = transpile(circs, backend) circs[0].calibrations # This returns calibration only for x gate Note that the instruction schedule map is a mutable object. If you override one of the entries and use that backend for other experiments, you may accidentally update the gate definition. .. code-block:: python backend = FakeGuadalupe() instmap = backend.defaults().instruction_schedule_map instmap.add("x", (0, ), my_x_gate_schedule) qc = QuantumCircuit(1, 1) qc.x(0) qc.measure(0, 0) qc = transpile(qc, backend) # This backend uses custom X gate If you want to update the gate definitions of a specific experiment, you need to first deepcopy the instruction schedule map and directly pass it to the transpiler. deprecations: - | There has been a significant transpiler pass reorganization regarding calibrations. The import paths:: from qiskit.transpiler.passes.scheduling.calibration_creators import RZXCalibrationBuilder from qiskit.transpiler.passes.scheduling.calibration_creators import RZXCalibrationBuilderNoEcho are deprecated, and will be removed in a future release. The import path:: from qiskit.transpiler.passes.scheduling.rzx_templates import rzx_templates is also deprecated, and will be removed in a future release. You should use the new import paths:: from qiskit.transpiler.passes import RZXCalibrationBuilder from qiskit.transpiler.passes import RZXCalibrationBuilderNoEcho from qiskit.transpiler.passes.calibration.rzx_templates import rzx_templates
qiskit/releasenotes/notes/0.19/add-pulse-gate-pass-dc347177ed541bcc.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.19/add-pulse-gate-pass-dc347177ed541bcc.yaml", "repo_id": "qiskit", "token_count": 1219 }
254
--- features: - | The constructor of :class:`~qiskit.transpiler.passes.RZXCalibrationBuilder` has two new kwargs ``instruction_schedule_map`` and ``qubit_channel_mapping`` which take a :class:`~qiskit.pulse.InstructionScheduleMap` and list of channel name lists for each qubit respectively. These new arguments are used to directly specify the information needed from a backend target. They should be used instead of passing a :class:`~qiskit.providers.BaseBackend` or :class:`~qiskit.providers.BackendV1` object directly to the pass with the ``backend`` argument. deprecations: - | For the constructor of the :class:`~qiskit.transpiler.passes.RZXCalibrationBuilder` passing a backend either as the first positional argument or with the named ``backend`` kwarg is deprecated and will no longer work in a future release. Instead a :class:`~qiskit.pulse.InstructionScheduleMap` should be passed directly to the ``instruction_schedule_map`` kwarg and a list of channel name lists for each qubit should be passed directly to ``qubit_channel_mapping``. For example, if you were calling the pass like:: from qiskit.transpiler.passes import RZXCalibrationBuilder from qiskit.test.mock import FakeMumbai backend = FakeMumbai() cal_pass = RZXCalibrationBuilder(backend) instead you should call it like:: from qiskit.transpiler.passes import RZXCalibrationBuilder from qiskit.test.mock import FakeMumbai backend = FakeMumbai() inst_map = backend.defaults().instruction_schedule_map channel_map = self.backend.configuration().qubit_channel_mapping cal_pass = RZXCalibrationBuilder( instruction_schedule_map=inst_map, qubit_channel_mapping=channel_map, ) This change is necessary because as a general rule backend objects are not pickle serializable and it would break when it was used with multiple processes inside of :func:`~qiskit.compiler.transpile` when compiling multiple circuits at once.
qiskit/releasenotes/notes/0.19/deprecate-backend-rzx-cal-build-8eda1526725d7e7d.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.19/deprecate-backend-rzx-cal-build-8eda1526725d7e7d.yaml", "repo_id": "qiskit", "token_count": 723 }
255
--- fixes: - | Fixed an issue where calling :meth:`.QuantumCircuit.copy` on the "body" circuits of a control-flow operation created with the builder interface would raise an error. For example, this was previously an error, but will now return successfully:: from qiskit.circuit import QuantumCircuit, QuantumRegister, ClassicalRegister qreg = QuantumRegister(4) creg = ClassicalRegister(1) circ = QuantumCircuit(qreg, creg) with circ.if_test((creg, 0)): circ.h(0) if_else_instruction, _, _ = circ.data[0] true_body = if_else_instruction.params[0] true_body.copy()
qiskit/releasenotes/notes/0.19/fix-control-flow-builder-parameter-copy-b1f6efcc6bc283e7.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.19/fix-control-flow-builder-parameter-copy-b1f6efcc6bc283e7.yaml", "repo_id": "qiskit", "token_count": 258 }
256
--- fixes: - | Fixed an issue in scheduling of circuits with clbits operations, e.g. measurements, conditional gates, updating :class:`~qiskit.transpiler.passes.ASAPSchedule`, :class:`~qiskit.transpiler.passes.ALAPSchedule`, and :class:`~qiskit.transpiler.passes.AlignMeasures`. The updated schedulers assume all clbits I/O operations take no time, ``measure`` writes the measured value to a clbit at the end, and ``c_if`` reads the conditional value in clbit(s) at the beginning. Fixed `#7006 <https://github.com/Qiskit/qiskit-terra/issues/7006>`__.
qiskit/releasenotes/notes/0.19/fix-scheduling-circuits-with-clbits-operations-e5d8bfa90e9a3ae1.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.19/fix-scheduling-circuits-with-clbits-operations-e5d8bfa90e9a3ae1.yaml", "repo_id": "qiskit", "token_count": 215 }
257
--- features: - | Added an :meth:`.Optimizer.minimize` method to all optimizers: :class:`~qiskit.algorithms.optimizers.Optimizer` and derived classes. This method mimics the signature of SciPy's ``minimize()`` function and returns an :class:`~qiskit.algorithms.optimizers.OptimizerResult`. For example .. code-block:: python import numpy as np from qiskit.algorithms.optimizers import COBYLA def loss(x): return -(x[0] - 1) ** 2 - (x[1] + 1) ** 3 initial_point = np.array([0, 0]) optimizer = COBYLA() result = optimizer.minimize(loss, initial_point) optimal_parameters = result.x minimum_value = result.fun num_function_evals = result.nfev deprecations: - | The :meth:`.Optimizer.optimize` method for all the optimizers (:class:`~qiskit.algorithms.optimizers.Optimizer` and derived classes) is now deprecated and will be removed in a future release. Instead, the :meth:`.Optimizer.minimize` method should be used which mimics the signature of SciPy's ``minimize()`` function. To replace the current `optimize` call with `minimize` you can replace .. code-block:: python xopt, fopt, nfev = optimizer.optimize( num_vars, objective_function, gradient_function, variable_bounds, initial_point, ) with .. code-block:: python result = optimizer.minimize( fun=objective_function, x0=initial_point, jac=gradient_function, bounds=variable_bounds, ) xopt, fopt, nfev = result.x, result.fun, result.nfev
qiskit/releasenotes/notes/0.19/optimizer-minimize-5a5a1e9d67db441a.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.19/optimizer-minimize-5a5a1e9d67db441a.yaml", "repo_id": "qiskit", "token_count": 731 }
258
--- upgrade: - | The use of ``*`` (``__mul__``) for the :meth:`~qiskit.quantum_info.Operator.dot` method and ``@`` (``__matmul__``) for the :meth:`~qiskit.quantum_info.Operator.compose` method of ``BaseOperator`` (which is the parent of all the operator classes in :mod:`qiskit.quantum_info` including classes like :class:`~qiskit.quantum_info.Operator` and :class:`~qiskit.quantum_info.Pauli`) is no longer supported. The use of these operators were previously deprecated in 0.17.0 release. Instead you should use the :meth:`~qiskit.quantum_info.Operator.dot` and :meth:`~qiskit.quantum_info.Operator.compose` methods directly, or the ``&`` operator (``__and__``) can be used for :meth:`~qiskit.quantum_info.Operator.compose`. For example, if you were previously using the operator like:: from qiskit.quantum_info import random_hermitian op_a = random_hermitian(4) op_b = random_hermitian(4) new_op = op_a @ op_b this should be changed to be:: from qiskit.quantum_info import random_hermitian op_a = random_hermitian(4) op_b = random_hermitian(4) new_op = op_a.compose(op_b) or:: new_op = op_a & op_b
qiskit/releasenotes/notes/0.19/remove-deprecated-ops-2fbd27abaee98c68.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.19/remove-deprecated-ops-2fbd27abaee98c68.yaml", "repo_id": "qiskit", "token_count": 533 }
259
--- fixes: - | Fixed an issue with the :meth:`~qiskit.circuit.QuantumCircuit.draw` method and :func:`~qiskit.visualization.circuit_drawer` function, where a custom style set via the user config file (i.e. ``settings.conf``) would ignore the set value of the ``circuit_mpl_style`` field if the ``style`` kwarg on the function/method was not set.
qiskit/releasenotes/notes/0.19/user-config-mpl-style-a9ae4eb7ce072fcd.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.19/user-config-mpl-style-a9ae4eb7ce072fcd.yaml", "repo_id": "qiskit", "token_count": 131 }
260
--- upgrade: - | The classes :class:`~qiskit.circuit.Qubit`, :class:`.Clbit` and :class:`.AncillaQubit` now have the ``__slots__`` attribute. This is to reduce their memory usage. As a side effect, they can no longer have arbitrary data attached as attributes to them. This is very unlikely to have any effect on downstream code other than performance benefits.
qiskit/releasenotes/notes/0.20/bit-slots-17d6649872da0440.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.20/bit-slots-17d6649872da0440.yaml", "repo_id": "qiskit", "token_count": 123 }
261
--- fixes: - | Fixed an issue where the :meth:`.HHL.construct_circuit` method under certain conditions would not return a correct :class:`~.QuantumCircuit`. Previously, the function had a rounding error in calculating how many qubits were necessary to represent the eigenvalues which would cause an incorrect circuit output.
qiskit/releasenotes/notes/0.20/fix-hhl_construct_circuit-nl-size-03cbfba9ed50a57a.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.20/fix-hhl_construct_circuit-nl-size-03cbfba9ed50a57a.yaml", "repo_id": "qiskit", "token_count": 97 }
262
--- features: - | New fake backend classes are available under ``qiskit.providers.fake_provider``. These include mocked versions of ``ibm_cairo``, ``ibm_hanoi``, ``ibmq_kolkata``, ``ibm_nairobi``, and ``ibm_washington``. As with the other fake backends, these include snapshots of calibration and error data taken from the real system, and can be used for local testing, compilation and simulation.
qiskit/releasenotes/notes/0.20/new-fake-backends-04ea9cb26374e385.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.20/new-fake-backends-04ea9cb26374e385.yaml", "repo_id": "qiskit", "token_count": 134 }
263
--- upgrade: - | The previously deprecated ``ParametrizedSchedule`` class has been removed and no longer exists. This class was deprecated as a part of the 0.17.0 release. Instead of using this class you can directly parametrize :py:class:`~qiskit.pulse.Schedule` or :py:class:`~qiskit.pulse.ScheduleBlock` objects by specifying a :py:class:`~qiskit.circuit.Parameter` object to the parametric pulse argument.
qiskit/releasenotes/notes/0.20/remove-parametrized-schedule-fc4b31a8180db9d9.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.20/remove-parametrized-schedule-fc4b31a8180db9d9.yaml", "repo_id": "qiskit", "token_count": 150 }
264
--- fixes: - | Extra validation was added to :class:`.DiagonalGate` to check the argument has modulus one.
qiskit/releasenotes/notes/0.21/3842-14af3f8d922a7253.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.21/3842-14af3f8d922a7253.yaml", "repo_id": "qiskit", "token_count": 35 }
265
--- fixes: - | The :class:`~.BackendV2`\ -based fake backends in the :mod:`qiskit.providers.fake_provider` module, such as :class:`.FakeMontrealV2`, now support the :class:`~qiskit.circuit.Delay` operation in their :attr:`~.BackendV2.target` attributes. Previously, :class:`.QuantumCircuit` objects that contained delays could not be compiled to these backends.
qiskit/releasenotes/notes/0.21/delay-fake-backends-3f68c074e85d531f.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.21/delay-fake-backends-3f68c074e85d531f.yaml", "repo_id": "qiskit", "token_count": 140 }
266
--- deprecations: - | The ``qiskit.test.mock`` module is now deprecated. The fake backend and fake provider classes which were previously available in ``qiskit.test.mock`` have been accessible in :mod:`qiskit.providers.fake_provider` since Terra 0.20.0. This change represents a proper commitment to support the fake backend classes as part of Qiskit, whereas previously they were just part of the internal testing suite, and were exposed to users as a side effect.
qiskit/releasenotes/notes/0.21/move-qiskit.test.mock-to-qiskit.providers.fake_provider-7f36ff80a05f9a9a.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.21/move-qiskit.test.mock-to-qiskit.providers.fake_provider-7f36ff80a05f9a9a.yaml", "repo_id": "qiskit", "token_count": 138 }
267
--- features: - | Classes in the :mod:`.quantum_info` module that support scalar multiplication can now be multiplied by a scalar from either the left or the right. Previously, they would only accept scalar multipliers from the left.
qiskit/releasenotes/notes/0.21/scaler-multiplication-left-side-7bea0d73f9afabe2.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.21/scaler-multiplication-left-side-7bea0d73f9afabe2.yaml", "repo_id": "qiskit", "token_count": 69 }
268
--- features: - | Added :mod:`qiskit.algorithms.eigensolvers` package to include interfaces for primitive-enabled algorithms. This new module will eventually replace the previous ``qiskit.algorithms.eigen_solvers``. This new module contains an alternative implementation of the :class:`~qiskit.algorithms.eigensolvers.VQD` which instead of taking a backend or :class:`~.QuantumInstance` instead takes an instance of :class:`~.BaseEstimator`, including :class:`~.Estimator`, :class:`~.BackendEstimator`, or any provider implementations such as those as those present in ``qiskit-ibm-runtime`` and ``qiskit-aer``. For example, to use the new implementation with an instance of :class:`~.Estimator` class: .. code-block:: python from qiskit.algorithms.eigensolvers import VQD from qiskit.algorithms.optimizers import SLSQP from qiskit.circuit.library import TwoLocal from qiskit.primitives import Sampler, Estimator from qiskit.algorithms.state_fidelities import ComputeUncompute from qiskit.opflow import PauliSumOp from qiskit.quantum_info import SparsePauliOp h2_op = PauliSumOp(SparsePauliOp( ["II", "IZ", "ZI", "ZZ", "XX"], coeffs=[ -1.052373245772859, 0.39793742484318045, -0.39793742484318045, -0.01128010425623538, 0.18093119978423156, ], )) estimator = Estimator() ansatz = TwoLocal(rotation_blocks=["ry", "rz"], entanglement_blocks="cz") optimizer = SLSQP() fidelity = ComputeUncompute(Sampler()) vqd = VQD(estimator, fidelity, ansatz, optimizer, k=2) result = vqd.compute_eigenvalues(h2_op) eigenvalues = result.eigenvalues Note that the evaluated auxillary operators are now obtained via the ``aux_operators_evaluated`` field on the results. This will consist of a list or dict of tuples containing the expectation values for these operators, as we well as the metadata from primitive run. ``aux_operator_eigenvalues`` is no longer a valid field.
qiskit/releasenotes/notes/0.22/add-eigensolvers-with-primitives-8b3a9f55f5fd285f.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.22/add-eigensolvers-with-primitives-8b3a9f55f5fd285f.yaml", "repo_id": "qiskit", "token_count": 889 }
269
--- features: - | A new transpiler pass, :class:`.ConvertConditionsToIfOps` was added, which can be used to convert old-style :meth:`.Instruction.c_if`-conditioned instructions into :class:`.IfElseOp` objects. This is to help ease the transition from the old type to the new type for backends. For most users, there is no need to add this to your pass managers, and it is not included in any preset pass managers.
qiskit/releasenotes/notes/0.22/c_if-to-if_else-converter-2d48046de31814a8.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.22/c_if-to-if_else-converter-2d48046de31814a8.yaml", "repo_id": "qiskit", "token_count": 139 }
270
--- fixes: - | Fixed initialization of empty symplectic matrix in :meth:`~.PauliList.from_symplectic` in :class:`~.PauliList` class For example:: from qiskit.quantum_info.operators import PauliList x = np.array([], dtype=bool).reshape((1,0)) z = np.array([], dtype=bool).reshape((1,0)) pauli_list = PauliList.from_symplectic(x, z)
qiskit/releasenotes/notes/0.22/fix-empty-string-pauli-list-init-4d978fb0eaf1bc70.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.22/fix-empty-string-pauli-list-init-4d978fb0eaf1bc70.yaml", "repo_id": "qiskit", "token_count": 163 }
271
--- features: - | Added a new abstract class :class:`~.ClassicalIOChannel` to the :mod:`qiskit.pulse.channels` module. This class is used to represent classical I/O channels and differentiate these channels from other subclasses of :class:`~qiskit.pulse.channels.Channel`. This new class is the base class for the :class:`~.MemorySlot`, :class:`~.RegisterSlot`, and :class:`~.SnapshotChannel` classes. Accordingly, the :func:`~qiskit.pulse.transforms.pad` canonicalization pulse transform in :mod:`qiskit.pulse.transforms` will not introduce delays to any instances of :class:`~.ClassicalIOChannel` upgrade: - | The constructors for the :class:`~.SetPhase`, :class:`~.ShiftPhase`, :class:`~.SetFrequency`, and :class:`~.ShiftFrequency` classes will now raise a :class:`~.PulseError` if the value passed in via the ``channel`` argument is not an instance of :class:`~.PulseChannel`. This change was made to validate the input to the constructors are valid as the instructions are only valid for pulse channels and not other types of channels.
qiskit/releasenotes/notes/0.22/introduce-classical-io-channel-0a616e6ca75b7687.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.22/introduce-classical-io-channel-0a616e6ca75b7687.yaml", "repo_id": "qiskit", "token_count": 366 }
272
--- upgrade: - | The ``qiskit.pulse.builder`` contexts ``inline`` and ``pad`` have been removed. These were first deprecated in Terra 0.18.0 (July 2021). There is no replacement for ``inline``; one can simply write the pulses in the containing scope. The ``pad`` context manager has had no effect since it was deprecated.
qiskit/releasenotes/notes/0.22/qiskit.pulse.builder-ddefe88dca5765b9.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.22/qiskit.pulse.builder-ddefe88dca5765b9.yaml", "repo_id": "qiskit", "token_count": 106 }
273
--- fixes: - | The function :func:`~qiskit.visualization.state_visualization.state_to_latex` produced not valid LaTeX in presence of close-to-zero values, resulting in errors when :func:`~qiskit.visualization.state_visualization.state_drawer` is called. Fixed `#8169 <https://github.com/Qiskit/qiskit-terra/issues/8169>`__.
qiskit/releasenotes/notes/0.22/state_to_latex_for_none-da834de3811640ce.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.22/state_to_latex_for_none-da834de3811640ce.yaml", "repo_id": "qiskit", "token_count": 124 }
274
--- features: - | Added a new base transpiler pass, :class:`~CollectAndCollapse`, to collect and to consolidate blocks of nodes in a circuit. To be completely general, this pass depends on two functions: the collection function and the collapsing function. The collection function ``collect_function`` takes a DAG and returns a list of blocks. The collapsing function ``collapse_function`` takes a DAG and a list of blocks, consolidates each block, and returns the modified DAG. As two examples, the inherited :class:`~CollectLinearFunctions` collects blocks of :class:`.CXGate` and :class:`.SwapGate` gates, and replaces each block with a :class:`.LinearFunction`, while the inherited class :class:`~CollectCliffords` collects blocks of "Clifford" gates and replaces each block with a :class:`qiskit.quantum_info.Clifford`. To allow code reuse between the collection and collapsing functions of inherited classes, added a new class :class:`~BlockCollector` that implements various collection strategies, and a new class :class:`~BlockCollapser` that implements various collapsing strategies. Currently :class:`~BlockCollector` includes the strategy to greedily collect all gates adhering to a given filter function (for example, collecting all Clifford gates), and :class:`~BlockCollapser` includes the strategy to consolidate all gates in a block to a single object (or example, a block of Clifford gates can be consolidated to a single ``Clifford``). The interface also supports the option ``do_commutative_analysis``, which allows to exploit commutativity between gates in order to collect larger blocks of nodes. As an example, collecting blocks of CX gates in the following circuit:: qc = QuantumCircuit(2) qc.cx(0, 1) qc.z(0) qc.cx(1, 0) allows to consolidate the two CX gates, as the first CX gate and the Z-gate commute. - | Added a new :class:`~CollectCliffords` transpiler pass that collects blocks of clifford gates and consolidates these blocks into :class:`qiskit.quantum_info.Clifford` objects. This pass inherits from :class:`~CollectAndCollapse` and in particular supports the option ``do_commutative_analysis``. It also supports two additional options ``split_blocks`` and ``min_block_size``. See the release notes for :class:`~CollectAndCollapse` and :class:`~CollectLinearFunctions` for additional details. upgrade: - | Modified the :class:`~CollectLinearFunctions` transpiler pass to inherit from :class:`~CollectAndCollapse`. In particular it supports the option ``do_commutative_analysis`` that allows to exploit commutativity between gates in order to collect larger blocks of nodes. See the release notes for :class:`~CollectAndCollapse` for an explicit example. In addition, :class:`~CollectLinearFunctions` supports new options ``split_blocks`` and ``min_block_size``. The option ``split_blocks`` allows to split collected blocks into sub-blocks over disjoint subsets of qubits. As an example, in the following circuit:: qc = QuantumCircuit(4) qc.cx(0, 2) qc.cx(1, 3) qc.cx(2, 0) qc.cx(3, 1) qc.cx(1, 3) the single block of CX gates over qubits ``{0, 1, 2, 3}`` can be split into two disjoint sub-blocks, one over qubits ``{0, 2}`` and the other over qubits ``{1, 3}``. The option ``min_block_size`` allows to specify the minimum size of the block to be consolidated, blocks with fewer gates will not be modified. As an example, in the following circuit:: qc = QuantumCircuit(4) qc.cx(1, 2) qc.cx(2, 1) the two CX gates will be consolidated when ``min_block_size`` is 1 or 2, and will remain unchanged when ``min_block_size`` is 3 or larger.
qiskit/releasenotes/notes/0.23/add-collect-and-collapse-pass-d4411b682bd03294.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.23/add-collect-and-collapse-pass-d4411b682bd03294.yaml", "repo_id": "qiskit", "token_count": 1254 }
275
--- features: - | The OpenQASM 2 exporter (:meth:`.QuantumCircuit.qasm`) will now emit higher precision floating point numbers for gate parameters per default. This is accomplished by relying on Python's built-in float formatting in case no suitable approximation to some power/fraction of `pi` can be found. In addition, a tighter bound (`1e-12` instead of `1e-6`) is used for checking whether a given parameter is close to a fraction/power of `pi`. Fixed `#7166 <https://github.com/Qiskit/qiskit-terra/issues/7166>`__.
qiskit/releasenotes/notes/0.23/change-qasm-float-output-d69d0c2896f8ecbb.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.23/change-qasm-float-output-d69d0c2896f8ecbb.yaml", "repo_id": "qiskit", "token_count": 178 }
276
fixes: - | Fixed an issue with the approximate quantum compiler (:class:`~qiskit.transpiler.synthesis.aqc.AQC`) that caused it to return a wrong circuit when the unitary has a determinant βˆ’1.
qiskit/releasenotes/notes/0.23/fix-aqc-check-if-su-matrix.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.23/fix-aqc-check-if-su-matrix.yaml", "repo_id": "qiskit", "token_count": 72 }
277
--- fixes: - | Fixed an issue with :class:`~qiskit.algorithms.eigensolvers.NumPyEigensolver` and by extension :class:`~qiskit.algorithms.minimum_eigensolvers.NumPyMinimumEigensolver` where solving for :class:`~qiskit.quantum_info.operators.base_operator.BaseOperator` subclasses other than :class:`~qiskit.quantum_info.operators.Operator` would cause an error.
qiskit/releasenotes/notes/0.23/fix-numpy-eigensolver-sparse-pauli-op-b09a9ac8fb93fe4a.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.23/fix-numpy-eigensolver-sparse-pauli-op-b09a9ac8fb93fe4a.yaml", "repo_id": "qiskit", "token_count": 156 }
278
--- fixes: - | Fixed an issue with the :func:`~.transpile` where it would previously fail with a ``TypeError`` if a custom :class:`~.Target` object was passed in via the ``target`` argument and a list of multiple circuits were specified for the ``circuits`` argument.
qiskit/releasenotes/notes/0.23/fix-target-transpile-parallel-772f943a08d0570b.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.23/fix-target-transpile-parallel-772f943a08d0570b.yaml", "repo_id": "qiskit", "token_count": 88 }
279
--- features: - | Extending :class:`~CollectCliffords` transpiler pass to collect and combine blocks of "clifford gates" into :class:`qiskit.quantum_info.Clifford` objects, where the "clifford gates" may now also include objects of type :class:`.LinearFunction`, :class:`qiskit.quantum_info.Clifford`, and :class:`~qiskit.circuit.library.PauliGate`. As an example:: from qiskit.circuit import QuantumCircuit from qiskit.circuit.library import LinearFunction, PauliGate from qiskit.quantum_info.operators import Clifford from qiskit.transpiler.passes import CollectCliffords from qiskit.transpiler import PassManager # Create a Clifford cliff_circuit = QuantumCircuit(2) cliff_circuit.cx(0, 1) cliff_circuit.h(0) cliff = Clifford(cliff_circuit) # Create a linear function lf = LinearFunction([[0, 1], [1, 0]]) # Create a pauli gate pauli_gate = PauliGate("XYZ") # Create a quantum circuit with the above and also simple clifford gates. qc = QuantumCircuit(4) qc.cz(0, 1) qc.append(cliff, [0, 1]) qc.h(0) qc.append(lf, [0, 2]) qc.append(pauli_gate, [0, 2, 1]) qc.x(2) # Run CollectCliffords transpiler pass qct = PassManager(CollectCliffords()).run(qc) All the gates will be collected and combined into a single Clifford. Thus the final circuit consists of a single Clifford object. fixes: - | Restoring the functionality to construct :class:`qiskit.quantum_info.Clifford` objects from quantum circuits containing other :class:`qiskit.quantum_info.Clifford` objects.
qiskit/releasenotes/notes/0.23/improve-collect-cliffords-f57aeafe95460b18.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.23/improve-collect-cliffords-f57aeafe95460b18.yaml", "repo_id": "qiskit", "token_count": 705 }
280
--- upgrade: - | Methods inherited from ``set`` have been removed from :class:`.ParameterView`, the type returned by :attr:`.QuantumCircuit.parameters`. These were deprecated since Terra 0.17; this type has been a general view type since then.
qiskit/releasenotes/notes/0.23/remove-deprecated-parameterview-cc08100049605b73.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.23/remove-deprecated-parameterview-cc08100049605b73.yaml", "repo_id": "qiskit", "token_count": 76 }
281
--- features: - | Added the :class:`.ReverseEstimatorGradient` class for a classical, fast evaluation of expectation value gradients based on backpropagation or reverse-mode gradients. This class uses statevectors and thus provides exact gradients but scales exponentially in system size. It is designed for fast reference calculation of smaller system sizes. It can for example be used as:: from qiskit.circuit.library import EfficientSU2 from qiskit.quantum_info import SparsePauliOp from qiskit.algorithms.gradients import ReverseEstimatorGradient observable = SparsePauliOp.from_sparse_list([("ZZ", [0, 1], 1)], num_qubits=10) circuit = EfficientSU2(num_qubits=10) values = [i / 100 for i in range(circuit.num_parameters)] gradient = ReverseEstimatorGradient() result = gradient.run([circuit], [observable], [values]).result()
qiskit/releasenotes/notes/0.23/turbo-gradients-5bebc6e665b900b2.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.23/turbo-gradients-5bebc6e665b900b2.yaml", "repo_id": "qiskit", "token_count": 299 }
282
--- features: - | Added :class:`.GlobalPhaseGate` which can be applied to add a global phase on the :class:`.QuantumCircuit`.
qiskit/releasenotes/notes/0.24/add-global-phase-gate-b52c5b25ab8a3cf6.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.24/add-global-phase-gate-b52c5b25ab8a3cf6.yaml", "repo_id": "qiskit", "token_count": 46 }
283
--- features: - | Adds a flag ``local`` to the :class:`~.ComputeUncompute` state fidelity class that allows to compute the local fidelity, which is defined by averaging over single-qubit projectors.
qiskit/releasenotes/notes/0.24/computeuncompute-local-fidelity-501fe175762b7593.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.24/computeuncompute-local-fidelity-501fe175762b7593.yaml", "repo_id": "qiskit", "token_count": 67 }
284
--- fixes: - | The return type of `qiskit.transpiler.passmanager.PassManager.run` is now always the same as that of its first argument. Passing a single circuit returns a single circuit, passing a list of circuits, even of length 1, returns a list of circuits. See `#9798 <https://github.com/Qiskit/qiskit-terra/issues/9798>`.
qiskit/releasenotes/notes/0.24/fix-9798-30c0eb0e5181b691.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.24/fix-9798-30c0eb0e5181b691.yaml", "repo_id": "qiskit", "token_count": 117 }
285
--- fixes: - | Fixed an issue with the :meth:`.InstructionScheduleMap.has_custom_gate` method, where it would always return ``True`` when the :class:`~.InstructionScheduleMap` object was created by :class:`.Target`. Fixed `#9595 <https://github.com/Qiskit/qiskit-terra/issues/9595>`__
qiskit/releasenotes/notes/0.24/fix-instmap-from-target-f38962c3fd03e5d3.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.24/fix-instmap-from-target-f38962c3fd03e5d3.yaml", "repo_id": "qiskit", "token_count": 111 }
286
--- fixes: - | Manually setting an item in :attr:`.QuantumCircuit.data` will now correctly allow the operation to be any object that implements :class:`.Operation`, not just a :class:`.circuit.Instruction`. Note that any manual mutation of :attr:`.QuantumCircuit.data` is discouraged; it is not *usually* any more efficient than building a new circuit object, as checking the invariants surrounding parametrized objects can be surprisingly expensive.
qiskit/releasenotes/notes/0.24/fix-setting-circuit-data-operation-1b8326b1b089f10c.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.24/fix-setting-circuit-data-operation-1b8326b1b089f10c.yaml", "repo_id": "qiskit", "token_count": 129 }
287
--- features: - | The :class:`qiskit.providers.options.Options` class now implements the :class`Mapping` and `__setitem__`. :class:`Options` instances therefore now offer the same interface as standard dictionaries, except for the deletion methods (`__delitem__`, `pop`, `clear`). Key assignments are validated by the registered validators, if any. See `#9686 <https://github.com/Qiskit/qiskit-terra/issues/9686>`. upgrade: - | Instances of `options.__dict__.items()` and related calls can be replaced by the same call without the `__dict__` proxy (e.g. `options.items()`).
qiskit/releasenotes/notes/0.24/options-implement-mutable-mapping-b11f4e2c6df4cf31.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.24/options-implement-mutable-mapping-b11f4e2c6df4cf31.yaml", "repo_id": "qiskit", "token_count": 204 }
288
--- features: - | Modifies the drawer for the :class:`~.transpiler.StagedPassManager` to add an outer box around the passes for each stage.
qiskit/releasenotes/notes/0.24/staged-pass-manager-drawer-f1da0308895a30d9.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.24/staged-pass-manager-drawer-f1da0308895a30d9.yaml", "repo_id": "qiskit", "token_count": 46 }
289
--- fixes: - | Updated :func:`~qiskit.visualization.plot_gate_map`, :func:`~qiskit.visualization.plot_error_map`, and :func:`~qiskit.visualization.plot_circuit_layout` to support 433 qubit heavy-hex coupling maps. This allows coupling map visualizations for IBM's ``ibm_seattle``.
qiskit/releasenotes/notes/0.25/433_qubit_coordinates_map-8abc318fefdb99ac.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.25/433_qubit_coordinates_map-8abc318fefdb99ac.yaml", "repo_id": "qiskit", "token_count": 98 }
290
--- features: - | Added a new synthesis algorithm :func:`qiskit.synthesis.linear_phase.synth_cx_cz_depth_line_my` of a CX circuit followed by a CZ circuit for linear nearest neighbor (LNN) connectivity in 2-qubit depth of at most 5n using CX and phase gates (S, Sdg or Z). The synthesis algorithm is based on the paper of Maslov and Yang (https://arxiv.org/abs/2210.16195). The algorithm accepts a binary invertible matrix ``mat_x`` representing the CX-circuit, a binary symmetric matrix ``mat_z`` representing the CZ-circuit, and returns a quantum circuit with 2-qubit depth of at most 5n computing the composition of the CX and CZ circuits. The following example illustrates the new functionality:: import numpy as np from qiskit.synthesis.linear_phase import synth_cx_cz_depth_line_my mat_x = np.array([[0, 1], [1, 1]]) mat_z = np.array([[0, 1], [1, 0]]) qc = synth_cx_cz_depth_line_my(mat_x, mat_z) This algorithm is now used by default in the Clifford synthesis algorithm :func:`qiskit.synthesis.clifford.synth_clifford_depth_lnn` that optimizes 2-qubit depth for LNN connectivity, improving the 2-qubit depth from 9n+4 to 7n+2. The clifford synthesis algorithm can be used as follows:: from qiskit.quantum_info import random_clifford from qiskit.synthesis import synth_clifford_depth_lnn cliff = random_clifford(3) qc = synth_clifford_depth_lnn(cliff) The above synthesis can be further improved as described in the paper by Maslov and Yang, using local optimization between 2-qubit layers. This improvement is left for follow-up work.
qiskit/releasenotes/notes/0.25/cx_cz_synthesis-3d5ec98372ce1608.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.25/cx_cz_synthesis-3d5ec98372ce1608.yaml", "repo_id": "qiskit", "token_count": 600 }
291
--- fixes: - | Construction of a :class:`~.quantum_info.Statevector` from a :class:`.QuantumCircuit` containing zero-qubit operations will no longer raise an error. These operations impart a global phase on the resulting statevector.
qiskit/releasenotes/notes/0.25/fix-0q-operator-statevector-79199c65c24637c4.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.25/fix-0q-operator-statevector-79199c65c24637c4.yaml", "repo_id": "qiskit", "token_count": 75 }
292
--- fixes: - | Fixed the dimensions of the output density matrix from :meth:`.DensityMatrix.partial_transpose` so they match the dimensions of the corresponding input density matrix.
qiskit/releasenotes/notes/0.25/fix-partial-transpose-output-dims-3082fcf4147055dc.yaml/0
{ "file_path": "qiskit/releasenotes/notes/0.25/fix-partial-transpose-output-dims-3082fcf4147055dc.yaml", "repo_id": "qiskit", "token_count": 52 }
293