repo
stringclasses
900 values
file
stringclasses
754 values
content
stringlengths
4
215k
https://github.com/swe-train/qiskit__qiskit
swe-train
# 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. """ Core module of the timeline drawer. This module provides the `DrawerCanvas` which is a collection of drawings. The canvas instance is not just a container of drawing objects, as it also performs data processing like binding abstract coordinates. Initialization ~~~~~~~~~~~~~~ The `DataCanvas` is not exposed to users as they are implicitly initialized in the interface function. It is noteworthy that the data canvas is agnostic to plotters. This means once the canvas instance is initialized we can reuse this data among multiple plotters. The canvas is initialized with a stylesheet. ```python canvas = DrawerCanvas(stylesheet=stylesheet) canvas.load_program(sched) canvas.update() ``` Once all properties are set, `.update` method is called to apply changes to drawings. Update ~~~~~~ To update the image, a user can set new values to canvas and then call the `.update` method. ```python canvas.set_time_range(2000, 3000) canvas.update() ``` All stored drawings are updated accordingly. The plotter API can access to drawings with `.collections` property of the canvas instance. This returns an iterator of drawings with the unique data key. If a plotter provides object handler for plotted shapes, the plotter API can manage the lookup table of the handler and the drawings by using this data key. """ from __future__ import annotations import warnings from collections.abc import Iterator from copy import deepcopy from functools import partial from enum import Enum import numpy as np from qiskit import circuit from qiskit.visualization.exceptions import VisualizationError from qiskit.visualization.timeline import drawings, types from qiskit.visualization.timeline.stylesheet import QiskitTimelineStyle class DrawerCanvas: """Data container for drawings.""" def __init__(self, stylesheet: QiskitTimelineStyle): """Create new data container.""" # stylesheet self.formatter = stylesheet.formatter self.generator = stylesheet.generator self.layout = stylesheet.layout # drawings self._collections: dict[str, drawings.ElementaryData] = {} self._output_dataset: dict[str, drawings.ElementaryData] = {} # vertical offset of bits self.bits: list[types.Bits] = [] self.assigned_coordinates: dict[types.Bits, float] = {} # visible controls self.disable_bits: set[types.Bits] = set() self.disable_types: set[str] = set() # time self._time_range = (0, 0) # graph height self.vmax = 0 self.vmin = 0 @property def time_range(self) -> tuple[int, int]: """Return current time range to draw. Calculate net duration and add side margin to edge location. Returns: Time window considering side margin. """ t0, t1 = self._time_range duration = t1 - t0 new_t0 = t0 - duration * self.formatter["margin.left_percent"] new_t1 = t1 + duration * self.formatter["margin.right_percent"] return new_t0, new_t1 @time_range.setter def time_range(self, new_range: tuple[int, int]): """Update time range to draw.""" self._time_range = new_range @property def collections(self) -> Iterator[tuple[str, drawings.ElementaryData]]: """Return currently active entries from drawing data collection. The object is returned with unique name as a key of an object handler. When the horizontal coordinate contains `AbstractCoordinate`, the value is substituted by current time range preference. """ yield from self._output_dataset.items() def add_data(self, data: drawings.ElementaryData): """Add drawing to collections. If the given object already exists in the collections, this interface replaces the old object instead of adding new entry. Args: data: New drawing to add. """ if not self.formatter["control.show_clbits"]: data.bits = [b for b in data.bits if not isinstance(b, circuit.Clbit)] self._collections[data.data_key] = data # pylint: disable=cyclic-import def load_program(self, program: circuit.QuantumCircuit): """Load quantum circuit and create drawing.. Args: program: Scheduled circuit object to draw. Raises: VisualizationError: When circuit is not scheduled. """ not_gate_like = (circuit.Barrier,) if getattr(program, "_op_start_times") is None: # Run scheduling for backward compatibility from qiskit import transpile from qiskit.transpiler import InstructionDurations, TranspilerError warnings.warn( "Visualizing un-scheduled circuit with timeline drawer has been deprecated. " "This circuit should be transpiled with scheduler though it consists of " "instructions with explicit durations.", DeprecationWarning, ) try: program = transpile( program, scheduling_method="alap", instruction_durations=InstructionDurations(), optimization_level=0, ) except TranspilerError as ex: raise VisualizationError( f"Input circuit {program.name} is not scheduled and it contains " "operations with unknown delays. This cannot be visualized." ) from ex for t0, instruction in zip(program.op_start_times, program.data): bits = list(instruction.qubits) + list(instruction.clbits) for bit_pos, bit in enumerate(bits): if not isinstance(instruction.operation, not_gate_like): # Generate draw object for gates gate_source = types.ScheduledGate( t0=t0, operand=instruction.operation, duration=instruction.operation.duration, bits=bits, bit_position=bit_pos, ) for gen in self.generator["gates"]: obj_generator = partial(gen, formatter=self.formatter) for datum in obj_generator(gate_source): self.add_data(datum) if len(bits) > 1 and bit_pos == 0: # Generate draw object for gate-gate link line_pos = t0 + 0.5 * instruction.operation.duration link_source = types.GateLink( t0=line_pos, opname=instruction.operation.name, bits=bits ) for gen in self.generator["gate_links"]: obj_generator = partial(gen, formatter=self.formatter) for datum in obj_generator(link_source): self.add_data(datum) if isinstance(instruction.operation, circuit.Barrier): # Generate draw object for barrier barrier_source = types.Barrier(t0=t0, bits=bits, bit_position=bit_pos) for gen in self.generator["barriers"]: obj_generator = partial(gen, formatter=self.formatter) for datum in obj_generator(barrier_source): self.add_data(datum) self.bits = list(program.qubits) + list(program.clbits) for bit in self.bits: for gen in self.generator["bits"]: # Generate draw objects for bit obj_generator = partial(gen, formatter=self.formatter) for datum in obj_generator(bit): self.add_data(datum) # update time range t_end = max(program.duration, self.formatter["margin.minimum_duration"]) self.set_time_range(t_start=0, t_end=t_end) def set_time_range(self, t_start: int, t_end: int): """Set time range to draw. Args: t_start: Left boundary of drawing in units of cycle time. t_end: Right boundary of drawing in units of cycle time. """ self.time_range = (t_start, t_end) def set_disable_bits(self, bit: types.Bits, remove: bool = True): """Interface method to control visibility of bits. Specified object in the blocked list will not be shown. Args: bit: A qubit or classical bit object to disable. remove: Set `True` to disable, set `False` to enable. """ if remove: self.disable_bits.add(bit) else: self.disable_bits.discard(bit) def set_disable_type(self, data_type: types.DataTypes, remove: bool = True): """Interface method to control visibility of data types. Specified object in the blocked list will not be shown. Args: data_type: A drawing data type to disable. remove: Set `True` to disable, set `False` to enable. """ if isinstance(data_type, Enum): data_type_str = str(data_type.value) else: data_type_str = data_type if remove: self.disable_types.add(data_type_str) else: self.disable_types.discard(data_type_str) def update(self): """Update all collections. This method should be called before the canvas is passed to the plotter. """ self._output_dataset.clear() self.assigned_coordinates.clear() # update coordinate y0 = -self.formatter["margin.top"] for bit in self.layout["bit_arrange"](self.bits): # remove classical bit if isinstance(bit, circuit.Clbit) and not self.formatter["control.show_clbits"]: continue # remove idle bit if not self._check_bit_visible(bit): continue offset = y0 - 0.5 self.assigned_coordinates[bit] = offset y0 = offset - 0.5 self.vmax = 0 self.vmin = y0 - self.formatter["margin.bottom"] # add data temp_gate_links = {} temp_data = {} for data_key, data in self._collections.items(): # deep copy to keep original data hash new_data = deepcopy(data) new_data.xvals = self._bind_coordinate(data.xvals) new_data.yvals = self._bind_coordinate(data.yvals) if data.data_type == str(types.LineType.GATE_LINK.value): temp_gate_links[data_key] = new_data else: temp_data[data_key] = new_data # update horizontal offset of gate links temp_data.update(self._check_link_overlap(temp_gate_links)) # push valid data for data_key, data in temp_data.items(): if self._check_data_visible(data): self._output_dataset[data_key] = data def _check_data_visible(self, data: drawings.ElementaryData) -> bool: """A helper function to check if the data is visible. Args: data: Drawing object to test. Returns: Return `True` if the data is visible. """ _barriers = [str(types.LineType.BARRIER.value)] _delays = [str(types.BoxType.DELAY.value), str(types.LabelType.DELAY.value)] def _time_range_check(_data): """If data is located outside the current time range.""" t0, t1 = self.time_range if np.max(_data.xvals) < t0 or np.min(_data.xvals) > t1: return False return True def _associated_bit_check(_data): """If any associated bit is not shown.""" if all(bit not in self.assigned_coordinates for bit in _data.bits): return False return True def _data_check(_data): """If data is valid.""" if _data.data_type == str(types.LineType.GATE_LINK.value): active_bits = [bit for bit in _data.bits if bit not in self.disable_bits] if len(active_bits) < 2: return False elif _data.data_type in _barriers and not self.formatter["control.show_barriers"]: return False elif _data.data_type in _delays and not self.formatter["control.show_delays"]: return False return True checks = [_time_range_check, _associated_bit_check, _data_check] if all(check(data) for check in checks): return True return False def _check_bit_visible(self, bit: types.Bits) -> bool: """A helper function to check if the bit is visible. Args: bit: Bit object to test. Returns: Return `True` if the bit is visible. """ _gates = [str(types.BoxType.SCHED_GATE.value), str(types.SymbolType.FRAME.value)] if bit in self.disable_bits: return False if self.formatter["control.show_idle"]: return True for data in self._collections.values(): if bit in data.bits and data.data_type in _gates: return True return False def _bind_coordinate(self, vals: Iterator[types.Coordinate]) -> np.ndarray: """A helper function to bind actual coordinates to an `AbstractCoordinate`. Args: vals: Sequence of coordinate objects associated with a drawing. Returns: Numpy data array with substituted values. """ def substitute(val: types.Coordinate): if val == types.AbstractCoordinate.LEFT: return self.time_range[0] if val == types.AbstractCoordinate.RIGHT: return self.time_range[1] if val == types.AbstractCoordinate.TOP: return self.vmax if val == types.AbstractCoordinate.BOTTOM: return self.vmin raise VisualizationError(f"Coordinate {val} is not supported.") try: return np.asarray(vals, dtype=float) except TypeError: return np.asarray(list(map(substitute, vals)), dtype=float) def _check_link_overlap( self, links: dict[str, drawings.GateLinkData] ) -> dict[str, drawings.GateLinkData]: """Helper method to check overlap of bit links. This method dynamically shifts horizontal position of links if they are overlapped. """ duration = self.time_range[1] - self.time_range[0] allowed_overlap = self.formatter["margin.link_interval_percent"] * duration # return y coordinates def y_coords(link: drawings.GateLinkData): return np.array([self.assigned_coordinates.get(bit, np.nan) for bit in link.bits]) # group overlapped links overlapped_group: list[list[str]] = [] data_keys = list(links.keys()) while len(data_keys) > 0: ref_key = data_keys.pop() overlaps = set() overlaps.add(ref_key) for key in data_keys[::-1]: # check horizontal overlap if np.abs(links[ref_key].xvals[0] - links[key].xvals[0]) < allowed_overlap: # check vertical overlap y0s = y_coords(links[ref_key]) y1s = y_coords(links[key]) v1 = np.nanmin(y0s) - np.nanmin(y1s) v2 = np.nanmax(y0s) - np.nanmax(y1s) v3 = np.nanmin(y0s) - np.nanmax(y1s) v4 = np.nanmax(y0s) - np.nanmin(y1s) if not (v1 * v2 > 0 and v3 * v4 > 0): overlaps.add(data_keys.pop(data_keys.index(key))) overlapped_group.append(list(overlaps)) # renew horizontal offset new_links = {} for overlaps in overlapped_group: if len(overlaps) > 1: xpos_mean = np.mean([links[key].xvals[0] for key in overlaps]) # sort link key by y position sorted_keys = sorted(overlaps, key=lambda x: np.nanmax(y_coords(links[x]))) x0 = xpos_mean - 0.5 * allowed_overlap * (len(overlaps) - 1) for ind, key in enumerate(sorted_keys): data = links[key] data.xvals = [x0 + ind * allowed_overlap] new_links[key] = data else: key = overlaps[0] new_links[key] = links[key] return {key: new_links[key] for key in links.keys()}
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """A collection of backend information formatted to generate drawing data. This instance will be provided to generator functions. The module provides an abstract class :py:class:``DrawerBackendInfo`` with necessary methods to generate drawing objects. Because the data structure of backend class may depend on providers, this abstract class has an abstract factory method `create_from_backend`. Each subclass should provide the factory method which conforms to the associated provider. By default we provide :py:class:``OpenPulseBackendInfo`` class that has the factory method taking backends satisfying OpenPulse specification [1]. This class can be also initialized without the factory method by manually specifying required information. This may be convenient for visualizing a pulse program for simulator backend that only has a device Hamiltonian information. This requires two mapping objects for channel/qubit and channel/frequency along with the system cycle time. If those information are not provided, this class will be initialized with a set of empty data and the drawer illustrates a pulse program without any specific information. Reference: - [1] Qiskit Backend Specifications for OpenQASM and OpenPulse Experiments, https://arxiv.org/abs/1809.03452 """ from abc import ABC, abstractmethod from collections import defaultdict from typing import Dict, List, Union, Optional from qiskit import pulse from qiskit.providers import BackendConfigurationError from qiskit.providers.backend import Backend class DrawerBackendInfo(ABC): """Backend information to be used for the drawing data generation.""" def __init__( self, name: Optional[str] = None, dt: Optional[float] = None, channel_frequency_map: Optional[Dict[pulse.channels.Channel, float]] = None, qubit_channel_map: Optional[Dict[int, List[pulse.channels.Channel]]] = None, ): """Create new backend information. Args: name: Name of the backend. dt: System cycle time. channel_frequency_map: Mapping of channel and associated frequency. qubit_channel_map: Mapping of qubit and associated channels. """ self.backend_name = name or "no-backend" self._dt = dt self._chan_freq_map = channel_frequency_map or {} self._qubit_channel_map = qubit_channel_map or {} @classmethod @abstractmethod def create_from_backend(cls, backend: Backend): """Initialize a class with backend information provided by provider. Args: backend: Backend object. """ raise NotImplementedError @property def dt(self): """Return cycle time.""" return self._dt def get_qubit_index(self, chan: pulse.channels.Channel) -> Union[int, None]: """Get associated qubit index of given channel object.""" for qind, chans in self._qubit_channel_map.items(): if chan in chans: return qind return chan.index def get_channel_frequency(self, chan: pulse.channels.Channel) -> Union[float, None]: """Get frequency of given channel object.""" return self._chan_freq_map.get(chan, None) class OpenPulseBackendInfo(DrawerBackendInfo): """Drawing information of backend that conforms to OpenPulse specification.""" @classmethod def create_from_backend(cls, backend: Backend): """Initialize a class with backend information provided by provider. Args: backend: Backend object. Returns: OpenPulseBackendInfo: New configured instance. """ configuration = backend.configuration() defaults = backend.defaults() # load name name = backend.name() # load cycle time dt = configuration.dt # load frequencies chan_freqs = {} chan_freqs.update( {pulse.DriveChannel(qind): freq for qind, freq in enumerate(defaults.qubit_freq_est)} ) chan_freqs.update( {pulse.MeasureChannel(qind): freq for qind, freq in enumerate(defaults.meas_freq_est)} ) for qind, u_lo_mappers in enumerate(configuration.u_channel_lo): temp_val = 0.0 + 0.0j for u_lo_mapper in u_lo_mappers: temp_val += defaults.qubit_freq_est[u_lo_mapper.q] * u_lo_mapper.scale chan_freqs[pulse.ControlChannel(qind)] = temp_val.real # load qubit channel mapping qubit_channel_map = defaultdict(list) for qind in range(configuration.n_qubits): qubit_channel_map[qind].append(configuration.drive(qubit=qind)) qubit_channel_map[qind].append(configuration.measure(qubit=qind)) for tind in range(configuration.n_qubits): try: qubit_channel_map[qind].extend(configuration.control(qubits=(qind, tind))) except BackendConfigurationError: pass return OpenPulseBackendInfo( name=name, dt=dt, channel_frequency_map=chan_freqs, qubit_channel_map=qubit_channel_map )
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. r""" Channel event manager for pulse schedules. This module provides a `ChannelEvents` class that manages a series of instructions for a pulse channel. Channel-wise filtering of the pulse program makes the arrangement of channels easier in the core drawer function. The `ChannelEvents` class is expected to be called by other programs (not by end-users). The `ChannelEvents` class instance is created with the class method ``load_program``: .. code-block:: python event = ChannelEvents.load_program(sched, DriveChannel(0)) The `ChannelEvents` is created for a specific pulse channel and loosely assorts pulse instructions within the channel with different visualization purposes. Phase and frequency related instructions are loosely grouped as frame changes. The instantaneous value of those operands are combined and provided as ``PhaseFreqTuple``. Instructions that have finite duration are grouped as waveforms. The grouped instructions are returned as an iterator by the corresponding method call: .. code-block:: python for t0, frame, instruction in event.get_waveforms(): ... for t0, frame_change, instructions in event.get_frame_changes(): ... The class method ``get_waveforms`` returns the iterator of waveform type instructions with the ``PhaseFreqTuple`` (frame) at the time when instruction is issued. This is because a pulse envelope of ``Waveform`` may be modulated with a phase factor $exp(-i \omega t - \phi)$ with frequency $\omega$ and phase $\phi$ and appear on the canvas. Thus, it is better to tell users in which phase and frequency the pulse envelope is modulated from a viewpoint of program debugging. On the other hand, the class method ``get_frame_changes`` returns a ``PhaseFreqTuple`` that represents a total amount of change at that time because it is convenient to know the operand value itself when we debug a program. Because frame change type instructions are usually zero duration, multiple instructions can be issued at the same time and those operand values should be appropriately combined. In Qiskit Pulse we have set and shift type instructions for the frame control, the set type instruction will be converted into the relevant shift amount for visualization. Note that these instructions are not interchangeable and the order should be kept. For example: .. code-block:: python sched1 = Schedule() sched1 = sched1.insert(0, ShiftPhase(-1.57, DriveChannel(0)) sched1 = sched1.insert(0, SetPhase(3.14, DriveChannel(0)) sched2 = Schedule() sched2 = sched2.insert(0, SetPhase(3.14, DriveChannel(0)) sched2 = sched2.insert(0, ShiftPhase(-1.57, DriveChannel(0)) In this example, ``sched1`` and ``sched2`` will have different frames. On the drawer canvas, the total frame change amount of +3.14 should be shown for ``sched1``, while ``sched2`` is +1.57. Since the `SetPhase` and the `ShiftPhase` instruction behave differently, we cannot simply sum up the operand values in visualization output. It should be also noted that zero duration instructions issued at the same time will be overlapped on the canvas. Thus it is convenient to plot a total frame change amount rather than plotting each operand value bound to the instruction. """ from __future__ import annotations from collections import defaultdict from collections.abc import Iterator from qiskit import pulse, circuit from qiskit.visualization.pulse_v2.types import PhaseFreqTuple, PulseInstruction class ChannelEvents: """Channel event manager.""" _waveform_group = ( pulse.instructions.Play, pulse.instructions.Delay, pulse.instructions.Acquire, ) _frame_group = ( pulse.instructions.SetFrequency, pulse.instructions.ShiftFrequency, pulse.instructions.SetPhase, pulse.instructions.ShiftPhase, ) def __init__( self, waveforms: dict[int, pulse.Instruction], frames: dict[int, list[pulse.Instruction]], channel: pulse.channels.Channel, ): """Create new event manager. Args: waveforms: List of waveforms shown in this channel. frames: List of frame change type instructions shown in this channel. channel: Channel object associated with this manager. """ self._waveforms = waveforms self._frames = frames self.channel = channel # initial frame self._init_phase = 0.0 self._init_frequency = 0.0 # time resolution self._dt = 0.0 @classmethod def load_program(cls, program: pulse.Schedule, channel: pulse.channels.Channel): """Load a pulse program represented by ``Schedule``. Args: program: Target ``Schedule`` to visualize. channel: The channel managed by this instance. Returns: ChannelEvents: The channel event manager for the specified channel. """ waveforms = {} frames = defaultdict(list) # parse instructions for t0, inst in program.filter(channels=[channel]).instructions: if isinstance(inst, cls._waveform_group): if inst.duration == 0: # special case, duration of delay can be zero continue waveforms[t0] = inst elif isinstance(inst, cls._frame_group): frames[t0].append(inst) return ChannelEvents(waveforms, frames, channel) def set_config(self, dt: float, init_frequency: float, init_phase: float): """Setup system status. Args: dt: Time resolution in sec. init_frequency: Modulation frequency in Hz. init_phase: Initial phase in rad. """ self._dt = dt or 1.0 self._init_frequency = init_frequency or 0.0 self._init_phase = init_phase or 0.0 def get_waveforms(self) -> Iterator[PulseInstruction]: """Return waveform type instructions with frame.""" sorted_frame_changes = sorted(self._frames.items(), key=lambda x: x[0], reverse=True) sorted_waveforms = sorted(self._waveforms.items(), key=lambda x: x[0]) # bind phase and frequency with instruction phase = self._init_phase frequency = self._init_frequency for t0, inst in sorted_waveforms: is_opaque = False while len(sorted_frame_changes) > 0 and sorted_frame_changes[-1][0] <= t0: _, frame_changes = sorted_frame_changes.pop() phase, frequency = ChannelEvents._calculate_current_frame( frame_changes=frame_changes, phase=phase, frequency=frequency ) # Convert parameter expression into float if isinstance(phase, circuit.ParameterExpression): phase = float(phase.bind({param: 0 for param in phase.parameters})) if isinstance(frequency, circuit.ParameterExpression): frequency = float(frequency.bind({param: 0 for param in frequency.parameters})) frame = PhaseFreqTuple(phase, frequency) # Check if pulse has unbound parameters if isinstance(inst, pulse.Play): is_opaque = inst.pulse.is_parameterized() yield PulseInstruction(t0, self._dt, frame, inst, is_opaque) def get_frame_changes(self) -> Iterator[PulseInstruction]: """Return frame change type instructions with total frame change amount.""" # TODO parse parametrised FCs correctly sorted_frame_changes = sorted(self._frames.items(), key=lambda x: x[0]) phase = self._init_phase frequency = self._init_frequency for t0, frame_changes in sorted_frame_changes: is_opaque = False pre_phase = phase pre_frequency = frequency phase, frequency = ChannelEvents._calculate_current_frame( frame_changes=frame_changes, phase=phase, frequency=frequency ) # keep parameter expression to check either phase or frequency is parameterized frame = PhaseFreqTuple(phase - pre_phase, frequency - pre_frequency) # remove parameter expressions to find if next frame is parameterized if isinstance(phase, circuit.ParameterExpression): phase = float(phase.bind({param: 0 for param in phase.parameters})) is_opaque = True if isinstance(frequency, circuit.ParameterExpression): frequency = float(frequency.bind({param: 0 for param in frequency.parameters})) is_opaque = True yield PulseInstruction(t0, self._dt, frame, frame_changes, is_opaque) @classmethod def _calculate_current_frame( cls, frame_changes: list[pulse.instructions.Instruction], phase: float, frequency: float ) -> tuple[float, float]: """Calculate the current frame from the previous frame. If parameter is unbound phase or frequency accumulation with this instruction is skipped. Args: frame_changes: List of frame change instructions at a specific time. phase: Phase of previous frame. frequency: Frequency of previous frame. Returns: Phase and frequency of new frame. """ for frame_change in frame_changes: if isinstance(frame_change, pulse.instructions.SetFrequency): frequency = frame_change.frequency elif isinstance(frame_change, pulse.instructions.ShiftFrequency): frequency += frame_change.frequency elif isinstance(frame_change, pulse.instructions.SetPhase): phase = frame_change.phase elif isinstance(frame_change, pulse.instructions.ShiftPhase): phase += frame_change.phase return phase, frequency
https://github.com/swe-train/qiskit__qiskit
swe-train
# Copyright 2022-2023 Ohad Lev. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0, # or in the root directory of this package("LICENSE.txt"). # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ `SATInterface` class. """ import os import json from typing import List, Tuple, Union, Optional, Dict, Any from sys import stdout from datetime import datetime from hashlib import sha256 from qiskit import transpile, QuantumCircuit, qpy from qiskit.result.counts import Counts from qiskit.visualization.circuit.text import TextDrawing from qiskit.providers.backend import Backend from qiskit.transpiler.passes import RemoveBarriers from IPython import display from matplotlib.figure import Figure from sat_circuits_engine.util import timer_dec, timestamp, flatten_circuit from sat_circuits_engine.util.settings import DATA_PATH, TRANSPILE_KWARGS from sat_circuits_engine.circuit import GroverConstraintsOperator, SATCircuit from sat_circuits_engine.constraints_parse import ParsedConstraints from sat_circuits_engine.interface.circuit_decomposition import decompose_operator from sat_circuits_engine.interface.counts_visualization import plot_histogram from sat_circuits_engine.interface.translator import ConstraintsTranslator from sat_circuits_engine.classical_processing import ( find_iterations_unknown, calc_iterations, ClassicalVerifier, ) from sat_circuits_engine.interface.interactive_inputs import ( interactive_operator_inputs, interactive_solutions_num_input, interactive_run_input, interactive_backend_input, interactive_shots_input, ) # Local globlas for visualization of charts and diagrams IFRAME_WIDTH = "100%" IFRAME_HEIGHT = "700" class SATInterface: """ An interface for building, running and mining data from n-SAT problems quantum circuits. There are 2 options to use this class: (1) Using an interactive interface (intuitive but somewhat limited) - for this just initiate a bare instance of this class: `SATInterface()`. (2) Using the API defined by this class, that includes the following methods: * The following descriptions are partial, for full annotations see the methods' docstrings. - `__init__`: an instance of `SATInterface must be initiated with exactly 1 combination: (a) (high_level_constraints_string + high_level_vars) - for constraints in a high-level format. (b) (num_input_qubits + constraints_string) - for constraints in a low-level foramt. * For formats annotations see `constriants_format.ipynb` in the main directory. - `obtain_grover_operator`: obtains the suitable grover operator for the constraints. - `save_display_grover_operator`: saves and displays data generated by the `obtain_grover_operator` method. - `obtain_overall_circuit`: obtains the suitable overall SAT circuit. - `save_display_overall_circuit: saves and displays data generated by the `obtain_overall_circuit` method. - `run_overall_circuit`: executes the overall SAT circuit. - `save_display_results`: saves and displays data generated by the `run_overall_circuit` method. It is very recommended to go through `demos.ipynb` that demonstrates the various optional uses of this class, in addition to reading `constraints_format.ipynb`, which is a must for using this package properly. Both notebooks are in ther main directory. """ def __init__( self, num_input_qubits: Optional[int] = None, constraints_string: Optional[str] = None, high_level_constraints_string: Optional[str] = None, high_level_vars: Optional[Dict[str, int]] = None, name: Optional[str] = None, save_data: Optional[bool] = True, ) -> None: """ Accepts the combination of paramters: (high_level_constraints_string + high_level_vars) or (num_input_qubits + constraints_string). Exactly one combination is accepted. In other cases either an iteractive user interface will be called to take user's inputs, or an exception will be raised due to misuse of the API. Args: num_input_qubits (Optional[int] = None): number of input qubits. constraints_string (Optional[str] = None): a string of constraints in a low-level format. high_level_constraints_string (Optional[str] = None): a string of constraints in a high-level format. high_level_vars (Optional[Dict[str, int]] = None): a dictionary that configures the high-level variables - keys are names and values are bits-lengths. name (Optional[str] = None): a name for this object, if None than the generic name "SAT" is given automatically. save_data (Optional[bool] = True): if True, saves all data and metadata generated by this class to a unique data folder (by using the `save_XXX` methods of this class). Raises: SyntaxError - if a forbidden combination of arguments has been provided. """ if name is None: name = "SAT" self.name = name # Creating a directory for data to be saved if save_data: self.time_created = timestamp(datetime.now()) self.dir_path = f"{DATA_PATH}{self.time_created}_{self.name}/" os.mkdir(self.dir_path) print(f"Data will be saved into '{self.dir_path}'.") # Initial metadata, more to be added by this class' `save_XXX` methods self.metadata = { "name": self.name, "datetime": self.time_created, "num_input_qubits": num_input_qubits, "constraints_string": constraints_string, "high_level_constraints_string": high_level_constraints_string, "high_level_vars": high_level_vars, } self.update_metadata() # Identifying user's platform, for visualization purposes self.identify_platform() # In the case of low-level constraints format, that is the default value self.high_to_low_map = None # Case A - interactive interface if (num_input_qubits is None or constraints_string is None) and ( high_level_constraints_string is None or high_level_vars is None ): self.interactive_interface() # Case B - API else: self.high_level_constraints_string = high_level_constraints_string self.high_level_vars = high_level_vars # Case B.1 - high-level format constraints inputs if num_input_qubits is None or constraints_string is None: self.num_input_qubits = sum(self.high_level_vars.values()) self.high_to_low_map, self.constraints_string = ConstraintsTranslator( self.high_level_constraints_string, self.high_level_vars ).translate() # Case B.2 - low-level format constraints inputs elif num_input_qubits is not None and constraints_string is not None: self.num_input_qubits = num_input_qubits self.constraints_string = constraints_string # Misuse else: raise SyntaxError( "SATInterface accepts the combination of paramters:" "(high_level_constraints_string + high_level_vars) or " "(num_input_qubits + constraints_string). " "Exactly one combination is accepted, not both." ) self.parsed_constraints = ParsedConstraints( self.constraints_string, self.high_level_constraints_string ) def update_metadata(self, update_metadata: Optional[Dict[str, Any]] = None) -> None: """ Updates the metadata file (in the unique data folder of a given `SATInterface` instance). Args: update_metadata (Optional[Dict[str, Any]] = None): - If None - just dumps `self.metadata` into the metadata JSON file. - If defined - updates the `self.metadata` attribute and then dumps it. """ if update_metadata is not None: self.metadata.update(update_metadata) with open(f"{self.dir_path}metadata.json", "w") as metadata_file: json.dump(self.metadata, metadata_file, indent=4) def identify_platform(self) -> None: """ Identifies user's platform. Writes True to `self.jupyter` for Jupyter notebook, False for terminal. """ # If True then the platform is a terminal/command line/shell if stdout.isatty(): self.jupyter = False # If False, we assume the platform is a Jupyter notebook else: self.jupyter = True def output_to_platform( self, *, title: str, output_terminal: Union[TextDrawing, str], output_jupyter: Union[Figure, str], display_both_on_jupyter: Optional[bool] = False, ) -> None: """ Displays output to user's platform. Args: title (str): a title for the output. output_terminal (Union[TextDrawing, str]): text to print for a terminal platform. output_jupyter: (Union[Figure, str]): objects to display for a Jupyter notebook platform. can handle `Figure` matplotlib objects or strings of paths to IFrame displayable file, e.g PDF files. display_both_on_jupyter (Optional[bool] = False): if True, displays both `output_terminal` and `output_jupyter` in a Jupyter notebook platform. Raises: TypeError - in the case of misusing the `output_jupyter` argument. """ print() print(title) if self.jupyter: if isinstance(output_jupyter, str): display.display(display.IFrame(output_jupyter, width=IFRAME_WIDTH, height=IFRAME_HEIGHT)) elif isinstance(output_jupyter, Figure): display.display(output_jupyter) else: raise TypeError("output_jupyter must be an str (path to image file) or a Figure object.") if display_both_on_jupyter: print(output_terminal) else: print(output_terminal) def interactive_interface(self) -> None: """ An interactive CLI that allows exploiting most (but not all) of the package's features. Uses functions of the form `interactive_XXX_inputs` from the `interactive_inputs.py` module. Divided into 3 main stages: 1. Obtaining Grover's operator for the SAT problem. 2. Obtaining the overall SAT cirucit. 3. Executing the circuit and parsing the results. The interface is built in a modular manner such that a user can halt at any stage. The defualt settings for the interactive user intreface are: 1. `name = "SAT"`. 2. `save_data = True`. 3. `display = True`. 4. `transpile_kwargs = {'basis_gates': ['u', 'cx'], 'optimization_level': 3}`. 5. Backends are limited to those defined in the global-constant-like function `BACKENDS`: - Those are the local `aer_simulator` and the remote `ibmq_qasm_simulator` for now. Due to these default settings the interactive CLI is somewhat restrictive, for full flexibility a user should use the API and not the CLI. """ # Handling operator part operator_inputs = interactive_operator_inputs() self.num_input_qubits = operator_inputs["num_input_qubits"] self.high_to_low_map = operator_inputs["high_to_low_map"] self.constraints_string = operator_inputs["constraints_string"] self.high_level_constraints_string = operator_inputs["high_level_constraints_string"] self.high_level_vars = operator_inputs["high_level_vars"] self.parsed_constraints = ParsedConstraints( self.constraints_string, self.high_level_constraints_string ) self.update_metadata( { "num_input_qubits": self.num_input_qubits, "constraints_string": self.constraints_string, "high_level_constraints_string": self.high_level_constraints_string, "high_level_vars": self.high_level_vars, } ) obtain_grover_operator_output = self.obtain_grover_operator() self.save_display_grover_operator(obtain_grover_operator_output) # Handling overall circuit part solutions_num = interactive_solutions_num_input() if solutions_num is not None: backend = None if solutions_num == -1: backend = interactive_backend_input() overall_circuit_data = self.obtain_overall_sat_circuit( obtain_grover_operator_output["operator"], solutions_num, backend ) self.save_display_overall_circuit(overall_circuit_data) # Handling circuit execution part if interactive_run_input(): if backend is None: backend = interactive_backend_input() shots = interactive_shots_input() counts_parsed = self.run_overall_sat_circuit( overall_circuit_data["circuit"], backend, shots ) self.save_display_results(counts_parsed) print() print(f"Done saving data into '{self.dir_path}'.") def obtain_grover_operator( self, transpile_kwargs: Optional[Dict[str, Any]] = None ) -> Dict[str, Union[GroverConstraintsOperator, QuantumCircuit]]: """ Obtains the suitable `GroverConstraintsOperator` object for the constraints, decomposes it using the `circuit_decomposition.py` module and transpiles it according to `transpile_kwargs`. Args: transpile_kwargs (Optional[Dict[str, Any]]): kwargs for Qiskit's transpile function. The defualt is set to the global constant `TRANSPILE_KWARGS`. Returns: (Dict[str, Union[GroverConstraintsOperator, QuantumCircuit, Dict[str, List[int]]]]): - 'operator' (GroverConstraintsOperator):the high-level blocks operator. - 'decomposed_operator' (QuantumCircuit): decomposed to building-blocks operator. * For annotations regarding the decomposition method see the `circuit_decomposition` module. - 'transpiled_operator' (QuantumCircuit): the transpiled operator. *** The high-level operator and the decomposed operator are generated with barriers between constraints as default for visualizations purposes. The barriers are stripped off before transpiling so the the transpiled operator object contains no barriers. *** - 'high_level_to_bit_indexes_map' (Optional[Dict[str, List[int]]] = None): A map of high-level variables with their allocated bit-indexes in the input register. """ print() print( "The system synthesizes and transpiles a Grover's " "operator for the given constraints. Please wait.." ) if transpile_kwargs is None: transpile_kwargs = TRANSPILE_KWARGS self.transpile_kwargs = transpile_kwargs operator = GroverConstraintsOperator( self.parsed_constraints, self.num_input_qubits, insert_barriers=True ) decomposed_operator = decompose_operator(operator) no_baerriers_operator = RemoveBarriers()(operator) transpiled_operator = transpile(no_baerriers_operator, **transpile_kwargs) print("Done.") return { "operator": operator, "decomposed_operator": decomposed_operator, "transpiled_operator": transpiled_operator, "high_level_to_bit_indexes_map": self.high_to_low_map, } def save_display_grover_operator( self, obtain_grover_operator_output: Dict[str, Union[GroverConstraintsOperator, QuantumCircuit]], display: Optional[bool] = True, ) -> None: """ Handles saving and displaying data generated by the `self.obtain_grover_operator` method. Args: obtain_grover_operator_output(Dict[str, Union[GroverConstraintsOperator, QuantumCircuit]]): the dictionary returned upon calling the `self.obtain_grover_operator` method. display (Optional[bool] = True) - If true, displays objects to user's platform. """ # Creating a directory to save operator's data operator_dir_path = f"{self.dir_path}grover_operator/" os.mkdir(operator_dir_path) # Titles for displaying objects, by order of `obtain_grover_operator_output` titles = [ "The operator diagram - high level blocks:", "The operator diagram - decomposed:", f"The transpiled operator diagram saved into '{operator_dir_path}'.\n" f"It's not presented here due to its complexity.\n" f"Please note that barriers appear in the high-level diagrams above only for convenient\n" f"visual separation between constraints.\n" f"Before transpilation all barriers are removed to avoid redundant inefficiencies.", ] for index, (op_name, op_obj) in enumerate(obtain_grover_operator_output.items()): # Generic path and name for files to be saved files_path = f"{operator_dir_path}{op_name}" # Generating a circuit diagrams figure figure_path = f"{files_path}.pdf" op_obj.draw("mpl", filename=figure_path, fold=-1) # Generating a QPY serialization file for the circuit object qpy_file_path = f"{files_path}.qpy" with open(qpy_file_path, "wb") as qpy_file: qpy.dump(op_obj, qpy_file) # Original high-level operator and decomposed operator if index < 2 and display: # Displaying to user self.output_to_platform( title=titles[index], output_terminal=op_obj.draw("text"), output_jupyter=figure_path ) # Transpiled operator elif index == 2: # Output to user, not including the circuit diagram print() print(titles[index]) print() print(f"The transpilation kwargs are: {self.transpile_kwargs}.") transpiled_operator_depth = op_obj.depth() transpiled_operator_gates_count = op_obj.count_ops() print(f"Transpiled operator depth: {transpiled_operator_depth}.") print(f"Transpiled operator gates count: {transpiled_operator_gates_count}.") print(f"Total number of qubits: {op_obj.num_qubits}.") # Generating QASM 2.0 file only for the (flattened = no registers) tranpsiled operator qasm_file_path = f"{files_path}.qasm" flatten_circuit(op_obj).qasm(filename=qasm_file_path) # Index 3 is 'high_level_to_bit_indexes_map' so it's time to break from the loop break # Mapping from high-level variables to bit-indexes will be displayed as well mapping = obtain_grover_operator_output["high_level_to_bit_indexes_map"] if mapping: print() print(f"The high-level variables mapping to bit-indexes:\n{mapping}") print() print( f"Saved into '{operator_dir_path}':\n", " Circuit diagrams for all levels.\n", " QPY serialization exports for all levels.\n", " QASM 2.0 export only for the transpiled level.", ) with open(f"{operator_dir_path}operator.qpy", "rb") as qpy_file: operator_qpy_sha256 = sha256(qpy_file.read()).hexdigest() self.update_metadata( { "high_level_to_bit_indexes_map": self.high_to_low_map, "transpile_kwargs": self.transpile_kwargs, "transpiled_operator_depth": transpiled_operator_depth, "transpiled_operator_gates_count": transpiled_operator_gates_count, "operator_qpy_sha256": operator_qpy_sha256, } ) def obtain_overall_sat_circuit( self, grover_operator: GroverConstraintsOperator, solutions_num: int, backend: Optional[Backend] = None, ) -> Dict[str, SATCircuit]: """ Obtains the suitable `SATCircuit` object (= the overall SAT circuit) for the SAT problem. Args: grover_operator (GroverConstraintsOperator): Grover's operator for the SAT problem. solutions_num (int): number of solutions for the SAT problem. In the case the number of solutions is unknown, specific negative values are accepted: * '-1' - for launching a classical iterative stochastic process that finds an adequate number of iterations - by calling the `find_iterations_unknown` function (see its docstrings for more information). * '-2' - for generating a dynamic circuit that iterates over Grover's iterator until a solution is obtained, using weak measurements. TODO - this feature isn't ready yet. backend (Optional[Backend] = None): in the case of a '-1' value given to `solutions_num`, a backend object to execute the depicted iterative prcess upon should be provided. Returns: (Dict[str, SATCircuit]): - 'circuit' key for the overall SAT circuit. - 'concise_circuit' key for the overall SAT circuit, with only 1 iteration over Grover's iterator (operator + diffuser). Useful for visualization purposes. *** The concise circuit is generated with barriers between segments as default for visualizations purposes. In the actual circuit there no barriers. *** """ # -1 = Unknown number of solutions - iterative stochastic process print() if solutions_num == -1: assert backend is not None, "Need to specify a backend if `solutions_num == -1`." print("Please wait while the system checks various solutions..") circuit, iterations = find_iterations_unknown( self.num_input_qubits, grover_operator, self.parsed_constraints, precision=10, backend=backend, ) print() print(f"An adequate number of iterations found = {iterations}.") # -2 = Unknown number of solutions - implement a dynamic circuit # TODO this feature isn't fully implemented yet elif solutions_num == -2: print("The system builds a dynamic circuit..") circuit = SATCircuit(self.num_input_qubits, grover_operator, iterations=None) circuit.add_input_reg_measurement() iterations = None # Known number of solutions else: print("The system builds the overall circuit..") iterations = calc_iterations(self.num_input_qubits, solutions_num) print(f"\nFor {solutions_num} solutions, {iterations} iterations needed.") circuit = SATCircuit( self.num_input_qubits, grover_operator, iterations, insert_barriers=False ) circuit.add_input_reg_measurement() self.iterations = iterations # Obtaining a SATCircuit object with one iteration for concise representation concise_circuit = SATCircuit( self.num_input_qubits, grover_operator, iterations=1, insert_barriers=True ) concise_circuit.add_input_reg_measurement() return {"circuit": circuit, "concise_circuit": concise_circuit} def save_display_overall_circuit( self, obtain_overall_sat_circuit_output: Dict[str, SATCircuit], display: Optional[bool] = True ) -> None: """ Handles saving and displaying data generated by the `self.obtain_overall_sat_circuit` method. Args: obtain_overall_sat_circuit_output(Dict[str, SATCircuit]): the dictionary returned upon calling the `self.obtain_overall_sat_circuit` method. display (Optional[bool] = True) - If true, displays objects to user's platform. """ circuit = obtain_overall_sat_circuit_output["circuit"] concise_circuit = obtain_overall_sat_circuit_output["concise_circuit"] # Creating a directory to save overall circuit's data overall_circuit_dir_path = f"{self.dir_path}overall_circuit/" os.mkdir(overall_circuit_dir_path) # Generating a figure of the overall SAT circuit with just 1 iteration (i.e "concise") concise_circuit_fig_path = f"{overall_circuit_dir_path}overall_circuit_1_iteration.pdf" concise_circuit.draw("mpl", filename=concise_circuit_fig_path, fold=-1) # Displaying the concise circuit to user if display: if self.iterations: self.output_to_platform( title=( f"The high level circuit contains {self.iterations}" f" iterations of the following form:" ), output_terminal=concise_circuit.draw("text"), output_jupyter=concise_circuit_fig_path, ) # Dynamic circuit case - TODO NOT FULLY IMPLEMENTED YET else: dynamic_circuit_fig_path = f"{overall_circuit_dir_path}overall_circuit_dynamic.pdf" circuit.draw("mpl", filename=dynamic_circuit_fig_path, fold=-1) self.output_to_platform( title="The dynamic circuit diagram:", output_terminal=circuit.draw("text"), output_jupyter=dynamic_circuit_fig_path, ) if self.iterations: transpiled_overall_circuit = transpile(flatten_circuit(circuit), **self.transpile_kwargs) print() print(f"The transpilation kwargs are: {self.transpile_kwargs}.") transpiled_overall_circuit_depth = transpiled_overall_circuit.depth() transpiled_overall_circuit_gates_count = transpiled_overall_circuit.count_ops() print(f"Transpiled overall-circuit depth: {transpiled_overall_circuit_depth}.") print(f"Transpiled overall-circuit gates count: {transpiled_overall_circuit_gates_count}.") print(f"Total number of qubits: {transpiled_overall_circuit.num_qubits}.") print() print("Exporting the full overall SAT circuit object..") export_files_path = f"{overall_circuit_dir_path}overall_circuit" with open(f"{export_files_path}.qpy", "wb") as qpy_file: qpy.dump(circuit, qpy_file) if self.iterations: transpiled_overall_circuit.qasm(filename=f"{export_files_path}.qasm") print() print( f"Saved into '{overall_circuit_dir_path}':\n", " A concised (1 iteration) circuit diagram of the high-level overall SAT circuit.\n", " QPY serialization export for the full overall SAT circuit object.", ) if self.iterations: print(" QASM 2.0 export for the transpiled full overall SAT circuit object.") metadata_update = { "num_total_qubits": circuit.num_qubits, "num_iterations": circuit.iterations, } if self.iterations: metadata_update["transpiled_overall_circuit_depth"] = (transpiled_overall_circuit_depth,) metadata_update[ "transpiled_overall_circuit_gates_count" ] = transpiled_overall_circuit_gates_count self.update_metadata(metadata_update) @timer_dec("Circuit simulation execution time = ") def run_overall_sat_circuit( self, circuit: QuantumCircuit, backend: Backend, shots: int ) -> Dict[str, Union[Counts, List[Tuple[Union[str, int]]], List[str], List[Dict[str, int]]]]: """ Executes a `circuit` on `backend` transpiled w.r.t backend, `shots` times. Args: circuit (QuantumCircuit): `QuantumCircuit` object or child-object (a.k.a `SATCircuit`) to execute. backend (Backend): backend to execute `circuit` upon. shots (int): number of execution shots. Returns: (Dict[str, Union[Counts, List[Tuple[Union[str, int]]], List[str], List[Dict[str, int]]]]): dict object returned by `self.parse_counts` - see this method's docstrings for annotations. """ # Defines also instance attributes to use in other methods self.backend = backend self.shots = shots print() print(f"The system is running the circuit {shots} times on {backend}, please wait..") print("This process might take a while.") job = backend.run(transpile(circuit, backend), shots=shots) counts = job.result().get_counts() print("Done.") parsed_counts = self.parse_counts(counts) return parsed_counts def parse_counts( self, counts: Counts ) -> Dict[str, Union[Counts, List[Tuple[Union[str, int]]], List[str], List[Dict[str, int]]]]: """ Parses a `Counts` object into several desired datas (see 'Returns' section). Args: counts (Counts): the `Counts` object to parse. Returns: (Dict[str, Union[Counts, List[Tuple[Union[str, int]]], List[str], List[Dict[str, int]]]]): 'counts' (Counts) - the original `Counts` object. 'counts_sorted' (List[Tuple[Union[str, int]]]) - results sorted in a descending order. 'distilled_solutions' (List[str]): list of solutions (bitstrings). 'high_level_vars_values' (List[Dict[str, int]]): list of solutions (each solution is a dictionary with variable-names as keys and their integer values as values). """ # Sorting results in an a descending order counts_sorted = sorted(counts.items(), key=lambda x: x[1], reverse=True) # Generating a set of distilled verified-only solutions verifier = ClassicalVerifier(self.parsed_constraints) distilled_solutions = set() for count_item in counts_sorted: if not verifier.verify(count_item[0]): break distilled_solutions.add(count_item[0]) # In the case of high-level format in use, translating `distilled_solutions` into integer values high_level_vars_values = None if self.high_level_constraints_string and self.high_level_vars: # Container for dictionaries with variables integer values high_level_vars_values = [] for solution in distilled_solutions: # Keys are variable-names and values are their integer values solution_vars = {} for var, bits_bundle in self.high_to_low_map.items(): reversed_solution = solution[::-1] var_bitstring = "" for bit_index in bits_bundle: var_bitstring += reversed_solution[bit_index] # Translating to integer value solution_vars[var] = int(var_bitstring, 2) high_level_vars_values.append(solution_vars) return { "counts": counts, "counts_sorted": counts_sorted, "distilled_solutions": distilled_solutions, "high_level_vars_values": high_level_vars_values, } def save_display_results( self, run_overall_sat_circuit_output: Dict[ str, Union[Counts, List[Tuple[Union[str, int]]], List[str], List[Dict[str, int]]] ], display: Optional[bool] = True, ) -> None: """ Handles saving and displaying data generated by the `self.run_overall_sat_circuit` method. Args: run_overall_sat_circuit_output (Dict[str, Union[Counts, List[Tuple[Union[str, int]]], List[str], List[Dict[str, int]]]]): the dictionary returned upon calling the `self.run_overall_sat_circuit` method. display (Optional[bool] = True) - If true, displays objects to user's platform. """ counts = run_overall_sat_circuit_output["counts"] counts_sorted = run_overall_sat_circuit_output["counts_sorted"] distilled_solutions = run_overall_sat_circuit_output["distilled_solutions"] high_level_vars_values = run_overall_sat_circuit_output["high_level_vars_values"] # Creating a directory to save results data results_dir_path = f"{self.dir_path}results/" os.mkdir(results_dir_path) # Defining custom dimensions for the custom `plot_histogram` of this package histogram_fig_width = max((len(counts) * self.num_input_qubits * (10 / 72)), 7) histogram_fig_height = 5 histogram_figsize = (histogram_fig_width, histogram_fig_height) histogram_path = f"{results_dir_path}histogram.pdf" plot_histogram(counts, figsize=histogram_figsize, sort="value_desc", filename=histogram_path) if display: # Basic output text output_text = ( f"All counts:\n{counts_sorted}\n" f"\nDistilled solutions ({len(distilled_solutions)} total):\n" f"{distilled_solutions}" ) # Additional outputs for a high-level constraints format if high_level_vars_values: # Mapping from high-level variables to bit-indexes will be displayed as well output_text += ( f"\n\nThe high-level variables mapping to bit-indexes:" f"\n{self.high_to_low_map}" ) # Actual integer solutions will be displayed as well additional_text = "" for solution_index, solution in enumerate(high_level_vars_values): additional_text += f"Solution {solution_index + 1}: " for var_index, (var, value) in enumerate(solution.items()): additional_text += f"{var} = {value}" if var_index != len(solution) - 1: additional_text += ", " else: additional_text += "\n" output_text += f"\n\nHigh-level format solutions: \n{additional_text}" self.output_to_platform( title=f"The results for {self.shots} shots are:", output_terminal=output_text, output_jupyter=histogram_path, display_both_on_jupyter=True, ) results_dict = { "high_level_to_bit_indexes_map": self.high_to_low_map, "solutions": list(distilled_solutions), "high_level_solutions": high_level_vars_values, "counts": counts_sorted, } with open(f"{results_dir_path}results.json", "w") as results_file: json.dump(results_dict, results_file, indent=4) self.update_metadata( { "num_solutions": len(distilled_solutions), "backend": str(self.backend), "shots": self.shots, } )
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ A collection of functions that decide the layout of an output image. See :py:mod:`~qiskit.visualization.timeline.types` for more info on the required data. There are 2 types of layout functions in this module. 1. layout.bit_arrange In this stylesheet entry the input data is a list of `types.Bits` and returns a sorted list of `types.Bits`. The function signature of the layout is restricted to: ```python def my_layout(bits: List[types.Bits]) -> List[types.Bits]: # your code here: sort input bits and return list of bits ``` 2. layout.time_axis_map In this stylesheet entry the input data is `Tuple[int, int]` that represents horizontal axis limit of the output image. The layout function returns `types.HorizontalAxis` data which is consumed by the plotter API to make horizontal axis. The function signature of the layout is restricted to: ```python def my_layout(time_window: Tuple[int, int]) -> types.HorizontalAxis: # your code here: create and return axis config ``` Arbitrary layout function satisfying the above format can be accepted. """ import warnings from typing import List, Tuple import numpy as np from qiskit import circuit from qiskit.visualization.exceptions import VisualizationError from qiskit.visualization.timeline import types def qreg_creg_ascending(bits: List[types.Bits]) -> List[types.Bits]: """Sort bits by ascending order. Bit order becomes Q0, Q1, ..., Cl0, Cl1, ... Args: bits: List of bits to sort. Returns: Sorted bits. """ qregs = [] cregs = [] for bit in bits: if isinstance(bit, circuit.Qubit): qregs.append(bit) elif isinstance(bit, circuit.Clbit): cregs.append(bit) else: raise VisualizationError(f"Unknown bit {bit} is provided.") with warnings.catch_warnings(): warnings.simplefilter("ignore") qregs = sorted(qregs, key=lambda x: x.index, reverse=False) cregs = sorted(cregs, key=lambda x: x.index, reverse=False) return qregs + cregs def qreg_creg_descending(bits: List[types.Bits]) -> List[types.Bits]: """Sort bits by descending order. Bit order becomes Q_N, Q_N-1, ..., Cl_N, Cl_N-1, ... Args: bits: List of bits to sort. Returns: Sorted bits. """ qregs = [] cregs = [] for bit in bits: if isinstance(bit, circuit.Qubit): qregs.append(bit) elif isinstance(bit, circuit.Clbit): cregs.append(bit) else: raise VisualizationError(f"Unknown bit {bit} is provided.") qregs = sorted(qregs, key=lambda x: x.index, reverse=True) cregs = sorted(cregs, key=lambda x: x.index, reverse=True) return qregs + cregs def time_map_in_dt(time_window: Tuple[int, int]) -> types.HorizontalAxis: """Layout function for the horizontal axis formatting. Generate equispaced 6 horizontal axis ticks. Args: time_window: Left and right edge of this graph. Returns: Axis formatter object. """ # shift time axis t0, t1 = time_window # axis label axis_loc = np.linspace(max(t0, 0), t1, 6) axis_label = axis_loc.copy() # consider time resolution label = "System cycle time (dt)" formatted_label = [f"{val:.0f}" for val in axis_label] return types.HorizontalAxis( window=(t0, t1), axis_map=dict(zip(axis_loc, formatted_label)), label=label )
https://github.com/swe-train/qiskit__qiskit
swe-train
# 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. """ Special data types. """ from enum import Enum from typing import NamedTuple, List, Union, NewType, Tuple, Dict from qiskit import circuit ScheduledGate = NamedTuple( "ScheduledGate", [ ("t0", int), ("operand", circuit.Gate), ("duration", int), ("bits", List[Union[circuit.Qubit, circuit.Clbit]]), ("bit_position", int), ], ) ScheduledGate.__doc__ = "A gate instruction with embedded time." ScheduledGate.t0.__doc__ = "Time when the instruction is issued." ScheduledGate.operand.__doc__ = "Gate object associated with the gate." ScheduledGate.duration.__doc__ = "Time duration of the instruction." ScheduledGate.bits.__doc__ = "List of bit associated with the gate." ScheduledGate.bit_position.__doc__ = "Position of bit associated with this drawing source." GateLink = NamedTuple( "GateLink", [("t0", int), ("opname", str), ("bits", List[Union[circuit.Qubit, circuit.Clbit]])] ) GateLink.__doc__ = "Dedicated object to represent a relationship between instructions." GateLink.t0.__doc__ = "A position where the link is placed." GateLink.opname.__doc__ = "Name of gate associated with this link." GateLink.bits.__doc__ = "List of bit associated with the instruction." Barrier = NamedTuple( "Barrier", [("t0", int), ("bits", List[Union[circuit.Qubit, circuit.Clbit]]), ("bit_position", int)], ) Barrier.__doc__ = "Dedicated object to represent a barrier instruction." Barrier.t0.__doc__ = "A position where the barrier is placed." Barrier.bits.__doc__ = "List of bit associated with the instruction." Barrier.bit_position.__doc__ = "Position of bit associated with this drawing source." HorizontalAxis = NamedTuple( "HorizontalAxis", [("window", Tuple[int, int]), ("axis_map", Dict[int, int]), ("label", str)] ) HorizontalAxis.__doc__ = "Data to represent configuration of horizontal axis." HorizontalAxis.window.__doc__ = "Left and right edge of graph." HorizontalAxis.axis_map.__doc__ = "Mapping of apparent coordinate system and actual location." HorizontalAxis.label.__doc__ = "Label of horizontal axis." class BoxType(str, Enum): """Box type. SCHED_GATE: Box that represents occupation time by gate. DELAY: Box associated with delay. TIMELINE: Box that represents time slot of a bit. """ SCHED_GATE = "Box.ScheduledGate" DELAY = "Box.Delay" TIMELINE = "Box.Timeline" class LineType(str, Enum): """Line type. BARRIER: Line that represents barrier instruction. GATE_LINK: Line that represents a link among gates. """ BARRIER = "Line.Barrier" GATE_LINK = "Line.GateLink" class SymbolType(str, Enum): """Symbol type. FRAME: Symbol that represents zero time frame change (Rz) instruction. """ FRAME = "Symbol.Frame" class LabelType(str, Enum): """Label type. GATE_NAME: Label that represents name of gate. DELAY: Label associated with delay. GATE_PARAM: Label that represents parameter of gate. BIT_NAME: Label that represents name of bit. """ GATE_NAME = "Label.Gate.Name" DELAY = "Label.Delay" GATE_PARAM = "Label.Gate.Param" BIT_NAME = "Label.Bit.Name" class AbstractCoordinate(Enum): """Abstract coordinate that the exact value depends on the user preference. RIGHT: The horizontal coordinate at t0 shifted by the left margin. LEFT: The horizontal coordinate at tf shifted by the right margin. TOP: The vertical coordinate at the top of the canvas. BOTTOM: The vertical coordinate at the bottom of the canvas. """ RIGHT = "RIGHT" LEFT = "LEFT" TOP = "TOP" BOTTOM = "BOTTOM" class Plotter(str, Enum): """Name of timeline plotter APIs. MPL: Matplotlib plotter interface. Show timeline in 2D canvas. """ MPL = "mpl" # convenient type to represent union of drawing data DataTypes = NewType("DataType", Union[BoxType, LabelType, LineType, SymbolType]) # convenient type to represent union of values to represent a coordinate Coordinate = NewType("Coordinate", Union[float, AbstractCoordinate]) # Valid bit objects Bits = NewType("Bits", Union[circuit.Qubit, circuit.Clbit])
https://github.com/swe-train/qiskit__qiskit
swe-train
# 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 """Waveform generators. A collection of functions that generate drawings from formatted input data. See py:mod:`qiskit.visualization.pulse_v2.types` for more info on the required data. In this module the input data is `types.PulseInstruction`. An end-user can write arbitrary functions that generate custom drawings. Generators in this module are called with the `formatter` and `device` kwargs. These data provides stylesheet configuration and backend system configuration. The format of generator is restricted to: ```python def my_object_generator(data: PulseInstruction, formatter: Dict[str, Any], device: DrawerBackendInfo) -> List[ElementaryData]: pass ``` Arbitrary generator function satisfying the above format can be accepted. Returned `ElementaryData` can be arbitrary subclasses that are implemented in the plotter API. """ from __future__ import annotations import re from fractions import Fraction from typing import Any import numpy as np from qiskit import pulse, circuit from qiskit.pulse import instructions, library from qiskit.visualization.exceptions import VisualizationError from qiskit.visualization.pulse_v2 import drawings, types, device_info def gen_filled_waveform_stepwise( data: types.PulseInstruction, formatter: dict[str, Any], device: device_info.DrawerBackendInfo ) -> list[drawings.LineData | drawings.BoxData | drawings.TextData]: """Generate filled area objects of the real and the imaginary part of waveform envelope. The curve of envelope is not interpolated nor smoothed and presented as stepwise function at each data point. Stylesheets: - The `fill_waveform` style is applied. Args: data: Waveform instruction data to draw. formatter: Dictionary of stylesheet settings. device: Backend configuration. Returns: List of `LineData`, `BoxData`, or `TextData` drawings. Raises: VisualizationError: When the instruction parser returns invalid data format. """ # generate waveform data waveform_data = _parse_waveform(data) channel = data.inst.channel # update metadata meta = waveform_data.meta qind = device.get_qubit_index(channel) meta.update({"qubit": qind if qind is not None else "N/A"}) if isinstance(waveform_data, types.ParsedInstruction): # Draw waveform with fixed shape xdata = waveform_data.xvals ydata = waveform_data.yvals # phase modulation if formatter["control.apply_phase_modulation"]: ydata = np.asarray(ydata, dtype=complex) * np.exp(1j * data.frame.phase) else: ydata = np.asarray(ydata, dtype=complex) return _draw_shaped_waveform( xdata=xdata, ydata=ydata, meta=meta, channel=channel, formatter=formatter ) elif isinstance(waveform_data, types.OpaqueShape): # Draw parametric pulse with unbound parameters # parameter name unbound_params = [] for pname, pval in data.inst.pulse.parameters.items(): if isinstance(pval, circuit.ParameterExpression): unbound_params.append(pname) pulse_data = data.inst.pulse if isinstance(pulse_data, library.SymbolicPulse): pulse_shape = pulse_data.pulse_type else: pulse_shape = "Waveform" return _draw_opaque_waveform( init_time=data.t0, duration=waveform_data.duration, pulse_shape=pulse_shape, pnames=unbound_params, meta=meta, channel=channel, formatter=formatter, ) else: raise VisualizationError("Invalid data format is provided.") def gen_ibmq_latex_waveform_name( data: types.PulseInstruction, formatter: dict[str, Any], device: device_info.DrawerBackendInfo ) -> list[drawings.TextData]: r"""Generate the formatted instruction name associated with the waveform. Channel name and ID string are removed and the rotation angle is expressed in units of pi. The controlled rotation angle associated with the CR pulse name is divided by 2. Note that in many scientific articles the controlled rotation angle implies the actual rotation angle, but in IQX backend the rotation angle represents the difference between rotation angles with different control qubit states. For example: - 'X90p_d0_abcdefg' is converted into 'X(\frac{\pi}{2})' - 'CR90p_u0_abcdefg` is converted into 'CR(\frac{\pi}{4})' Stylesheets: - The `annotate` style is applied. Notes: This generator can convert pulse names used in the IQX backends. If pulses are provided by the third party providers or the user defined, the generator output may be the as-is pulse name. Args: data: Waveform instruction data to draw. formatter: Dictionary of stylesheet settings. device: Backend configuration. Returns: List of `TextData` drawings. """ if data.is_opaque: return [] style = { "zorder": formatter["layer.annotate"], "color": formatter["color.annotate"], "size": formatter["text_size.annotate"], "va": "center", "ha": "center", } if isinstance(data.inst, pulse.instructions.Acquire): systematic_name = "Acquire" latex_name = None elif isinstance(data.inst, instructions.Delay): systematic_name = data.inst.name or "Delay" latex_name = None else: pulse_data = data.inst.pulse if pulse_data.name: systematic_name = pulse_data.name else: if isinstance(pulse_data, library.SymbolicPulse): systematic_name = pulse_data.pulse_type else: systematic_name = "Waveform" template = r"(?P<op>[A-Z]+)(?P<angle>[0-9]+)?(?P<sign>[pm])_(?P<ch>[dum])[0-9]+" match_result = re.match(template, systematic_name) if match_result is not None: match_dict = match_result.groupdict() sign = "" if match_dict["sign"] == "p" else "-" if match_dict["op"] == "CR": # cross resonance if match_dict["ch"] == "u": op_name = r"{\rm CR}" else: op_name = r"\overline{\rm CR}" # IQX name def is not standard. Echo CR is annotated with pi/4 rather than pi/2 angle_val = match_dict["angle"] frac = Fraction(int(int(angle_val) / 2), 180) if frac.numerator == 1: angle = rf"\pi/{frac.denominator:d}" else: angle = r"{num:d}/{denom:d} \pi".format( num=frac.numerator, denom=frac.denominator ) else: # single qubit pulse op_name = r"{{\rm {}}}".format(match_dict["op"]) angle_val = match_dict["angle"] if angle_val is None: angle = r"\pi" else: frac = Fraction(int(angle_val), 180) if frac.numerator == 1: angle = rf"\pi/{frac.denominator:d}" else: angle = r"{num:d}/{denom:d} \pi".format( num=frac.numerator, denom=frac.denominator ) latex_name = rf"{op_name}({sign}{angle})" else: latex_name = None text = drawings.TextData( data_type=types.LabelType.PULSE_NAME, channels=data.inst.channel, xvals=[data.t0 + 0.5 * data.inst.duration], yvals=[-formatter["label_offset.pulse_name"]], text=systematic_name, latex=latex_name, ignore_scaling=True, styles=style, ) return [text] def gen_waveform_max_value( data: types.PulseInstruction, formatter: dict[str, Any], device: device_info.DrawerBackendInfo ) -> list[drawings.TextData]: """Generate the annotation for the maximum waveform height for the real and the imaginary part of the waveform envelope. Maximum values smaller than the vertical resolution limit is ignored. Stylesheets: - The `annotate` style is applied. Args: data: Waveform instruction data to draw. formatter: Dictionary of stylesheet settings. device: Backend configuration. Returns: List of `TextData` drawings. """ if data.is_opaque: return [] style = { "zorder": formatter["layer.annotate"], "color": formatter["color.annotate"], "size": formatter["text_size.annotate"], "ha": "center", } # only pulses. if isinstance(data.inst, instructions.Play): # pulse operand = data.inst.pulse if isinstance(operand, (pulse.ParametricPulse, pulse.SymbolicPulse)): pulse_data = operand.get_waveform() else: pulse_data = operand xdata = np.arange(pulse_data.duration) + data.t0 ydata = pulse_data.samples else: return [] # phase modulation if formatter["control.apply_phase_modulation"]: ydata = np.asarray(ydata, dtype=complex) * np.exp(1j * data.frame.phase) else: ydata = np.asarray(ydata, dtype=complex) texts = [] # max of real part re_maxind = np.argmax(np.abs(ydata.real)) if np.abs(ydata.real[re_maxind]) > 0.01: # generator shows only 2 digits after the decimal point. if ydata.real[re_maxind] > 0: max_val = f"{ydata.real[re_maxind]:.2f}\n\u25BE" re_style = {"va": "bottom"} else: max_val = f"\u25B4\n{ydata.real[re_maxind]:.2f}" re_style = {"va": "top"} re_style.update(style) re_text = drawings.TextData( data_type=types.LabelType.PULSE_INFO, channels=data.inst.channel, xvals=[xdata[re_maxind]], yvals=[ydata.real[re_maxind]], text=max_val, styles=re_style, ) texts.append(re_text) # max of imag part im_maxind = np.argmax(np.abs(ydata.imag)) if np.abs(ydata.imag[im_maxind]) > 0.01: # generator shows only 2 digits after the decimal point. if ydata.imag[im_maxind] > 0: max_val = f"{ydata.imag[im_maxind]:.2f}\n\u25BE" im_style = {"va": "bottom"} else: max_val = f"\u25B4\n{ydata.imag[im_maxind]:.2f}" im_style = {"va": "top"} im_style.update(style) im_text = drawings.TextData( data_type=types.LabelType.PULSE_INFO, channels=data.inst.channel, xvals=[xdata[im_maxind]], yvals=[ydata.imag[im_maxind]], text=max_val, styles=im_style, ) texts.append(im_text) return texts def _draw_shaped_waveform( xdata: np.ndarray, ydata: np.ndarray, meta: dict[str, Any], channel: pulse.channels.PulseChannel, formatter: dict[str, Any], ) -> list[drawings.LineData | drawings.BoxData | drawings.TextData]: """A private function that generates drawings of stepwise pulse lines. Args: xdata: Array of horizontal coordinate of waveform envelope. ydata: Array of vertical coordinate of waveform envelope. meta: Metadata dictionary of the waveform. channel: Channel associated with the waveform to draw. formatter: Dictionary of stylesheet settings. Returns: List of drawings. Raises: VisualizationError: When the waveform color for channel is not defined. """ fill_objs: list[drawings.LineData | drawings.BoxData | drawings.TextData] = [] resolution = formatter["general.vertical_resolution"] # stepwise interpolation xdata: np.ndarray = np.concatenate((xdata, [xdata[-1] + 1])) ydata = np.repeat(ydata, 2) re_y = np.real(ydata) im_y = np.imag(ydata) time: np.ndarray = np.concatenate(([xdata[0]], np.repeat(xdata[1:-1], 2), [xdata[-1]])) # setup style options style = { "alpha": formatter["alpha.fill_waveform"], "zorder": formatter["layer.fill_waveform"], "linewidth": formatter["line_width.fill_waveform"], "linestyle": formatter["line_style.fill_waveform"], } try: color_real, color_imag = formatter["color.waveforms"][channel.prefix.upper()] except KeyError as ex: raise VisualizationError( f"Waveform color for channel type {channel.prefix} is not defined" ) from ex # create real part if np.any(re_y): # data compression re_valid_inds = _find_consecutive_index(re_y, resolution) # stylesheet re_style = {"color": color_real} re_style.update(style) # metadata re_meta = {"data": "real"} re_meta.update(meta) # active xy data re_xvals = time[re_valid_inds] re_yvals = re_y[re_valid_inds] # object real = drawings.LineData( data_type=types.WaveformType.REAL, channels=channel, xvals=re_xvals, yvals=re_yvals, fill=formatter["control.fill_waveform"], meta=re_meta, styles=re_style, ) fill_objs.append(real) # create imaginary part if np.any(im_y): # data compression im_valid_inds = _find_consecutive_index(im_y, resolution) # stylesheet im_style = {"color": color_imag} im_style.update(style) # metadata im_meta = {"data": "imag"} im_meta.update(meta) # active xy data im_xvals = time[im_valid_inds] im_yvals = im_y[im_valid_inds] # object imag = drawings.LineData( data_type=types.WaveformType.IMAG, channels=channel, xvals=im_xvals, yvals=im_yvals, fill=formatter["control.fill_waveform"], meta=im_meta, styles=im_style, ) fill_objs.append(imag) return fill_objs def _draw_opaque_waveform( init_time: int, duration: int, pulse_shape: str, pnames: list[str], meta: dict[str, Any], channel: pulse.channels.PulseChannel, formatter: dict[str, Any], ) -> list[drawings.LineData | drawings.BoxData | drawings.TextData]: """A private function that generates drawings of stepwise pulse lines. Args: init_time: Time when the opaque waveform starts. duration: Duration of opaque waveform. This can be None or ParameterExpression. pulse_shape: String that represents pulse shape. pnames: List of parameter names. meta: Metadata dictionary of the waveform. channel: Channel associated with the waveform to draw. formatter: Dictionary of stylesheet settings. Returns: List of drawings. """ fill_objs: list[drawings.LineData | drawings.BoxData | drawings.TextData] = [] fc, ec = formatter["color.opaque_shape"] # setup style options box_style = { "zorder": formatter["layer.fill_waveform"], "alpha": formatter["alpha.opaque_shape"], "linewidth": formatter["line_width.opaque_shape"], "linestyle": formatter["line_style.opaque_shape"], "facecolor": fc, "edgecolor": ec, } if duration is None or isinstance(duration, circuit.ParameterExpression): duration = formatter["box_width.opaque_shape"] box_obj = drawings.BoxData( data_type=types.WaveformType.OPAQUE, channels=channel, xvals=[init_time, init_time + duration], yvals=[ -0.5 * formatter["box_height.opaque_shape"], 0.5 * formatter["box_height.opaque_shape"], ], meta=meta, ignore_scaling=True, styles=box_style, ) fill_objs.append(box_obj) # parameter name func_repr = "{func}({params})".format(func=pulse_shape, params=", ".join(pnames)) text_style = { "zorder": formatter["layer.annotate"], "color": formatter["color.annotate"], "size": formatter["text_size.annotate"], "va": "bottom", "ha": "center", } text_obj = drawings.TextData( data_type=types.LabelType.OPAQUE_BOXTEXT, channels=channel, xvals=[init_time + 0.5 * duration], yvals=[0.5 * formatter["box_height.opaque_shape"]], text=func_repr, ignore_scaling=True, styles=text_style, ) fill_objs.append(text_obj) return fill_objs def _find_consecutive_index(data_array: np.ndarray, resolution: float) -> np.ndarray: """A helper function to return non-consecutive index from the given list. This drastically reduces memory footprint to represent a drawing, especially for samples of very long flat-topped Gaussian pulses. Tiny value fluctuation smaller than `resolution` threshold is removed. Args: data_array: The array of numbers. resolution: Minimum resolution of sample values. Returns: The compressed data array. """ try: vector = np.asarray(data_array, dtype=float) diff = np.diff(vector) diff[np.where(np.abs(diff) < resolution)] = 0 # keep left and right edges consecutive_l = np.insert(diff.astype(bool), 0, True) consecutive_r = np.append(diff.astype(bool), True) return consecutive_l | consecutive_r except ValueError: return np.ones_like(data_array).astype(bool) def _parse_waveform( data: types.PulseInstruction, ) -> types.ParsedInstruction | types.OpaqueShape: """A helper function that generates an array for the waveform with instruction metadata. Args: data: Instruction data set Raises: VisualizationError: When invalid instruction type is loaded. Returns: A data source to generate a drawing. """ inst = data.inst meta: dict[str, Any] = {} if isinstance(inst, instructions.Play): # pulse operand = inst.pulse if isinstance(operand, (pulse.ParametricPulse, pulse.SymbolicPulse)): # parametric pulse params = operand.parameters duration = params.pop("duration", None) if isinstance(duration, circuit.Parameter): duration = None if isinstance(operand, library.SymbolicPulse): pulse_shape = operand.pulse_type else: pulse_shape = "Waveform" meta["waveform shape"] = pulse_shape meta.update( { key: val.name if isinstance(val, circuit.Parameter) else val for key, val in params.items() } ) if data.is_opaque: # parametric pulse with unbound parameter if duration: meta.update( { "duration (cycle time)": inst.duration, "duration (sec)": inst.duration * data.dt if data.dt else "N/A", } ) else: meta.update({"duration (cycle time)": "N/A", "duration (sec)": "N/A"}) meta.update( { "t0 (cycle time)": data.t0, "t0 (sec)": data.t0 * data.dt if data.dt else "N/A", "phase": data.frame.phase, "frequency": data.frame.freq, "name": inst.name, } ) return types.OpaqueShape(duration=duration, meta=meta) else: # fixed shape parametric pulse pulse_data = operand.get_waveform() else: # waveform pulse_data = operand xdata = np.arange(pulse_data.duration) + data.t0 ydata = pulse_data.samples elif isinstance(inst, instructions.Delay): # delay xdata = np.arange(inst.duration) + data.t0 ydata = np.zeros(inst.duration) elif isinstance(inst, instructions.Acquire): # acquire xdata = np.arange(inst.duration) + data.t0 ydata = np.ones(inst.duration) acq_data = { "memory slot": inst.mem_slot.name, "register slot": inst.reg_slot.name if inst.reg_slot else "N/A", "discriminator": inst.discriminator.name if inst.discriminator else "N/A", "kernel": inst.kernel.name if inst.kernel else "N/A", } meta.update(acq_data) else: raise VisualizationError( "Unsupported instruction {inst} by " "filled envelope.".format(inst=inst.__class__.__name__) ) meta.update( { "duration (cycle time)": inst.duration, "duration (sec)": inst.duration * data.dt if data.dt else "N/A", "t0 (cycle time)": data.t0, "t0 (sec)": data.t0 * data.dt if data.dt else "N/A", "phase": data.frame.phase, "frequency": data.frame.freq, "name": inst.name, } ) return types.ParsedInstruction(xvals=xdata, yvals=ydata, meta=meta)
https://github.com/swe-train/qiskit__qiskit
swe-train
# 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. """ Core module of the timeline drawer. This module provides the `DrawerCanvas` which is a collection of drawings. The canvas instance is not just a container of drawing objects, as it also performs data processing like binding abstract coordinates. Initialization ~~~~~~~~~~~~~~ The `DataCanvas` is not exposed to users as they are implicitly initialized in the interface function. It is noteworthy that the data canvas is agnostic to plotters. This means once the canvas instance is initialized we can reuse this data among multiple plotters. The canvas is initialized with a stylesheet. ```python canvas = DrawerCanvas(stylesheet=stylesheet) canvas.load_program(sched) canvas.update() ``` Once all properties are set, `.update` method is called to apply changes to drawings. Update ~~~~~~ To update the image, a user can set new values to canvas and then call the `.update` method. ```python canvas.set_time_range(2000, 3000) canvas.update() ``` All stored drawings are updated accordingly. The plotter API can access to drawings with `.collections` property of the canvas instance. This returns an iterator of drawings with the unique data key. If a plotter provides object handler for plotted shapes, the plotter API can manage the lookup table of the handler and the drawings by using this data key. """ from __future__ import annotations import warnings from collections.abc import Iterator from copy import deepcopy from functools import partial from enum import Enum import numpy as np from qiskit import circuit from qiskit.visualization.exceptions import VisualizationError from qiskit.visualization.timeline import drawings, types from qiskit.visualization.timeline.stylesheet import QiskitTimelineStyle class DrawerCanvas: """Data container for drawings.""" def __init__(self, stylesheet: QiskitTimelineStyle): """Create new data container.""" # stylesheet self.formatter = stylesheet.formatter self.generator = stylesheet.generator self.layout = stylesheet.layout # drawings self._collections: dict[str, drawings.ElementaryData] = {} self._output_dataset: dict[str, drawings.ElementaryData] = {} # vertical offset of bits self.bits: list[types.Bits] = [] self.assigned_coordinates: dict[types.Bits, float] = {} # visible controls self.disable_bits: set[types.Bits] = set() self.disable_types: set[str] = set() # time self._time_range = (0, 0) # graph height self.vmax = 0 self.vmin = 0 @property def time_range(self) -> tuple[int, int]: """Return current time range to draw. Calculate net duration and add side margin to edge location. Returns: Time window considering side margin. """ t0, t1 = self._time_range duration = t1 - t0 new_t0 = t0 - duration * self.formatter["margin.left_percent"] new_t1 = t1 + duration * self.formatter["margin.right_percent"] return new_t0, new_t1 @time_range.setter def time_range(self, new_range: tuple[int, int]): """Update time range to draw.""" self._time_range = new_range @property def collections(self) -> Iterator[tuple[str, drawings.ElementaryData]]: """Return currently active entries from drawing data collection. The object is returned with unique name as a key of an object handler. When the horizontal coordinate contains `AbstractCoordinate`, the value is substituted by current time range preference. """ yield from self._output_dataset.items() def add_data(self, data: drawings.ElementaryData): """Add drawing to collections. If the given object already exists in the collections, this interface replaces the old object instead of adding new entry. Args: data: New drawing to add. """ if not self.formatter["control.show_clbits"]: data.bits = [b for b in data.bits if not isinstance(b, circuit.Clbit)] self._collections[data.data_key] = data # pylint: disable=cyclic-import def load_program(self, program: circuit.QuantumCircuit): """Load quantum circuit and create drawing.. Args: program: Scheduled circuit object to draw. Raises: VisualizationError: When circuit is not scheduled. """ not_gate_like = (circuit.Barrier,) if getattr(program, "_op_start_times") is None: # Run scheduling for backward compatibility from qiskit import transpile from qiskit.transpiler import InstructionDurations, TranspilerError warnings.warn( "Visualizing un-scheduled circuit with timeline drawer has been deprecated. " "This circuit should be transpiled with scheduler though it consists of " "instructions with explicit durations.", DeprecationWarning, ) try: program = transpile( program, scheduling_method="alap", instruction_durations=InstructionDurations(), optimization_level=0, ) except TranspilerError as ex: raise VisualizationError( f"Input circuit {program.name} is not scheduled and it contains " "operations with unknown delays. This cannot be visualized." ) from ex for t0, instruction in zip(program.op_start_times, program.data): bits = list(instruction.qubits) + list(instruction.clbits) for bit_pos, bit in enumerate(bits): if not isinstance(instruction.operation, not_gate_like): # Generate draw object for gates gate_source = types.ScheduledGate( t0=t0, operand=instruction.operation, duration=instruction.operation.duration, bits=bits, bit_position=bit_pos, ) for gen in self.generator["gates"]: obj_generator = partial(gen, formatter=self.formatter) for datum in obj_generator(gate_source): self.add_data(datum) if len(bits) > 1 and bit_pos == 0: # Generate draw object for gate-gate link line_pos = t0 + 0.5 * instruction.operation.duration link_source = types.GateLink( t0=line_pos, opname=instruction.operation.name, bits=bits ) for gen in self.generator["gate_links"]: obj_generator = partial(gen, formatter=self.formatter) for datum in obj_generator(link_source): self.add_data(datum) if isinstance(instruction.operation, circuit.Barrier): # Generate draw object for barrier barrier_source = types.Barrier(t0=t0, bits=bits, bit_position=bit_pos) for gen in self.generator["barriers"]: obj_generator = partial(gen, formatter=self.formatter) for datum in obj_generator(barrier_source): self.add_data(datum) self.bits = list(program.qubits) + list(program.clbits) for bit in self.bits: for gen in self.generator["bits"]: # Generate draw objects for bit obj_generator = partial(gen, formatter=self.formatter) for datum in obj_generator(bit): self.add_data(datum) # update time range t_end = max(program.duration, self.formatter["margin.minimum_duration"]) self.set_time_range(t_start=0, t_end=t_end) def set_time_range(self, t_start: int, t_end: int): """Set time range to draw. Args: t_start: Left boundary of drawing in units of cycle time. t_end: Right boundary of drawing in units of cycle time. """ self.time_range = (t_start, t_end) def set_disable_bits(self, bit: types.Bits, remove: bool = True): """Interface method to control visibility of bits. Specified object in the blocked list will not be shown. Args: bit: A qubit or classical bit object to disable. remove: Set `True` to disable, set `False` to enable. """ if remove: self.disable_bits.add(bit) else: self.disable_bits.discard(bit) def set_disable_type(self, data_type: types.DataTypes, remove: bool = True): """Interface method to control visibility of data types. Specified object in the blocked list will not be shown. Args: data_type: A drawing data type to disable. remove: Set `True` to disable, set `False` to enable. """ if isinstance(data_type, Enum): data_type_str = str(data_type.value) else: data_type_str = data_type if remove: self.disable_types.add(data_type_str) else: self.disable_types.discard(data_type_str) def update(self): """Update all collections. This method should be called before the canvas is passed to the plotter. """ self._output_dataset.clear() self.assigned_coordinates.clear() # update coordinate y0 = -self.formatter["margin.top"] for bit in self.layout["bit_arrange"](self.bits): # remove classical bit if isinstance(bit, circuit.Clbit) and not self.formatter["control.show_clbits"]: continue # remove idle bit if not self._check_bit_visible(bit): continue offset = y0 - 0.5 self.assigned_coordinates[bit] = offset y0 = offset - 0.5 self.vmax = 0 self.vmin = y0 - self.formatter["margin.bottom"] # add data temp_gate_links = {} temp_data = {} for data_key, data in self._collections.items(): # deep copy to keep original data hash new_data = deepcopy(data) new_data.xvals = self._bind_coordinate(data.xvals) new_data.yvals = self._bind_coordinate(data.yvals) if data.data_type == str(types.LineType.GATE_LINK.value): temp_gate_links[data_key] = new_data else: temp_data[data_key] = new_data # update horizontal offset of gate links temp_data.update(self._check_link_overlap(temp_gate_links)) # push valid data for data_key, data in temp_data.items(): if self._check_data_visible(data): self._output_dataset[data_key] = data def _check_data_visible(self, data: drawings.ElementaryData) -> bool: """A helper function to check if the data is visible. Args: data: Drawing object to test. Returns: Return `True` if the data is visible. """ _barriers = [str(types.LineType.BARRIER.value)] _delays = [str(types.BoxType.DELAY.value), str(types.LabelType.DELAY.value)] def _time_range_check(_data): """If data is located outside the current time range.""" t0, t1 = self.time_range if np.max(_data.xvals) < t0 or np.min(_data.xvals) > t1: return False return True def _associated_bit_check(_data): """If any associated bit is not shown.""" if all(bit not in self.assigned_coordinates for bit in _data.bits): return False return True def _data_check(_data): """If data is valid.""" if _data.data_type == str(types.LineType.GATE_LINK.value): active_bits = [bit for bit in _data.bits if bit not in self.disable_bits] if len(active_bits) < 2: return False elif _data.data_type in _barriers and not self.formatter["control.show_barriers"]: return False elif _data.data_type in _delays and not self.formatter["control.show_delays"]: return False return True checks = [_time_range_check, _associated_bit_check, _data_check] if all(check(data) for check in checks): return True return False def _check_bit_visible(self, bit: types.Bits) -> bool: """A helper function to check if the bit is visible. Args: bit: Bit object to test. Returns: Return `True` if the bit is visible. """ _gates = [str(types.BoxType.SCHED_GATE.value), str(types.SymbolType.FRAME.value)] if bit in self.disable_bits: return False if self.formatter["control.show_idle"]: return True for data in self._collections.values(): if bit in data.bits and data.data_type in _gates: return True return False def _bind_coordinate(self, vals: Iterator[types.Coordinate]) -> np.ndarray: """A helper function to bind actual coordinates to an `AbstractCoordinate`. Args: vals: Sequence of coordinate objects associated with a drawing. Returns: Numpy data array with substituted values. """ def substitute(val: types.Coordinate): if val == types.AbstractCoordinate.LEFT: return self.time_range[0] if val == types.AbstractCoordinate.RIGHT: return self.time_range[1] if val == types.AbstractCoordinate.TOP: return self.vmax if val == types.AbstractCoordinate.BOTTOM: return self.vmin raise VisualizationError(f"Coordinate {val} is not supported.") try: return np.asarray(vals, dtype=float) except TypeError: return np.asarray(list(map(substitute, vals)), dtype=float) def _check_link_overlap( self, links: dict[str, drawings.GateLinkData] ) -> dict[str, drawings.GateLinkData]: """Helper method to check overlap of bit links. This method dynamically shifts horizontal position of links if they are overlapped. """ duration = self.time_range[1] - self.time_range[0] allowed_overlap = self.formatter["margin.link_interval_percent"] * duration # return y coordinates def y_coords(link: drawings.GateLinkData): return np.array([self.assigned_coordinates.get(bit, np.nan) for bit in link.bits]) # group overlapped links overlapped_group: list[list[str]] = [] data_keys = list(links.keys()) while len(data_keys) > 0: ref_key = data_keys.pop() overlaps = set() overlaps.add(ref_key) for key in data_keys[::-1]: # check horizontal overlap if np.abs(links[ref_key].xvals[0] - links[key].xvals[0]) < allowed_overlap: # check vertical overlap y0s = y_coords(links[ref_key]) y1s = y_coords(links[key]) v1 = np.nanmin(y0s) - np.nanmin(y1s) v2 = np.nanmax(y0s) - np.nanmax(y1s) v3 = np.nanmin(y0s) - np.nanmax(y1s) v4 = np.nanmax(y0s) - np.nanmin(y1s) if not (v1 * v2 > 0 and v3 * v4 > 0): overlaps.add(data_keys.pop(data_keys.index(key))) overlapped_group.append(list(overlaps)) # renew horizontal offset new_links = {} for overlaps in overlapped_group: if len(overlaps) > 1: xpos_mean = np.mean([links[key].xvals[0] for key in overlaps]) # sort link key by y position sorted_keys = sorted(overlaps, key=lambda x: np.nanmax(y_coords(links[x]))) x0 = xpos_mean - 0.5 * allowed_overlap * (len(overlaps) - 1) for ind, key in enumerate(sorted_keys): data = links[key] data.xvals = [x0 + ind * allowed_overlap] new_links[key] = data else: key = overlaps[0] new_links[key] = links[key] return {key: new_links[key] for key in links.keys()}
https://github.com/swe-train/qiskit__qiskit
swe-train
# 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. """ Drawing objects for timeline drawer. Drawing objects play two important roles: - Allowing unittests of visualization module. Usually it is hard for image files to be tested. - Removing program parser from each plotter interface. We can easily add new plotter. This module is based on the structure of matplotlib as it is the primary plotter of the timeline drawer. However this interface is agnostic to the actual plotter. Design concept ~~~~~~~~~~~~~~ When we think about dynamically updating drawings, it will be most efficient to update only the changed properties of drawings rather than regenerating entirely from scratch. Thus the core :py:class:`~qiskit.visualization.timeline.core.DrawerCanvas` generates all possible drawings in the beginning and then the canvas instance manages visibility of each drawing according to the end-user request. Data key ~~~~~~~~ In the abstract class ``ElementaryData`` common attributes to represent a drawing are specified. In addition, drawings have the `data_key` property that returns an unique hash of the object for comparison. This key is generated from a data type, the location of the drawing in the canvas, and associated qubit or classical bit objects. See py:mod:`qiskit.visualization.timeline.types` for detail on the data type. If a data key cannot distinguish two independent objects, you need to add a new data type. The data key may be used in the plotter interface to identify the object. Drawing objects ~~~~~~~~~~~~~~~ To support not only `matplotlib` but also multiple plotters, those drawings should be universal and designed without strong dependency on modules in `matplotlib`. This means drawings that represent primitive geometries are preferred. It should be noted that there will be no unittest for each plotter API, which takes drawings and outputs image data, we should avoid adding a complicated geometry that has a context of the scheduled circuit program. For example, a two qubit scheduled gate may be drawn by two rectangles that represent time occupation of two quantum registers during the gate along with a line connecting these rectangles to identify the pair. This shape can be represented with two box-type objects with one line-type object instead of defining a new object dedicated to the two qubit gate. As many plotters don't support an API that visualizes such a linked-box shape, if we introduce such complex drawings and write a custom wrapper function on top of the existing API, it could be difficult to prevent bugs with the CI tools due to lack of the effective unittest for image data. Link between gates ~~~~~~~~~~~~~~~~~~ The ``GateLinkData`` is the special subclass of drawing that represents a link between bits. Usually objects are associated to the specific bit, but ``GateLinkData`` can be associated with multiple bits to illustrate relationship between quantum or classical bits during a gate operation. """ from abc import ABC from enum import Enum from typing import Optional, Dict, Any, List, Union import numpy as np from qiskit import circuit from qiskit.visualization.timeline import types from qiskit.visualization.exceptions import VisualizationError class ElementaryData(ABC): """Base class of the scheduled circuit visualization object. Note that drawings are mutable. """ __hash__ = None def __init__( self, data_type: Union[str, Enum], xvals: Union[np.ndarray, List[types.Coordinate]], yvals: Union[np.ndarray, List[types.Coordinate]], bits: Optional[Union[types.Bits, List[types.Bits]]] = None, meta: Optional[Dict[str, Any]] = None, styles: Optional[Dict[str, Any]] = None, ): """Create new drawing. Args: data_type: String representation of this drawing. xvals: Series of horizontal coordinate that the object is drawn. yvals: Series of vertical coordinate that the object is drawn. bits: Qubit or Clbit object bound to this drawing. meta: Meta data dictionary of the object. styles: Style keyword args of the object. This conforms to `matplotlib`. """ if bits and isinstance(bits, (circuit.Qubit, circuit.Clbit)): bits = [bits] if isinstance(data_type, Enum): data_type = data_type.value self.data_type = str(data_type) self.xvals = xvals self.yvals = yvals self.bits = bits self.meta = meta self.styles = styles @property def data_key(self): """Return unique hash of this object.""" return str( hash( ( self.__class__.__name__, self.data_type, tuple(self.bits), tuple(self.xvals), tuple(self.yvals), ) ) ) def __repr__(self): return f"{self.__class__.__name__}(type={self.data_type}, key={self.data_key})" def __eq__(self, other): return isinstance(other, self.__class__) and self.data_key == other.data_key class LineData(ElementaryData): """Drawing object that represents line shape.""" def __init__( self, data_type: Union[str, Enum], xvals: Union[np.ndarray, List[types.Coordinate]], yvals: Union[np.ndarray, List[types.Coordinate]], bit: types.Bits, meta: Dict[str, Any] = None, styles: Dict[str, Any] = None, ): """Create new line. Args: data_type: String representation of this drawing. xvals: Series of horizontal coordinate that the object is drawn. yvals: Series of vertical coordinate that the object is drawn. bit: Bit associated to this object. meta: Meta data dictionary of the object. styles: Style keyword args of the object. This conforms to `matplotlib`. """ super().__init__( data_type=data_type, xvals=xvals, yvals=yvals, bits=bit, meta=meta, styles=styles ) class BoxData(ElementaryData): """Drawing object that represents box shape.""" def __init__( self, data_type: Union[str, Enum], xvals: Union[np.ndarray, List[types.Coordinate]], yvals: Union[np.ndarray, List[types.Coordinate]], bit: types.Bits, meta: Dict[str, Any] = None, styles: Dict[str, Any] = None, ): """Create new box. Args: data_type: String representation of this drawing. xvals: Left and right coordinate that the object is drawn. yvals: Top and bottom coordinate that the object is drawn. bit: Bit associated to this object. meta: Meta data dictionary of the object. styles: Style keyword args of the object. This conforms to `matplotlib`. Raises: VisualizationError: When number of data points are not equals to 2. """ if len(xvals) != 2 or len(yvals) != 2: raise VisualizationError("Length of data points are not equals to 2.") super().__init__( data_type=data_type, xvals=xvals, yvals=yvals, bits=bit, meta=meta, styles=styles ) class TextData(ElementaryData): """Drawing object that represents a text on canvas.""" def __init__( self, data_type: Union[str, Enum], xval: types.Coordinate, yval: types.Coordinate, bit: types.Bits, text: str, latex: Optional[str] = None, meta: Dict[str, Any] = None, styles: Dict[str, Any] = None, ): """Create new text. Args: data_type: String representation of this drawing. xval: Horizontal coordinate that the object is drawn. yval: Vertical coordinate that the object is drawn. bit: Bit associated to this object. text: A string to draw on the canvas. latex: If set this string is used instead of `text`. meta: Meta data dictionary of the object. styles: Style keyword args of the object. This conforms to `matplotlib`. """ self.text = text self.latex = latex super().__init__( data_type=data_type, xvals=[xval], yvals=[yval], bits=bit, meta=meta, styles=styles ) class GateLinkData(ElementaryData): """A special drawing data type that represents bit link of multi-bit gates. Note this object takes multiple bits and dedicates them to the bit link. This may appear as a line on the canvas. """ def __init__( self, xval: types.Coordinate, bits: List[types.Bits], styles: Dict[str, Any] = None ): """Create new bit link. Args: xval: Horizontal coordinate that the object is drawn. bits: Bit associated to this object. styles: Style keyword args of the object. This conforms to `matplotlib`. """ super().__init__( data_type=types.LineType.GATE_LINK, xvals=[xval], yvals=[0], bits=bits, meta=None, styles=styles, )
https://github.com/swe-train/qiskit__qiskit
swe-train
# Copyright 2022-2023 Ohad Lev. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0, # or in the root directory of this package("LICENSE.txt"). # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ `SATInterface` class. """ import os import json from typing import List, Tuple, Union, Optional, Dict, Any from sys import stdout from datetime import datetime from hashlib import sha256 from qiskit import transpile, QuantumCircuit, qpy from qiskit.result.counts import Counts from qiskit.visualization.circuit.text import TextDrawing from qiskit.providers.backend import Backend from qiskit.transpiler.passes import RemoveBarriers from IPython import display from matplotlib.figure import Figure from sat_circuits_engine.util import timer_dec, timestamp, flatten_circuit from sat_circuits_engine.util.settings import DATA_PATH, TRANSPILE_KWARGS from sat_circuits_engine.circuit import GroverConstraintsOperator, SATCircuit from sat_circuits_engine.constraints_parse import ParsedConstraints from sat_circuits_engine.interface.circuit_decomposition import decompose_operator from sat_circuits_engine.interface.counts_visualization import plot_histogram from sat_circuits_engine.interface.translator import ConstraintsTranslator from sat_circuits_engine.classical_processing import ( find_iterations_unknown, calc_iterations, ClassicalVerifier, ) from sat_circuits_engine.interface.interactive_inputs import ( interactive_operator_inputs, interactive_solutions_num_input, interactive_run_input, interactive_backend_input, interactive_shots_input, ) # Local globlas for visualization of charts and diagrams IFRAME_WIDTH = "100%" IFRAME_HEIGHT = "700" class SATInterface: """ An interface for building, running and mining data from n-SAT problems quantum circuits. There are 2 options to use this class: (1) Using an interactive interface (intuitive but somewhat limited) - for this just initiate a bare instance of this class: `SATInterface()`. (2) Using the API defined by this class, that includes the following methods: * The following descriptions are partial, for full annotations see the methods' docstrings. - `__init__`: an instance of `SATInterface must be initiated with exactly 1 combination: (a) (high_level_constraints_string + high_level_vars) - for constraints in a high-level format. (b) (num_input_qubits + constraints_string) - for constraints in a low-level foramt. * For formats annotations see `constriants_format.ipynb` in the main directory. - `obtain_grover_operator`: obtains the suitable grover operator for the constraints. - `save_display_grover_operator`: saves and displays data generated by the `obtain_grover_operator` method. - `obtain_overall_circuit`: obtains the suitable overall SAT circuit. - `save_display_overall_circuit: saves and displays data generated by the `obtain_overall_circuit` method. - `run_overall_circuit`: executes the overall SAT circuit. - `save_display_results`: saves and displays data generated by the `run_overall_circuit` method. It is very recommended to go through `demos.ipynb` that demonstrates the various optional uses of this class, in addition to reading `constraints_format.ipynb`, which is a must for using this package properly. Both notebooks are in ther main directory. """ def __init__( self, num_input_qubits: Optional[int] = None, constraints_string: Optional[str] = None, high_level_constraints_string: Optional[str] = None, high_level_vars: Optional[Dict[str, int]] = None, name: Optional[str] = None, save_data: Optional[bool] = True, ) -> None: """ Accepts the combination of paramters: (high_level_constraints_string + high_level_vars) or (num_input_qubits + constraints_string). Exactly one combination is accepted. In other cases either an iteractive user interface will be called to take user's inputs, or an exception will be raised due to misuse of the API. Args: num_input_qubits (Optional[int] = None): number of input qubits. constraints_string (Optional[str] = None): a string of constraints in a low-level format. high_level_constraints_string (Optional[str] = None): a string of constraints in a high-level format. high_level_vars (Optional[Dict[str, int]] = None): a dictionary that configures the high-level variables - keys are names and values are bits-lengths. name (Optional[str] = None): a name for this object, if None than the generic name "SAT" is given automatically. save_data (Optional[bool] = True): if True, saves all data and metadata generated by this class to a unique data folder (by using the `save_XXX` methods of this class). Raises: SyntaxError - if a forbidden combination of arguments has been provided. """ if name is None: name = "SAT" self.name = name # Creating a directory for data to be saved if save_data: self.time_created = timestamp(datetime.now()) self.dir_path = f"{DATA_PATH}{self.time_created}_{self.name}/" os.mkdir(self.dir_path) print(f"Data will be saved into '{self.dir_path}'.") # Initial metadata, more to be added by this class' `save_XXX` methods self.metadata = { "name": self.name, "datetime": self.time_created, "num_input_qubits": num_input_qubits, "constraints_string": constraints_string, "high_level_constraints_string": high_level_constraints_string, "high_level_vars": high_level_vars, } self.update_metadata() # Identifying user's platform, for visualization purposes self.identify_platform() # In the case of low-level constraints format, that is the default value self.high_to_low_map = None # Case A - interactive interface if (num_input_qubits is None or constraints_string is None) and ( high_level_constraints_string is None or high_level_vars is None ): self.interactive_interface() # Case B - API else: self.high_level_constraints_string = high_level_constraints_string self.high_level_vars = high_level_vars # Case B.1 - high-level format constraints inputs if num_input_qubits is None or constraints_string is None: self.num_input_qubits = sum(self.high_level_vars.values()) self.high_to_low_map, self.constraints_string = ConstraintsTranslator( self.high_level_constraints_string, self.high_level_vars ).translate() # Case B.2 - low-level format constraints inputs elif num_input_qubits is not None and constraints_string is not None: self.num_input_qubits = num_input_qubits self.constraints_string = constraints_string # Misuse else: raise SyntaxError( "SATInterface accepts the combination of paramters:" "(high_level_constraints_string + high_level_vars) or " "(num_input_qubits + constraints_string). " "Exactly one combination is accepted, not both." ) self.parsed_constraints = ParsedConstraints( self.constraints_string, self.high_level_constraints_string ) def update_metadata(self, update_metadata: Optional[Dict[str, Any]] = None) -> None: """ Updates the metadata file (in the unique data folder of a given `SATInterface` instance). Args: update_metadata (Optional[Dict[str, Any]] = None): - If None - just dumps `self.metadata` into the metadata JSON file. - If defined - updates the `self.metadata` attribute and then dumps it. """ if update_metadata is not None: self.metadata.update(update_metadata) with open(f"{self.dir_path}metadata.json", "w") as metadata_file: json.dump(self.metadata, metadata_file, indent=4) def identify_platform(self) -> None: """ Identifies user's platform. Writes True to `self.jupyter` for Jupyter notebook, False for terminal. """ # If True then the platform is a terminal/command line/shell if stdout.isatty(): self.jupyter = False # If False, we assume the platform is a Jupyter notebook else: self.jupyter = True def output_to_platform( self, *, title: str, output_terminal: Union[TextDrawing, str], output_jupyter: Union[Figure, str], display_both_on_jupyter: Optional[bool] = False, ) -> None: """ Displays output to user's platform. Args: title (str): a title for the output. output_terminal (Union[TextDrawing, str]): text to print for a terminal platform. output_jupyter: (Union[Figure, str]): objects to display for a Jupyter notebook platform. can handle `Figure` matplotlib objects or strings of paths to IFrame displayable file, e.g PDF files. display_both_on_jupyter (Optional[bool] = False): if True, displays both `output_terminal` and `output_jupyter` in a Jupyter notebook platform. Raises: TypeError - in the case of misusing the `output_jupyter` argument. """ print() print(title) if self.jupyter: if isinstance(output_jupyter, str): display.display(display.IFrame(output_jupyter, width=IFRAME_WIDTH, height=IFRAME_HEIGHT)) elif isinstance(output_jupyter, Figure): display.display(output_jupyter) else: raise TypeError("output_jupyter must be an str (path to image file) or a Figure object.") if display_both_on_jupyter: print(output_terminal) else: print(output_terminal) def interactive_interface(self) -> None: """ An interactive CLI that allows exploiting most (but not all) of the package's features. Uses functions of the form `interactive_XXX_inputs` from the `interactive_inputs.py` module. Divided into 3 main stages: 1. Obtaining Grover's operator for the SAT problem. 2. Obtaining the overall SAT cirucit. 3. Executing the circuit and parsing the results. The interface is built in a modular manner such that a user can halt at any stage. The defualt settings for the interactive user intreface are: 1. `name = "SAT"`. 2. `save_data = True`. 3. `display = True`. 4. `transpile_kwargs = {'basis_gates': ['u', 'cx'], 'optimization_level': 3}`. 5. Backends are limited to those defined in the global-constant-like function `BACKENDS`: - Those are the local `aer_simulator` and the remote `ibmq_qasm_simulator` for now. Due to these default settings the interactive CLI is somewhat restrictive, for full flexibility a user should use the API and not the CLI. """ # Handling operator part operator_inputs = interactive_operator_inputs() self.num_input_qubits = operator_inputs["num_input_qubits"] self.high_to_low_map = operator_inputs["high_to_low_map"] self.constraints_string = operator_inputs["constraints_string"] self.high_level_constraints_string = operator_inputs["high_level_constraints_string"] self.high_level_vars = operator_inputs["high_level_vars"] self.parsed_constraints = ParsedConstraints( self.constraints_string, self.high_level_constraints_string ) self.update_metadata( { "num_input_qubits": self.num_input_qubits, "constraints_string": self.constraints_string, "high_level_constraints_string": self.high_level_constraints_string, "high_level_vars": self.high_level_vars, } ) obtain_grover_operator_output = self.obtain_grover_operator() self.save_display_grover_operator(obtain_grover_operator_output) # Handling overall circuit part solutions_num = interactive_solutions_num_input() if solutions_num is not None: backend = None if solutions_num == -1: backend = interactive_backend_input() overall_circuit_data = self.obtain_overall_sat_circuit( obtain_grover_operator_output["operator"], solutions_num, backend ) self.save_display_overall_circuit(overall_circuit_data) # Handling circuit execution part if interactive_run_input(): if backend is None: backend = interactive_backend_input() shots = interactive_shots_input() counts_parsed = self.run_overall_sat_circuit( overall_circuit_data["circuit"], backend, shots ) self.save_display_results(counts_parsed) print() print(f"Done saving data into '{self.dir_path}'.") def obtain_grover_operator( self, transpile_kwargs: Optional[Dict[str, Any]] = None ) -> Dict[str, Union[GroverConstraintsOperator, QuantumCircuit]]: """ Obtains the suitable `GroverConstraintsOperator` object for the constraints, decomposes it using the `circuit_decomposition.py` module and transpiles it according to `transpile_kwargs`. Args: transpile_kwargs (Optional[Dict[str, Any]]): kwargs for Qiskit's transpile function. The defualt is set to the global constant `TRANSPILE_KWARGS`. Returns: (Dict[str, Union[GroverConstraintsOperator, QuantumCircuit, Dict[str, List[int]]]]): - 'operator' (GroverConstraintsOperator):the high-level blocks operator. - 'decomposed_operator' (QuantumCircuit): decomposed to building-blocks operator. * For annotations regarding the decomposition method see the `circuit_decomposition` module. - 'transpiled_operator' (QuantumCircuit): the transpiled operator. *** The high-level operator and the decomposed operator are generated with barriers between constraints as default for visualizations purposes. The barriers are stripped off before transpiling so the the transpiled operator object contains no barriers. *** - 'high_level_to_bit_indexes_map' (Optional[Dict[str, List[int]]] = None): A map of high-level variables with their allocated bit-indexes in the input register. """ print() print( "The system synthesizes and transpiles a Grover's " "operator for the given constraints. Please wait.." ) if transpile_kwargs is None: transpile_kwargs = TRANSPILE_KWARGS self.transpile_kwargs = transpile_kwargs operator = GroverConstraintsOperator( self.parsed_constraints, self.num_input_qubits, insert_barriers=True ) decomposed_operator = decompose_operator(operator) no_baerriers_operator = RemoveBarriers()(operator) transpiled_operator = transpile(no_baerriers_operator, **transpile_kwargs) print("Done.") return { "operator": operator, "decomposed_operator": decomposed_operator, "transpiled_operator": transpiled_operator, "high_level_to_bit_indexes_map": self.high_to_low_map, } def save_display_grover_operator( self, obtain_grover_operator_output: Dict[str, Union[GroverConstraintsOperator, QuantumCircuit]], display: Optional[bool] = True, ) -> None: """ Handles saving and displaying data generated by the `self.obtain_grover_operator` method. Args: obtain_grover_operator_output(Dict[str, Union[GroverConstraintsOperator, QuantumCircuit]]): the dictionary returned upon calling the `self.obtain_grover_operator` method. display (Optional[bool] = True) - If true, displays objects to user's platform. """ # Creating a directory to save operator's data operator_dir_path = f"{self.dir_path}grover_operator/" os.mkdir(operator_dir_path) # Titles for displaying objects, by order of `obtain_grover_operator_output` titles = [ "The operator diagram - high level blocks:", "The operator diagram - decomposed:", f"The transpiled operator diagram saved into '{operator_dir_path}'.\n" f"It's not presented here due to its complexity.\n" f"Please note that barriers appear in the high-level diagrams above only for convenient\n" f"visual separation between constraints.\n" f"Before transpilation all barriers are removed to avoid redundant inefficiencies.", ] for index, (op_name, op_obj) in enumerate(obtain_grover_operator_output.items()): # Generic path and name for files to be saved files_path = f"{operator_dir_path}{op_name}" # Generating a circuit diagrams figure figure_path = f"{files_path}.pdf" op_obj.draw("mpl", filename=figure_path, fold=-1) # Generating a QPY serialization file for the circuit object qpy_file_path = f"{files_path}.qpy" with open(qpy_file_path, "wb") as qpy_file: qpy.dump(op_obj, qpy_file) # Original high-level operator and decomposed operator if index < 2 and display: # Displaying to user self.output_to_platform( title=titles[index], output_terminal=op_obj.draw("text"), output_jupyter=figure_path ) # Transpiled operator elif index == 2: # Output to user, not including the circuit diagram print() print(titles[index]) print() print(f"The transpilation kwargs are: {self.transpile_kwargs}.") transpiled_operator_depth = op_obj.depth() transpiled_operator_gates_count = op_obj.count_ops() print(f"Transpiled operator depth: {transpiled_operator_depth}.") print(f"Transpiled operator gates count: {transpiled_operator_gates_count}.") print(f"Total number of qubits: {op_obj.num_qubits}.") # Generating QASM 2.0 file only for the (flattened = no registers) tranpsiled operator qasm_file_path = f"{files_path}.qasm" flatten_circuit(op_obj).qasm(filename=qasm_file_path) # Index 3 is 'high_level_to_bit_indexes_map' so it's time to break from the loop break # Mapping from high-level variables to bit-indexes will be displayed as well mapping = obtain_grover_operator_output["high_level_to_bit_indexes_map"] if mapping: print() print(f"The high-level variables mapping to bit-indexes:\n{mapping}") print() print( f"Saved into '{operator_dir_path}':\n", " Circuit diagrams for all levels.\n", " QPY serialization exports for all levels.\n", " QASM 2.0 export only for the transpiled level.", ) with open(f"{operator_dir_path}operator.qpy", "rb") as qpy_file: operator_qpy_sha256 = sha256(qpy_file.read()).hexdigest() self.update_metadata( { "high_level_to_bit_indexes_map": self.high_to_low_map, "transpile_kwargs": self.transpile_kwargs, "transpiled_operator_depth": transpiled_operator_depth, "transpiled_operator_gates_count": transpiled_operator_gates_count, "operator_qpy_sha256": operator_qpy_sha256, } ) def obtain_overall_sat_circuit( self, grover_operator: GroverConstraintsOperator, solutions_num: int, backend: Optional[Backend] = None, ) -> Dict[str, SATCircuit]: """ Obtains the suitable `SATCircuit` object (= the overall SAT circuit) for the SAT problem. Args: grover_operator (GroverConstraintsOperator): Grover's operator for the SAT problem. solutions_num (int): number of solutions for the SAT problem. In the case the number of solutions is unknown, specific negative values are accepted: * '-1' - for launching a classical iterative stochastic process that finds an adequate number of iterations - by calling the `find_iterations_unknown` function (see its docstrings for more information). * '-2' - for generating a dynamic circuit that iterates over Grover's iterator until a solution is obtained, using weak measurements. TODO - this feature isn't ready yet. backend (Optional[Backend] = None): in the case of a '-1' value given to `solutions_num`, a backend object to execute the depicted iterative prcess upon should be provided. Returns: (Dict[str, SATCircuit]): - 'circuit' key for the overall SAT circuit. - 'concise_circuit' key for the overall SAT circuit, with only 1 iteration over Grover's iterator (operator + diffuser). Useful for visualization purposes. *** The concise circuit is generated with barriers between segments as default for visualizations purposes. In the actual circuit there no barriers. *** """ # -1 = Unknown number of solutions - iterative stochastic process print() if solutions_num == -1: assert backend is not None, "Need to specify a backend if `solutions_num == -1`." print("Please wait while the system checks various solutions..") circuit, iterations = find_iterations_unknown( self.num_input_qubits, grover_operator, self.parsed_constraints, precision=10, backend=backend, ) print() print(f"An adequate number of iterations found = {iterations}.") # -2 = Unknown number of solutions - implement a dynamic circuit # TODO this feature isn't fully implemented yet elif solutions_num == -2: print("The system builds a dynamic circuit..") circuit = SATCircuit(self.num_input_qubits, grover_operator, iterations=None) circuit.add_input_reg_measurement() iterations = None # Known number of solutions else: print("The system builds the overall circuit..") iterations = calc_iterations(self.num_input_qubits, solutions_num) print(f"\nFor {solutions_num} solutions, {iterations} iterations needed.") circuit = SATCircuit( self.num_input_qubits, grover_operator, iterations, insert_barriers=False ) circuit.add_input_reg_measurement() self.iterations = iterations # Obtaining a SATCircuit object with one iteration for concise representation concise_circuit = SATCircuit( self.num_input_qubits, grover_operator, iterations=1, insert_barriers=True ) concise_circuit.add_input_reg_measurement() return {"circuit": circuit, "concise_circuit": concise_circuit} def save_display_overall_circuit( self, obtain_overall_sat_circuit_output: Dict[str, SATCircuit], display: Optional[bool] = True ) -> None: """ Handles saving and displaying data generated by the `self.obtain_overall_sat_circuit` method. Args: obtain_overall_sat_circuit_output(Dict[str, SATCircuit]): the dictionary returned upon calling the `self.obtain_overall_sat_circuit` method. display (Optional[bool] = True) - If true, displays objects to user's platform. """ circuit = obtain_overall_sat_circuit_output["circuit"] concise_circuit = obtain_overall_sat_circuit_output["concise_circuit"] # Creating a directory to save overall circuit's data overall_circuit_dir_path = f"{self.dir_path}overall_circuit/" os.mkdir(overall_circuit_dir_path) # Generating a figure of the overall SAT circuit with just 1 iteration (i.e "concise") concise_circuit_fig_path = f"{overall_circuit_dir_path}overall_circuit_1_iteration.pdf" concise_circuit.draw("mpl", filename=concise_circuit_fig_path, fold=-1) # Displaying the concise circuit to user if display: if self.iterations: self.output_to_platform( title=( f"The high level circuit contains {self.iterations}" f" iterations of the following form:" ), output_terminal=concise_circuit.draw("text"), output_jupyter=concise_circuit_fig_path, ) # Dynamic circuit case - TODO NOT FULLY IMPLEMENTED YET else: dynamic_circuit_fig_path = f"{overall_circuit_dir_path}overall_circuit_dynamic.pdf" circuit.draw("mpl", filename=dynamic_circuit_fig_path, fold=-1) self.output_to_platform( title="The dynamic circuit diagram:", output_terminal=circuit.draw("text"), output_jupyter=dynamic_circuit_fig_path, ) if self.iterations: transpiled_overall_circuit = transpile(flatten_circuit(circuit), **self.transpile_kwargs) print() print(f"The transpilation kwargs are: {self.transpile_kwargs}.") transpiled_overall_circuit_depth = transpiled_overall_circuit.depth() transpiled_overall_circuit_gates_count = transpiled_overall_circuit.count_ops() print(f"Transpiled overall-circuit depth: {transpiled_overall_circuit_depth}.") print(f"Transpiled overall-circuit gates count: {transpiled_overall_circuit_gates_count}.") print(f"Total number of qubits: {transpiled_overall_circuit.num_qubits}.") print() print("Exporting the full overall SAT circuit object..") export_files_path = f"{overall_circuit_dir_path}overall_circuit" with open(f"{export_files_path}.qpy", "wb") as qpy_file: qpy.dump(circuit, qpy_file) if self.iterations: transpiled_overall_circuit.qasm(filename=f"{export_files_path}.qasm") print() print( f"Saved into '{overall_circuit_dir_path}':\n", " A concised (1 iteration) circuit diagram of the high-level overall SAT circuit.\n", " QPY serialization export for the full overall SAT circuit object.", ) if self.iterations: print(" QASM 2.0 export for the transpiled full overall SAT circuit object.") metadata_update = { "num_total_qubits": circuit.num_qubits, "num_iterations": circuit.iterations, } if self.iterations: metadata_update["transpiled_overall_circuit_depth"] = (transpiled_overall_circuit_depth,) metadata_update[ "transpiled_overall_circuit_gates_count" ] = transpiled_overall_circuit_gates_count self.update_metadata(metadata_update) @timer_dec("Circuit simulation execution time = ") def run_overall_sat_circuit( self, circuit: QuantumCircuit, backend: Backend, shots: int ) -> Dict[str, Union[Counts, List[Tuple[Union[str, int]]], List[str], List[Dict[str, int]]]]: """ Executes a `circuit` on `backend` transpiled w.r.t backend, `shots` times. Args: circuit (QuantumCircuit): `QuantumCircuit` object or child-object (a.k.a `SATCircuit`) to execute. backend (Backend): backend to execute `circuit` upon. shots (int): number of execution shots. Returns: (Dict[str, Union[Counts, List[Tuple[Union[str, int]]], List[str], List[Dict[str, int]]]]): dict object returned by `self.parse_counts` - see this method's docstrings for annotations. """ # Defines also instance attributes to use in other methods self.backend = backend self.shots = shots print() print(f"The system is running the circuit {shots} times on {backend}, please wait..") print("This process might take a while.") job = backend.run(transpile(circuit, backend), shots=shots) counts = job.result().get_counts() print("Done.") parsed_counts = self.parse_counts(counts) return parsed_counts def parse_counts( self, counts: Counts ) -> Dict[str, Union[Counts, List[Tuple[Union[str, int]]], List[str], List[Dict[str, int]]]]: """ Parses a `Counts` object into several desired datas (see 'Returns' section). Args: counts (Counts): the `Counts` object to parse. Returns: (Dict[str, Union[Counts, List[Tuple[Union[str, int]]], List[str], List[Dict[str, int]]]]): 'counts' (Counts) - the original `Counts` object. 'counts_sorted' (List[Tuple[Union[str, int]]]) - results sorted in a descending order. 'distilled_solutions' (List[str]): list of solutions (bitstrings). 'high_level_vars_values' (List[Dict[str, int]]): list of solutions (each solution is a dictionary with variable-names as keys and their integer values as values). """ # Sorting results in an a descending order counts_sorted = sorted(counts.items(), key=lambda x: x[1], reverse=True) # Generating a set of distilled verified-only solutions verifier = ClassicalVerifier(self.parsed_constraints) distilled_solutions = set() for count_item in counts_sorted: if not verifier.verify(count_item[0]): break distilled_solutions.add(count_item[0]) # In the case of high-level format in use, translating `distilled_solutions` into integer values high_level_vars_values = None if self.high_level_constraints_string and self.high_level_vars: # Container for dictionaries with variables integer values high_level_vars_values = [] for solution in distilled_solutions: # Keys are variable-names and values are their integer values solution_vars = {} for var, bits_bundle in self.high_to_low_map.items(): reversed_solution = solution[::-1] var_bitstring = "" for bit_index in bits_bundle: var_bitstring += reversed_solution[bit_index] # Translating to integer value solution_vars[var] = int(var_bitstring, 2) high_level_vars_values.append(solution_vars) return { "counts": counts, "counts_sorted": counts_sorted, "distilled_solutions": distilled_solutions, "high_level_vars_values": high_level_vars_values, } def save_display_results( self, run_overall_sat_circuit_output: Dict[ str, Union[Counts, List[Tuple[Union[str, int]]], List[str], List[Dict[str, int]]] ], display: Optional[bool] = True, ) -> None: """ Handles saving and displaying data generated by the `self.run_overall_sat_circuit` method. Args: run_overall_sat_circuit_output (Dict[str, Union[Counts, List[Tuple[Union[str, int]]], List[str], List[Dict[str, int]]]]): the dictionary returned upon calling the `self.run_overall_sat_circuit` method. display (Optional[bool] = True) - If true, displays objects to user's platform. """ counts = run_overall_sat_circuit_output["counts"] counts_sorted = run_overall_sat_circuit_output["counts_sorted"] distilled_solutions = run_overall_sat_circuit_output["distilled_solutions"] high_level_vars_values = run_overall_sat_circuit_output["high_level_vars_values"] # Creating a directory to save results data results_dir_path = f"{self.dir_path}results/" os.mkdir(results_dir_path) # Defining custom dimensions for the custom `plot_histogram` of this package histogram_fig_width = max((len(counts) * self.num_input_qubits * (10 / 72)), 7) histogram_fig_height = 5 histogram_figsize = (histogram_fig_width, histogram_fig_height) histogram_path = f"{results_dir_path}histogram.pdf" plot_histogram(counts, figsize=histogram_figsize, sort="value_desc", filename=histogram_path) if display: # Basic output text output_text = ( f"All counts:\n{counts_sorted}\n" f"\nDistilled solutions ({len(distilled_solutions)} total):\n" f"{distilled_solutions}" ) # Additional outputs for a high-level constraints format if high_level_vars_values: # Mapping from high-level variables to bit-indexes will be displayed as well output_text += ( f"\n\nThe high-level variables mapping to bit-indexes:" f"\n{self.high_to_low_map}" ) # Actual integer solutions will be displayed as well additional_text = "" for solution_index, solution in enumerate(high_level_vars_values): additional_text += f"Solution {solution_index + 1}: " for var_index, (var, value) in enumerate(solution.items()): additional_text += f"{var} = {value}" if var_index != len(solution) - 1: additional_text += ", " else: additional_text += "\n" output_text += f"\n\nHigh-level format solutions: \n{additional_text}" self.output_to_platform( title=f"The results for {self.shots} shots are:", output_terminal=output_text, output_jupyter=histogram_path, display_both_on_jupyter=True, ) results_dict = { "high_level_to_bit_indexes_map": self.high_to_low_map, "solutions": list(distilled_solutions), "high_level_solutions": high_level_vars_values, "counts": counts_sorted, } with open(f"{results_dir_path}results.json", "w") as results_file: json.dump(results_dict, results_file, indent=4) self.update_metadata( { "num_solutions": len(distilled_solutions), "backend": str(self.backend), "shots": self.shots, } )
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ A collection of functions that decide the layout of an output image. See :py:mod:`~qiskit.visualization.timeline.types` for more info on the required data. There are 2 types of layout functions in this module. 1. layout.bit_arrange In this stylesheet entry the input data is a list of `types.Bits` and returns a sorted list of `types.Bits`. The function signature of the layout is restricted to: ```python def my_layout(bits: List[types.Bits]) -> List[types.Bits]: # your code here: sort input bits and return list of bits ``` 2. layout.time_axis_map In this stylesheet entry the input data is `Tuple[int, int]` that represents horizontal axis limit of the output image. The layout function returns `types.HorizontalAxis` data which is consumed by the plotter API to make horizontal axis. The function signature of the layout is restricted to: ```python def my_layout(time_window: Tuple[int, int]) -> types.HorizontalAxis: # your code here: create and return axis config ``` Arbitrary layout function satisfying the above format can be accepted. """ import warnings from typing import List, Tuple import numpy as np from qiskit import circuit from qiskit.visualization.exceptions import VisualizationError from qiskit.visualization.timeline import types def qreg_creg_ascending(bits: List[types.Bits]) -> List[types.Bits]: """Sort bits by ascending order. Bit order becomes Q0, Q1, ..., Cl0, Cl1, ... Args: bits: List of bits to sort. Returns: Sorted bits. """ qregs = [] cregs = [] for bit in bits: if isinstance(bit, circuit.Qubit): qregs.append(bit) elif isinstance(bit, circuit.Clbit): cregs.append(bit) else: raise VisualizationError(f"Unknown bit {bit} is provided.") with warnings.catch_warnings(): warnings.simplefilter("ignore") qregs = sorted(qregs, key=lambda x: x.index, reverse=False) cregs = sorted(cregs, key=lambda x: x.index, reverse=False) return qregs + cregs def qreg_creg_descending(bits: List[types.Bits]) -> List[types.Bits]: """Sort bits by descending order. Bit order becomes Q_N, Q_N-1, ..., Cl_N, Cl_N-1, ... Args: bits: List of bits to sort. Returns: Sorted bits. """ qregs = [] cregs = [] for bit in bits: if isinstance(bit, circuit.Qubit): qregs.append(bit) elif isinstance(bit, circuit.Clbit): cregs.append(bit) else: raise VisualizationError(f"Unknown bit {bit} is provided.") qregs = sorted(qregs, key=lambda x: x.index, reverse=True) cregs = sorted(cregs, key=lambda x: x.index, reverse=True) return qregs + cregs def time_map_in_dt(time_window: Tuple[int, int]) -> types.HorizontalAxis: """Layout function for the horizontal axis formatting. Generate equispaced 6 horizontal axis ticks. Args: time_window: Left and right edge of this graph. Returns: Axis formatter object. """ # shift time axis t0, t1 = time_window # axis label axis_loc = np.linspace(max(t0, 0), t1, 6) axis_label = axis_loc.copy() # consider time resolution label = "System cycle time (dt)" formatted_label = [f"{val:.0f}" for val in axis_label] return types.HorizontalAxis( window=(t0, t1), axis_map=dict(zip(axis_loc, formatted_label)), label=label )
https://github.com/swe-train/qiskit__qiskit
swe-train
# 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. """ Special data types. """ from enum import Enum from typing import NamedTuple, List, Union, NewType, Tuple, Dict from qiskit import circuit ScheduledGate = NamedTuple( "ScheduledGate", [ ("t0", int), ("operand", circuit.Gate), ("duration", int), ("bits", List[Union[circuit.Qubit, circuit.Clbit]]), ("bit_position", int), ], ) ScheduledGate.__doc__ = "A gate instruction with embedded time." ScheduledGate.t0.__doc__ = "Time when the instruction is issued." ScheduledGate.operand.__doc__ = "Gate object associated with the gate." ScheduledGate.duration.__doc__ = "Time duration of the instruction." ScheduledGate.bits.__doc__ = "List of bit associated with the gate." ScheduledGate.bit_position.__doc__ = "Position of bit associated with this drawing source." GateLink = NamedTuple( "GateLink", [("t0", int), ("opname", str), ("bits", List[Union[circuit.Qubit, circuit.Clbit]])] ) GateLink.__doc__ = "Dedicated object to represent a relationship between instructions." GateLink.t0.__doc__ = "A position where the link is placed." GateLink.opname.__doc__ = "Name of gate associated with this link." GateLink.bits.__doc__ = "List of bit associated with the instruction." Barrier = NamedTuple( "Barrier", [("t0", int), ("bits", List[Union[circuit.Qubit, circuit.Clbit]]), ("bit_position", int)], ) Barrier.__doc__ = "Dedicated object to represent a barrier instruction." Barrier.t0.__doc__ = "A position where the barrier is placed." Barrier.bits.__doc__ = "List of bit associated with the instruction." Barrier.bit_position.__doc__ = "Position of bit associated with this drawing source." HorizontalAxis = NamedTuple( "HorizontalAxis", [("window", Tuple[int, int]), ("axis_map", Dict[int, int]), ("label", str)] ) HorizontalAxis.__doc__ = "Data to represent configuration of horizontal axis." HorizontalAxis.window.__doc__ = "Left and right edge of graph." HorizontalAxis.axis_map.__doc__ = "Mapping of apparent coordinate system and actual location." HorizontalAxis.label.__doc__ = "Label of horizontal axis." class BoxType(str, Enum): """Box type. SCHED_GATE: Box that represents occupation time by gate. DELAY: Box associated with delay. TIMELINE: Box that represents time slot of a bit. """ SCHED_GATE = "Box.ScheduledGate" DELAY = "Box.Delay" TIMELINE = "Box.Timeline" class LineType(str, Enum): """Line type. BARRIER: Line that represents barrier instruction. GATE_LINK: Line that represents a link among gates. """ BARRIER = "Line.Barrier" GATE_LINK = "Line.GateLink" class SymbolType(str, Enum): """Symbol type. FRAME: Symbol that represents zero time frame change (Rz) instruction. """ FRAME = "Symbol.Frame" class LabelType(str, Enum): """Label type. GATE_NAME: Label that represents name of gate. DELAY: Label associated with delay. GATE_PARAM: Label that represents parameter of gate. BIT_NAME: Label that represents name of bit. """ GATE_NAME = "Label.Gate.Name" DELAY = "Label.Delay" GATE_PARAM = "Label.Gate.Param" BIT_NAME = "Label.Bit.Name" class AbstractCoordinate(Enum): """Abstract coordinate that the exact value depends on the user preference. RIGHT: The horizontal coordinate at t0 shifted by the left margin. LEFT: The horizontal coordinate at tf shifted by the right margin. TOP: The vertical coordinate at the top of the canvas. BOTTOM: The vertical coordinate at the bottom of the canvas. """ RIGHT = "RIGHT" LEFT = "LEFT" TOP = "TOP" BOTTOM = "BOTTOM" class Plotter(str, Enum): """Name of timeline plotter APIs. MPL: Matplotlib plotter interface. Show timeline in 2D canvas. """ MPL = "mpl" # convenient type to represent union of drawing data DataTypes = NewType("DataType", Union[BoxType, LabelType, LineType, SymbolType]) # convenient type to represent union of values to represent a coordinate Coordinate = NewType("Coordinate", Union[float, AbstractCoordinate]) # Valid bit objects Bits = NewType("Bits", Union[circuit.Qubit, circuit.Clbit])
https://github.com/swe-train/qiskit__qiskit
swe-train
# 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. # pylint: disable=missing-docstring,invalid-name,no-member # pylint: disable=attribute-defined-outside-init import itertools from qiskit import QuantumRegister, QuantumCircuit from qiskit.circuit import Parameter def build_circuit(width, gates): qr = QuantumRegister(width) qc = QuantumCircuit(qr) while len(qc) < gates: for k in range(width): qc.h(qr[k]) for k in range(width - 1): qc.cx(qr[k], qr[k + 1]) return qc class CircuitConstructionBench: params = ([1, 2, 5, 8, 14, 20], [8, 128, 2048, 8192, 32768, 131072]) param_names = ["width", "gates"] timeout = 600 def setup(self, width, gates): self.empty_circuit = build_circuit(width, 0) self.sample_circuit = build_circuit(width, gates) def time_circuit_construction(self, width, gates): build_circuit(width, gates) def time_circuit_extend(self, _, __): self.empty_circuit.extend(self.sample_circuit) def time_circuit_copy(self, _, __): self.sample_circuit.copy() def build_parameterized_circuit(width, gates, param_count): params = [Parameter("param-%s" % x) for x in range(param_count)] param_iter = itertools.cycle(params) qr = QuantumRegister(width) qc = QuantumCircuit(qr) while len(qc) < gates: for k in range(width): param = next(param_iter) qc.u2(0, param, qr[k]) for k in range(width - 1): param = next(param_iter) qc.crx(param, qr[k], qr[k + 1]) return qc, params class ParameterizedCircuitConstructionBench: params = ([20], [8, 128, 2048, 8192, 32768, 131072], [8, 128, 2048, 8192, 32768, 131072]) param_names = ["width", "gates", "number of params"] timeout = 600 def setup(self, _, gates, params): if params > gates: raise NotImplementedError def time_build_parameterized_circuit(self, width, gates, params): build_parameterized_circuit(width, gates, params) class ParameterizedCircuitBindBench: params = ([20], [8, 128, 2048, 8192, 32768, 131072], [8, 128, 2048, 8192, 32768, 131072]) param_names = ["width", "gates", "number of params"] timeout = 600 def setup(self, width, gates, params): if params > gates: raise NotImplementedError self.circuit, self.params = build_parameterized_circuit(width, gates, params) def time_bind_params(self, _, __, ___): self.circuit.bind_parameters({x: 3.14 for x in self.params})
https://github.com/swe-train/qiskit__qiskit
swe-train
# 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. # pylint: disable=no-member,invalid-name,missing-docstring,no-name-in-module # pylint: disable=attribute-defined-outside-init,unsubscriptable-object from qiskit import converters from qiskit import qasm from .utils import random_circuit class ConverterBenchmarks: params = ([1, 2, 5, 8, 14, 20, 32, 53], [8, 128, 2048, 8192]) param_names = ["n_qubits", "depth"] timeout = 600 def setup(self, n_qubits, depth): seed = 42 # NOTE: Remove the benchmarks larger than 20x2048 and 14x8192, this is # a tradeoff for speed of benchmarking, creating circuits this size # takes more time than is worth it for benchmarks that take a couple # seconds if n_qubits >= 20: if depth >= 2048: raise NotImplementedError elif n_qubits == 14: if depth > 2048: raise NotImplementedError self.qc = random_circuit(n_qubits, depth, measure=True, conditional=True, seed=seed) self.dag = converters.circuit_to_dag(self.qc) self.qasm = qasm.Qasm(data=self.qc.qasm()).parse() def time_circuit_to_dag(self, *_): converters.circuit_to_dag(self.qc) def time_circuit_to_instruction(self, *_): converters.circuit_to_instruction(self.qc) def time_dag_to_circuit(self, *_): converters.dag_to_circuit(self.dag) def time_ast_to_circuit(self, *_): converters.ast_to_dag(self.qasm)
https://github.com/swe-train/qiskit__qiskit
swe-train
# 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. # pylint: disable=no-member,invalid-name,missing-docstring,no-name-in-module # pylint: disable=attribute-defined-outside-init,unsubscriptable-object """Module for estimating import times.""" from sys import executable from subprocess import call class QiskitImport: def time_qiskit_import(self): call((executable, "-c", "import qiskit"))
https://github.com/swe-train/qiskit__qiskit
swe-train
# 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. # pylint: disable=missing-docstring,invalid-name,no-member # pylint: disable=attribute-defined-outside-init # pylint: disable=unused-argument from qiskit import QuantumRegister, QuantumCircuit from qiskit.compiler import transpile from qiskit.quantum_info.random import random_unitary class IsometryTranspileBench: params = ([0, 1, 2, 3], [3, 4, 5, 6]) param_names = ["number of input qubits", "number of output qubits"] def setup(self, m, n): q = QuantumRegister(n) qc = QuantumCircuit(q) if not hasattr(qc, "iso"): raise NotImplementedError iso = random_unitary(2**n, seed=0).data[:, 0 : 2**m] if len(iso.shape) == 1: iso = iso.reshape((len(iso), 1)) qc.iso(iso, q[:m], q[m:]) self.circuit = qc def track_cnot_counts_after_mapping_to_ibmq_16_melbourne(self, *unused): coupling = [ [1, 0], [1, 2], [2, 3], [4, 3], [4, 10], [5, 4], [5, 6], [5, 9], [6, 8], [7, 8], [9, 8], [9, 10], [11, 3], [11, 10], [11, 12], [12, 2], [13, 1], [13, 12], ] circuit = transpile( self.circuit, basis_gates=["u1", "u3", "u2", "cx"], coupling_map=coupling, seed_transpiler=0, ) counts = circuit.count_ops() cnot_count = counts.get("cx", 0) return cnot_count
https://github.com/swe-train/qiskit__qiskit
swe-train
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2018, 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. """ This module contains the definition of a base class for quantum fourier transforms. """ from abc import abstractmethod from qiskit import QuantumRegister, QuantumCircuit from qiskit.aqua import Pluggable, AquaError class QFT(Pluggable): """Base class for QFT. This method should initialize the module and its configuration, and use an exception if a component of the module is available. Args: configuration (dict): configuration dictionary """ @abstractmethod def __init__(self, *args, **kwargs): super().__init__() @classmethod def init_params(cls, params): qft_params = params.get(Pluggable.SECTION_KEY_QFT) kwargs = {k: v for k, v in qft_params.items() if k != 'name'} return cls(**kwargs) @abstractmethod def _build_matrix(self): raise NotImplementedError @abstractmethod def _build_circuit(self, qubits=None, circuit=None, do_swaps=True): raise NotImplementedError def construct_circuit(self, mode='circuit', qubits=None, circuit=None, do_swaps=True): """Construct the circuit. Args: mode (str): 'matrix' or 'circuit' qubits (QuantumRegister or qubits): register or qubits to build the circuit on. circuit (QuantumCircuit): circuit for construction. do_swaps (bool): include the swaps. Returns: The matrix or circuit depending on the specified mode. """ if mode == 'circuit': return self._build_circuit(qubits=qubits, circuit=circuit, do_swaps=do_swaps) elif mode == 'matrix': return self._build_matrix() else: raise AquaError('Unrecognized mode: {}.'.format(mode))
https://github.com/swe-train/qiskit__qiskit
swe-train
# 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. # pylint: disable=no-member,invalid-name,missing-docstring,no-name-in-module # pylint: disable=attribute-defined-outside-init,unsubscriptable-object import os from qiskit import QuantumCircuit from qiskit.compiler import transpile class QUEKOTranspilerBench: params = ([0, 1, 2, 3], [None, "sabre"]) param_names = ["optimization level", "routing/layout method"] timeout = 600 # pylint: disable=unused-argument def setup(self, optimization_level, routing_method): self.rochester_coupling_map = [ [0, 5], [0, 1], [1, 2], [1, 0], [2, 3], [2, 1], [3, 4], [3, 2], [4, 6], [4, 3], [5, 9], [5, 0], [6, 13], [6, 4], [7, 16], [7, 8], [8, 9], [8, 7], [9, 10], [9, 8], [9, 5], [10, 11], [10, 9], [11, 17], [11, 12], [11, 10], [12, 13], [12, 11], [13, 14], [13, 12], [13, 6], [14, 15], [14, 13], [15, 18], [15, 14], [16, 19], [16, 7], [17, 23], [17, 11], [18, 27], [18, 15], [19, 20], [19, 16], [20, 21], [20, 19], [21, 28], [21, 22], [21, 20], [22, 23], [22, 21], [23, 24], [23, 22], [23, 17], [24, 25], [24, 23], [25, 29], [25, 26], [25, 24], [26, 27], [26, 25], [27, 26], [27, 18], [28, 32], [28, 21], [29, 36], [29, 25], [30, 39], [30, 31], [31, 32], [31, 30], [32, 33], [32, 31], [32, 28], [33, 34], [33, 32], [34, 40], [34, 35], [34, 33], [35, 36], [35, 34], [36, 37], [36, 35], [36, 29], [37, 38], [37, 36], [38, 41], [38, 37], [39, 42], [39, 30], [40, 46], [40, 34], [41, 50], [41, 38], [42, 43], [42, 39], [43, 44], [43, 42], [44, 51], [44, 45], [44, 43], [45, 46], [45, 44], [46, 47], [46, 45], [46, 40], [47, 48], [47, 46], [48, 52], [48, 49], [48, 47], [49, 50], [49, 48], [50, 49], [50, 41], [51, 44], [52, 48], ] self.tokyo_coupling_map = [ [0, 1], [1, 2], [2, 3], [3, 4], [0, 5], [1, 6], [1, 7], [2, 6], [2, 7], [3, 8], [3, 9], [4, 8], [4, 9], [5, 6], [6, 7], [7, 8], [8, 9], [5, 10], [5, 11], [6, 10], [6, 11], [7, 12], [7, 13], [8, 12], [8, 13], [9, 14], [10, 11], [11, 12], [12, 13], [13, 14], [10, 15], [11, 16], [11, 17], [12, 16], [12, 17], [13, 18], [13, 19], [14, 18], [14, 19], [15, 16], [16, 17], [17, 18], [18, 19], ] self.sycamore_coupling_map = [ [0, 6], [1, 6], [1, 7], [2, 7], [2, 8], [3, 8], [3, 9], [4, 9], [4, 10], [5, 10], [5, 11], [6, 12], [6, 13], [7, 13], [7, 14], [8, 14], [8, 15], [9, 15], [9, 16], [10, 16], [10, 17], [11, 17], [12, 18], [13, 18], [13, 19], [14, 19], [14, 20], [15, 20], [15, 21], [16, 21], [16, 22], [17, 22], [17, 23], [18, 24], [18, 25], [19, 25], [19, 26], [20, 26], [20, 27], [21, 27], [21, 28], [22, 28], [22, 29], [23, 29], [24, 30], [25, 30], [25, 31], [26, 31], [26, 32], [27, 32], [27, 33], [28, 33], [28, 34], [29, 34], [29, 35], [30, 36], [30, 37], [31, 37], [31, 38], [32, 38], [32, 39], [33, 39], [33, 40], [34, 40], [34, 41], [35, 41], [36, 42], [37, 42], [37, 43], [38, 43], [38, 44], [39, 44], [39, 45], [40, 45], [40, 46], [41, 46], [41, 47], [42, 48], [42, 49], [43, 49], [43, 50], [44, 50], [44, 51], [45, 51], [45, 52], [46, 52], [46, 53], [47, 53], ] self.basis_gates = ["id", "rz", "sx", "x", "cx"] self.qasm_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "qasm")) self.bigd = QuantumCircuit.from_qasm_file( os.path.join(self.qasm_path, "20QBT_45CYC_.0D1_.1D2_3.qasm") ) self.bss = QuantumCircuit.from_qasm_file( os.path.join(self.qasm_path, "53QBT_100CYC_QSE_3.qasm") ) self.bntf = QuantumCircuit.from_qasm_file( os.path.join(self.qasm_path, "54QBT_25CYC_QSE_3.qasm") ) def track_depth_bntf_optimal_depth_25(self, optimization_level, routing_method): return transpile( self.bntf, coupling_map=self.sycamore_coupling_map, basis_gates=self.basis_gates, routing_method=routing_method, layout_method=routing_method, optimization_level=optimization_level, seed_transpiler=0, ).depth() def track_depth_bss_optimal_depth_100(self, optimization_level, routing_method): return transpile( self.bss, coupling_map=self.rochester_coupling_map, basis_gates=self.basis_gates, routing_method=routing_method, layout_method=routing_method, optimization_level=optimization_level, seed_transpiler=0, ).depth() def track_depth_bigd_optimal_depth_45(self, optimization_level, routing_method): return transpile( self.bigd, coupling_map=self.tokyo_coupling_map, basis_gates=self.basis_gates, routing_method=routing_method, layout_method=routing_method, optimization_level=optimization_level, seed_transpiler=0, ).depth() def time_transpile_bntf(self, optimization_level, routing_method): transpile( self.bntf, coupling_map=self.sycamore_coupling_map, basis_gates=self.basis_gates, routing_method=routing_method, layout_method=routing_method, optimization_level=optimization_level, seed_transpiler=0, ).depth() def time_transpile_bss(self, optimization_level, routing_method): transpile( self.bss, coupling_map=self.rochester_coupling_map, basis_gates=self.basis_gates, routing_method=routing_method, layout_method=routing_method, optimization_level=optimization_level, seed_transpiler=0, ).depth() def time_transpile_bigd(self, optimization_level, routing_method): transpile( self.bigd, coupling_map=self.tokyo_coupling_map, basis_gates=self.basis_gates, routing_method=routing_method, layout_method=routing_method, optimization_level=optimization_level, seed_transpiler=0, ).depth()
https://github.com/swe-train/qiskit__qiskit
swe-train
# 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. # pylint: disable=missing-docstring,invalid-name,no-member # pylint: disable=attribute-defined-outside-init import copy from qiskit.quantum_info.synthesis import OneQubitEulerDecomposer from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister try: from qiskit.compiler import transpile TRANSPILER_SEED_KEYWORD = "seed_transpiler" except ImportError: from qiskit.transpiler import transpile TRANSPILER_SEED_KEYWORD = "seed_mapper" try: from qiskit.quantum_info.random import random_unitary HAS_RANDOM_UNITARY = True except ImportError: from qiskit.tools.qi.qi import random_unitary_matrix HAS_RANDOM_UNITARY = False # Make a random circuit on a ring def make_circuit_ring(nq, depth, seed): assert int(nq / 2) == nq / 2 # for now size of ring must be even # Create a Quantum Register q = QuantumRegister(nq) # Create a Classical Register c = ClassicalRegister(nq) # Create a Quantum Circuit qc = QuantumCircuit(q, c) offset = 1 decomposer = OneQubitEulerDecomposer() # initial round of random single-qubit unitaries for i in range(nq): qc.h(q[i]) for j in range(depth): for i in range(int(nq / 2)): # round of CNOTS k = i * 2 + offset + j % 2 # j%2 makes alternating rounds overlap qc.cx(q[k % nq], q[(k + 1) % nq]) for i in range(nq): # round of single-qubit unitaries if HAS_RANDOM_UNITARY: u = random_unitary(2, seed).data else: u = random_unitary_matrix(2) # pylint: disable=used-before-assignment # noqa angles = decomposer.angles(u) qc.u3(angles[0], angles[1], angles[2], q[i]) # insert the final measurements qcm = copy.deepcopy(qc) for i in range(nq): qcm.measure(q[i], c[i]) return [qc, qcm, nq] class BenchRandomCircuitHex: params = [2 * i for i in range(2, 8)] param_names = ["n_qubits"] version = 3 def setup(self, n): depth = 2 * n self.seed = 0 self.circuit = make_circuit_ring(n, depth, self.seed)[0] def time_ibmq_backend_transpile(self, _): # Run with ibmq_16_melbourne configuration coupling_map = [ [1, 0], [1, 2], [2, 3], [4, 3], [4, 10], [5, 4], [5, 6], [5, 9], [6, 8], [7, 8], [9, 8], [9, 10], [11, 3], [11, 10], [11, 12], [12, 2], [13, 1], [13, 12], ] transpile( self.circuit, basis_gates=["u1", "u2", "u3", "cx", "id"], coupling_map=coupling_map, **{TRANSPILER_SEED_KEYWORD: self.seed}, ) def track_depth_ibmq_backend_transpile(self, _): # Run with ibmq_16_melbourne configuration coupling_map = [ [1, 0], [1, 2], [2, 3], [4, 3], [4, 10], [5, 4], [5, 6], [5, 9], [6, 8], [7, 8], [9, 8], [9, 10], [11, 3], [11, 10], [11, 12], [12, 2], [13, 1], [13, 12], ] return transpile( self.circuit, basis_gates=["u1", "u2", "u3", "cx", "id"], coupling_map=coupling_map, **{TRANSPILER_SEED_KEYWORD: self.seed}, ).depth()
https://github.com/swe-train/qiskit__qiskit
swe-train
# 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. # pylint: disable=no-member,invalid-name,missing-docstring,no-name-in-module # pylint: disable=attribute-defined-outside-init,unsubscriptable-object from qiskit import transpile from qiskit.transpiler import CouplingMap from .utils import build_ripple_adder_circuit class RippleAdderConstruction: params = ([10, 50, 100, 200, 500],) param_names = ["size"] version = 1 timeout = 600 def time_build_ripple_adder(self, size): build_ripple_adder_circuit(size) class RippleAdderTranspile: params = ([10, 20], [0, 1, 2, 3]) param_names = ["size", "level"] version = 1 timeout = 600 def setup(self, size, _): edge_len = int((2 * size + 2) ** 0.5) + 1 self.coupling_map = CouplingMap.from_grid(edge_len, edge_len) self.circuit = build_ripple_adder_circuit(size) def time_transpile_square_grid_ripple_adder(self, _, level): transpile( self.circuit, coupling_map=self.coupling_map, basis_gates=["u1", "u2", "u3", "cx", "id"], optimization_level=level, seed_transpiler=20220125, ) def track_depth_transpile_square_grid_ripple_adder(self, _, level): return transpile( self.circuit, coupling_map=self.coupling_map, basis_gates=["u1", "u2", "u3", "cx", "id"], optimization_level=level, seed_transpiler=20220125, ).depth()
https://github.com/swe-train/qiskit__qiskit
swe-train
# 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. # pylint: disable=invalid-name,missing-docstring # pylint: disable=attribute-defined-outside-init from qiskit import transpile from qiskit.circuit.library.standard_gates import XGate from qiskit.transpiler import CouplingMap from qiskit.transpiler import InstructionDurations from qiskit.transpiler.passes import ( TimeUnitConversion, ASAPSchedule, ALAPSchedule, DynamicalDecoupling, ) from qiskit.converters import circuit_to_dag from .utils import random_circuit class SchedulingPassBenchmarks: params = ([5, 10, 20], [500, 1000]) param_names = ["n_qubits", "depth"] timeout = 300 def setup(self, n_qubits, depth): seed = 42 self.circuit = random_circuit( n_qubits, depth, measure=True, conditional=True, reset=True, seed=seed, max_operands=2 ) self.basis_gates = ["rz", "sx", "x", "cx", "id", "reset"] self.cmap = [ [0, 1], [1, 0], [1, 2], [1, 6], [2, 1], [2, 3], [3, 2], [3, 4], [3, 8], [4, 3], [5, 6], [5, 10], [6, 1], [6, 5], [6, 7], [7, 6], [7, 8], [7, 12], [8, 3], [8, 7], [8, 9], [9, 8], [9, 14], [10, 5], [10, 11], [11, 10], [11, 12], [11, 16], [12, 7], [12, 11], [12, 13], [13, 12], [13, 14], [13, 18], [14, 9], [14, 13], [15, 16], [16, 11], [16, 15], [16, 17], [17, 16], [17, 18], [18, 13], [18, 17], [18, 19], [19, 18], ] self.coupling_map = CouplingMap(self.cmap) self.transpiled_circuit = transpile( self.circuit, basis_gates=self.basis_gates, coupling_map=self.coupling_map, optimization_level=1, ) self.dag = circuit_to_dag(self.transpiled_circuit) self.durations = InstructionDurations( [ ("rz", None, 0), ("id", None, 160), ("sx", None, 160), ("x", None, 160), ("cx", None, 800), ("measure", None, 3200), ("reset", None, 3600), ], dt=1e-9, ) self.timed_dag = TimeUnitConversion(self.durations).run(self.dag) _pass = ALAPSchedule(self.durations) _pass.property_set["time_unit"] = "dt" self.scheduled_dag = _pass.run(self.timed_dag) def time_time_unit_conversion_pass(self, _, __): TimeUnitConversion(self.durations).run(self.dag) def time_alap_schedule_pass(self, _, __): _pass = ALAPSchedule(self.durations) _pass.property_set["time_unit"] = "dt" _pass.run(self.timed_dag) def time_asap_schedule_pass(self, _, __): _pass = ASAPSchedule(self.durations) _pass.property_set["time_unit"] = "dt" _pass.run(self.timed_dag) def time_dynamical_decoupling_pass(self, _, __): DynamicalDecoupling(self.durations, dd_sequence=[XGate(), XGate()]).run(self.scheduled_dag)
https://github.com/swe-train/qiskit__qiskit
swe-train
# 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. # pylint: disable=missing-docstring,invalid-name,no-member # pylint: disable=attribute-defined-outside-init # pylint: disable=unused-argument import numpy as np from qiskit import QuantumRegister, QuantumCircuit from qiskit.compiler import transpile from qiskit.circuit.library.data_preparation import StatePreparation class StatePreparationTranspileBench: params = [4, 5, 6, 7, 8] param_names = ["number of qubits in state"] def setup(self, n): q = QuantumRegister(n) qc = QuantumCircuit(q) state = np.random.rand(2**n) + np.random.rand(2**n) * 1j state = state / np.linalg.norm(state) state_gate = StatePreparation(state) qc.append(state_gate, q) self.circuit = qc def track_cnot_counts_after_mapping_to_ibmq_16_melbourne(self, *unused): coupling = [ [1, 0], [1, 2], [2, 3], [4, 3], [4, 10], [5, 4], [5, 6], [5, 9], [6, 8], [7, 8], [9, 8], [9, 10], [11, 3], [11, 10], [11, 12], [12, 2], [13, 1], [13, 12], ] circuit = transpile( self.circuit, basis_gates=["u1", "u3", "u2", "cx"], coupling_map=coupling, seed_transpiler=0, ) counts = circuit.count_ops() cnot_count = counts.get("cx", 0) return cnot_count
https://github.com/swe-train/qiskit__qiskit
swe-train
# 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. # pylint: disable=missing-docstring,invalid-name,no-member # pylint: disable=attribute-defined-outside-init import os import qiskit class TranspilerBenchSuite: def _build_cx_circuit(self): cx_register = qiskit.QuantumRegister(2) cx_circuit = qiskit.QuantumCircuit(cx_register) cx_circuit.h(cx_register[0]) cx_circuit.h(cx_register[0]) cx_circuit.cx(cx_register[0], cx_register[1]) cx_circuit.cx(cx_register[0], cx_register[1]) cx_circuit.cx(cx_register[0], cx_register[1]) cx_circuit.cx(cx_register[0], cx_register[1]) return cx_circuit def _build_single_gate_circuit(self): single_register = qiskit.QuantumRegister(1) single_gate_circuit = qiskit.QuantumCircuit(single_register) single_gate_circuit.h(single_register[0]) return single_gate_circuit def setup(self): self.single_gate_circuit = self._build_single_gate_circuit() self.cx_circuit = self._build_cx_circuit() self.qasm_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "qasm")) large_qasm_path = os.path.join(self.qasm_path, "test_eoh_qasm.qasm") self.large_qasm = qiskit.QuantumCircuit.from_qasm_file(large_qasm_path) self.coupling_map = [ [0, 1], [1, 0], [1, 2], [1, 4], [2, 1], [2, 3], [3, 2], [3, 5], [4, 1], [4, 7], [5, 3], [5, 8], [6, 7], [7, 4], [7, 6], [7, 10], [8, 5], [8, 9], [8, 11], [9, 8], [10, 7], [10, 12], [11, 8], [11, 14], [12, 10], [12, 13], [12, 15], [13, 12], [13, 14], [14, 11], [14, 13], [14, 16], [15, 12], [15, 18], [16, 14], [16, 19], [17, 18], [18, 15], [18, 17], [18, 21], [19, 16], [19, 20], [19, 22], [20, 19], [21, 18], [21, 23], [22, 19], [22, 25], [23, 21], [23, 24], [24, 23], [24, 25], [25, 22], [25, 24], [25, 26], [26, 25], ] self.basis = ["id", "rz", "sx", "x", "cx", "reset"] def time_single_gate_compile(self): circ = qiskit.compiler.transpile( self.single_gate_circuit, coupling_map=self.coupling_map, basis_gates=self.basis, seed_transpiler=20220125, ) qiskit.compiler.assemble(circ) def time_cx_compile(self): circ = qiskit.compiler.transpile( self.cx_circuit, coupling_map=self.coupling_map, basis_gates=self.basis, seed_transpiler=20220125, ) qiskit.compiler.assemble(circ) def time_compile_from_large_qasm(self): circ = qiskit.compiler.transpile( self.large_qasm, coupling_map=self.coupling_map, basis_gates=self.basis, seed_transpiler=20220125, ) qiskit.compiler.assemble(circ)
https://github.com/swe-train/qiskit__qiskit
swe-train
# 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. # pylint: disable=no-member,invalid-name,missing-docstring,no-name-in-module # pylint: disable=attribute-defined-outside-init,unsubscriptable-object import os from qiskit.compiler import transpile from qiskit import QuantumCircuit from qiskit.transpiler import InstructionDurations from qiskit.providers.fake_provider import FakeMelbourne from .utils import build_qv_model_circuit class TranspilerLevelBenchmarks: params = [0, 1, 2, 3] param_names = ["transpiler optimization level"] timeout = 600 def setup(self, _): self.rochester_coupling_map = [ [0, 5], [0, 1], [1, 2], [1, 0], [2, 3], [2, 1], [3, 4], [3, 2], [4, 6], [4, 3], [5, 9], [5, 0], [6, 13], [6, 4], [7, 16], [7, 8], [8, 9], [8, 7], [9, 10], [9, 8], [9, 5], [10, 11], [10, 9], [11, 17], [11, 12], [11, 10], [12, 13], [12, 11], [13, 14], [13, 12], [13, 6], [14, 15], [14, 13], [15, 18], [15, 14], [16, 19], [16, 7], [17, 23], [17, 11], [18, 27], [18, 15], [19, 20], [19, 16], [20, 21], [20, 19], [21, 28], [21, 22], [21, 20], [22, 23], [22, 21], [23, 24], [23, 22], [23, 17], [24, 25], [24, 23], [25, 29], [25, 26], [25, 24], [26, 27], [26, 25], [27, 26], [27, 18], [28, 32], [28, 21], [29, 36], [29, 25], [30, 39], [30, 31], [31, 32], [31, 30], [32, 33], [32, 31], [32, 28], [33, 34], [33, 32], [34, 40], [34, 35], [34, 33], [35, 36], [35, 34], [36, 37], [36, 35], [36, 29], [37, 38], [37, 36], [38, 41], [38, 37], [39, 42], [39, 30], [40, 46], [40, 34], [41, 50], [41, 38], [42, 43], [42, 39], [43, 44], [43, 42], [44, 51], [44, 45], [44, 43], [45, 46], [45, 44], [46, 47], [46, 45], [46, 40], [47, 48], [47, 46], [48, 52], [48, 49], [48, 47], [49, 50], [49, 48], [50, 49], [50, 41], [51, 44], [52, 48], ] self.basis_gates = ["u1", "u2", "u3", "cx", "id"] self.qv_50_x_20 = build_qv_model_circuit(50, 20, 0) self.qv_14_x_14 = build_qv_model_circuit(14, 14, 0) self.qasm_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "qasm")) large_qasm_path = os.path.join(self.qasm_path, "test_eoh_qasm.qasm") self.large_qasm = QuantumCircuit.from_qasm_file(large_qasm_path) self.melbourne = FakeMelbourne() self.durations = InstructionDurations( [ ("u1", None, 0), ("id", None, 160), ("u2", None, 160), ("u3", None, 320), ("cx", None, 800), ("measure", None, 3200), ], dt=1e-9, ) def time_quantum_volume_transpile_50_x_20(self, transpiler_level): transpile( self.qv_50_x_20, basis_gates=self.basis_gates, coupling_map=self.rochester_coupling_map, seed_transpiler=0, optimization_level=transpiler_level, ) def track_depth_quantum_volume_transpile_50_x_20(self, transpiler_level): return transpile( self.qv_50_x_20, basis_gates=self.basis_gates, coupling_map=self.rochester_coupling_map, seed_transpiler=0, optimization_level=transpiler_level, ).depth() def time_transpile_from_large_qasm(self, transpiler_level): transpile( self.large_qasm, basis_gates=self.basis_gates, coupling_map=self.rochester_coupling_map, seed_transpiler=0, optimization_level=transpiler_level, ) def track_depth_transpile_from_large_qasm(self, transpiler_level): return transpile( self.large_qasm, basis_gates=self.basis_gates, coupling_map=self.rochester_coupling_map, seed_transpiler=0, optimization_level=transpiler_level, ).depth() def time_transpile_from_large_qasm_backend_with_prop(self, transpiler_level): transpile( self.large_qasm, self.melbourne, seed_transpiler=0, optimization_level=transpiler_level ) def track_depth_transpile_from_large_qasm_backend_with_prop(self, transpiler_level): return transpile( self.large_qasm, self.melbourne, seed_transpiler=0, optimization_level=transpiler_level ).depth() def time_transpile_qv_14_x_14(self, transpiler_level): transpile( self.qv_14_x_14, self.melbourne, seed_transpiler=0, optimization_level=transpiler_level ) def track_depth_transpile_qv_14_x_14(self, transpiler_level): return transpile( self.qv_14_x_14, self.melbourne, seed_transpiler=0, optimization_level=transpiler_level ).depth() def time_schedule_qv_14_x_14(self, transpiler_level): transpile( self.qv_14_x_14, self.melbourne, seed_transpiler=0, optimization_level=transpiler_level, scheduling_method="alap", instruction_durations=self.durations, ) # limit optimization levels to reduce time time_schedule_qv_14_x_14.params = [0, 1]
https://github.com/swe-train/qiskit__qiskit
swe-train
# 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. # pylint: disable=no-member,invalid-name,missing-docstring,no-name-in-module # pylint: disable=attribute-defined-outside-init,unsubscriptable-object import os from qiskit import QuantumCircuit from qiskit.compiler import transpile from qiskit.test.mock import FakeToronto class TranspilerQualitativeBench: params = ([0, 1, 2, 3], ["stochastic", "sabre"], ["dense", "noise_adaptive", "sabre"]) param_names = ["optimization level", "routing method", "layout method"] timeout = 600 # pylint: disable=unused-argument def setup(self, optimization_level, routing_method, layout_method): self.backend = FakeToronto() self.qasm_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "qasm")) self.depth_4gt10_v1_81 = QuantumCircuit.from_qasm_file( os.path.join(self.qasm_path, "depth_4gt10-v1_81.qasm") ) self.depth_4mod5_v0_19 = QuantumCircuit.from_qasm_file( os.path.join(self.qasm_path, "depth_4mod5-v0_19.qasm") ) self.depth_mod8_10_178 = QuantumCircuit.from_qasm_file( os.path.join(self.qasm_path, "depth_mod8-10_178.qasm") ) self.time_cnt3_5_179 = QuantumCircuit.from_qasm_file( os.path.join(self.qasm_path, "time_cnt3-5_179.qasm") ) self.time_cnt3_5_180 = QuantumCircuit.from_qasm_file( os.path.join(self.qasm_path, "time_cnt3-5_180.qasm") ) self.time_qft_16 = QuantumCircuit.from_qasm_file( os.path.join(self.qasm_path, "time_qft_16.qasm") ) def track_depth_transpile_4gt10_v1_81(self, optimization_level, routing_method, layout_method): return transpile( self.depth_4gt10_v1_81, self.backend, routing_method=routing_method, layout_method=layout_method, optimization_level=optimization_level, seed_transpiler=0, ).depth() def track_depth_transpile_4mod5_v0_19(self, optimization_level, routing_method, layout_method): return transpile( self.depth_4mod5_v0_19, self.backend, routing_method=routing_method, layout_method=layout_method, optimization_level=optimization_level, seed_transpiler=0, ).depth() def track_depth_transpile_mod8_10_178(self, optimization_level, routing_method, layout_method): return transpile( self.depth_mod8_10_178, self.backend, routing_method=routing_method, layout_method=layout_method, optimization_level=optimization_level, seed_transpiler=0, ).depth() def time_transpile_time_cnt3_5_179(self, optimization_level, routing_method, layout_method): transpile( self.time_cnt3_5_179, self.backend, routing_method=routing_method, layout_method=layout_method, optimization_level=optimization_level, seed_transpiler=0, ) def time_transpile_time_cnt3_5_180(self, optimization_level, routing_method, layout_method): transpile( self.time_cnt3_5_180, self.backend, routing_method=routing_method, layout_method=layout_method, optimization_level=optimization_level, seed_transpiler=0, ) def time_transpile_time_qft_16(self, optimization_level, routing_method, layout_method): transpile( self.time_qft_16, self.backend, routing_method=routing_method, layout_method=layout_method, optimization_level=optimization_level, seed_transpiler=0, )
https://github.com/swe-train/qiskit__qiskit
swe-train
# 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. # pylint: disable=no-member,invalid-name,missing-docstring,no-name-in-module # pylint: disable=attribute-defined-outside-init,unsubscriptable-object import os from qiskit import QuantumCircuit from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager from qiskit.providers.fake_provider import GenericBackendV2 from qiskit.transpiler import CouplingMap from qiskit import qasm2 class UtilityScaleBenchmarks: params = ["cx", "cz", "ecr"] param_names = ["2q gate"] def setup(self, basis_gate): cmap = CouplingMap.from_heavy_hex(9) basis_gates = ["rz", "x", "sx", basis_gate, "id"] backend = GenericBackendV2( cmap.size(), basis_gates, coupling_map=cmap, control_flow=True, seed=12345678942 ) self.pm = generate_preset_pass_manager(2, backend, seed_transpiler=1234567845) qasm_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "qasm") self.qft_qasm = os.path.join(qasm_dir, "qft_N100.qasm") self.qft_qc = QuantumCircuit.from_qasm_file(self.qft_qasm) self.square_heisenberg_qasm = os.path.join(qasm_dir, "square_heisenberg_N100.qasm") self.square_heisenberg_qc = QuantumCircuit.from_qasm_file(self.square_heisenberg_qasm) self.qaoa_qasm = os.path.join(qasm_dir, "qaoa_barabasi_albert_N100_3reps.qasm") self.qaoa_qc = QuantumCircuit.from_qasm_file(self.qaoa_qasm) def time_parse_qft_n100(self, _): qasm2.load( self.qft_qasm, include_path=qasm2.LEGACY_INCLUDE_PATH, custom_instructions=qasm2.LEGACY_CUSTOM_INSTRUCTIONS, custom_classical=qasm2.LEGACY_CUSTOM_CLASSICAL, strict=False, ) def time_parse_square_heisenberg_n100(self, _): qasm2.load( self.square_heisenberg_qasm, include_path=qasm2.LEGACY_INCLUDE_PATH, custom_instructions=qasm2.LEGACY_CUSTOM_INSTRUCTIONS, custom_classical=qasm2.LEGACY_CUSTOM_CLASSICAL, strict=False, ) def time_parse_qaoa_n100(self, _): qasm2.load( self.qaoa_qasm, include_path=qasm2.LEGACY_INCLUDE_PATH, custom_instructions=qasm2.LEGACY_CUSTOM_INSTRUCTIONS, custom_classical=qasm2.LEGACY_CUSTOM_CLASSICAL, strict=False, ) def time_qft(self, _): self.pm.run(self.qft_qc) def track_qft_depth(self, basis_gate): res = self.pm.run(self.qft_qc) return res.depth(filter_function=lambda x: x.operation.name == basis_gate) def time_square_heisenberg(self, _): self.pm.run(self.square_heisenberg_qc) def track_square_heisenberg_depth(self, basis_gate): res = self.pm.run(self.square_heisenberg_qc) return res.depth(filter_function=lambda x: x.operation.name == basis_gate) def time_qaoa(self, _): self.pm.run(self.qaoa_qc) def track_qaoa_depth(self, basis_gate): res = self.pm.run(self.qaoa_qc) return res.depth(filter_function=lambda x: x.operation.name == basis_gate)
https://github.com/swe-train/qiskit__qiskit
swe-train
# 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. # pylint: disable=missing-docstring import os import configparser as cp from uuid import uuid4 from unittest import mock from qiskit import exceptions from qiskit.test import QiskitTestCase from qiskit import user_config class TestUserConfig(QiskitTestCase): def setUp(self): super().setUp() self.file_path = "test_%s.conf" % uuid4() def test_empty_file_read(self): config = user_config.UserConfig(self.file_path) config.read_config_file() self.assertEqual({}, config.settings) def test_invalid_optimization_level(self): test_config = """ [default] transpile_optimization_level = 76 """ self.addCleanup(os.remove, self.file_path) with open(self.file_path, "w") as file: file.write(test_config) file.flush() config = user_config.UserConfig(self.file_path) self.assertRaises(exceptions.QiskitUserConfigError, config.read_config_file) def test_invalid_circuit_drawer(self): test_config = """ [default] circuit_drawer = MSPaint """ self.addCleanup(os.remove, self.file_path) with open(self.file_path, "w") as file: file.write(test_config) file.flush() config = user_config.UserConfig(self.file_path) self.assertRaises(exceptions.QiskitUserConfigError, config.read_config_file) def test_circuit_drawer_valid(self): test_config = """ [default] circuit_drawer = latex """ self.addCleanup(os.remove, self.file_path) with open(self.file_path, "w") as file: file.write(test_config) file.flush() config = user_config.UserConfig(self.file_path) config.read_config_file() self.assertEqual({"circuit_drawer": "latex"}, config.settings) def test_invalid_circuit_reverse_bits(self): test_config = """ [default] circuit_reverse_bits = Neither """ self.addCleanup(os.remove, self.file_path) with open(self.file_path, "w") as file: file.write(test_config) file.flush() config = user_config.UserConfig(self.file_path) self.assertRaises(exceptions.QiskitUserConfigError, config.read_config_file) def test_circuit_reverse_bits_valid(self): test_config = """ [default] circuit_reverse_bits = false """ self.addCleanup(os.remove, self.file_path) with open(self.file_path, "w") as file: file.write(test_config) file.flush() config = user_config.UserConfig(self.file_path) config.read_config_file() self.assertEqual({"circuit_reverse_bits": False}, config.settings) def test_optimization_level_valid(self): test_config = """ [default] transpile_optimization_level = 1 """ self.addCleanup(os.remove, self.file_path) with open(self.file_path, "w") as file: file.write(test_config) file.flush() config = user_config.UserConfig(self.file_path) config.read_config_file() self.assertEqual({"transpile_optimization_level": 1}, config.settings) def test_invalid_num_processes(self): test_config = """ [default] num_processes = -256 """ self.addCleanup(os.remove, self.file_path) with open(self.file_path, "w") as file: file.write(test_config) file.flush() config = user_config.UserConfig(self.file_path) self.assertRaises(exceptions.QiskitUserConfigError, config.read_config_file) def test_valid_num_processes(self): test_config = """ [default] num_processes = 31 """ self.addCleanup(os.remove, self.file_path) with open(self.file_path, "w") as file: file.write(test_config) file.flush() config = user_config.UserConfig(self.file_path) config.read_config_file() self.assertEqual({"num_processes": 31}, config.settings) def test_valid_parallel(self): test_config = """ [default] parallel = False """ self.addCleanup(os.remove, self.file_path) with open(self.file_path, "w") as file: file.write(test_config) file.flush() config = user_config.UserConfig(self.file_path) config.read_config_file() self.assertEqual({"parallel_enabled": False}, config.settings) def test_all_options_valid(self): test_config = """ [default] circuit_drawer = latex circuit_mpl_style = default circuit_mpl_style_path = ~:~/.qiskit circuit_reverse_bits = false transpile_optimization_level = 3 suppress_packaging_warnings = true parallel = false num_processes = 15 """ self.addCleanup(os.remove, self.file_path) with open(self.file_path, "w") as file: file.write(test_config) file.flush() config = user_config.UserConfig(self.file_path) config.read_config_file() self.assertEqual( { "circuit_drawer": "latex", "circuit_mpl_style": "default", "circuit_mpl_style_path": ["~", "~/.qiskit"], "circuit_reverse_bits": False, "transpile_optimization_level": 3, "num_processes": 15, "parallel_enabled": False, }, config.settings, ) def test_set_config_all_options_valid(self): self.addCleanup(os.remove, self.file_path) user_config.set_config("circuit_drawer", "latex", file_path=self.file_path) user_config.set_config("circuit_mpl_style", "default", file_path=self.file_path) user_config.set_config("circuit_mpl_style_path", "~:~/.qiskit", file_path=self.file_path) user_config.set_config("circuit_reverse_bits", "false", file_path=self.file_path) user_config.set_config("transpile_optimization_level", "3", file_path=self.file_path) user_config.set_config("parallel", "false", file_path=self.file_path) user_config.set_config("num_processes", "15", file_path=self.file_path) config_settings = None with mock.patch.dict(os.environ, {"QISKIT_SETTINGS": self.file_path}, clear=True): config_settings = user_config.get_config() self.assertEqual( { "circuit_drawer": "latex", "circuit_mpl_style": "default", "circuit_mpl_style_path": ["~", "~/.qiskit"], "circuit_reverse_bits": False, "transpile_optimization_level": 3, "num_processes": 15, "parallel_enabled": False, }, config_settings, ) def test_set_config_multiple_sections(self): self.addCleanup(os.remove, self.file_path) user_config.set_config("circuit_drawer", "latex", file_path=self.file_path) user_config.set_config("circuit_mpl_style", "default", file_path=self.file_path) user_config.set_config("transpile_optimization_level", "3", file_path=self.file_path) user_config.set_config("circuit_drawer", "latex", section="test", file_path=self.file_path) user_config.set_config("parallel", "false", section="test", file_path=self.file_path) user_config.set_config("num_processes", "15", section="test", file_path=self.file_path) config = cp.ConfigParser() config.read(self.file_path) self.assertEqual(config.sections(), ["default", "test"]) self.assertEqual( { "circuit_drawer": "latex", "circuit_mpl_style": "default", "transpile_optimization_level": "3", }, dict(config.items("default")), )
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test QuantumCircuit.find_bit.""" from ddt import ddt, data, unpack from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.circuit import Qubit, Clbit, AncillaRegister from qiskit.circuit.exceptions import CircuitError from qiskit.test import QiskitTestCase @ddt class TestQuantumCircuitFindBit(QiskitTestCase): """Test cases for QuantumCircuit.find_bit.""" @data(Qubit, Clbit) def test_bit_not_in_circuit(self, bit_type): """Verify we raise if the bit has not been attached to the circuit.""" qc = QuantumCircuit() bit = bit_type() with self.assertRaisesRegex(CircuitError, r"Could not locate provided bit"): qc.find_bit(bit) @data(Qubit, Clbit) def test_registerless_bit_constructor(self, bit_type): """Verify we find individual bits added via QuantumCircuit constructor.""" bits = [bit_type() for _ in range(5)] qc = QuantumCircuit(bits) for idx, bit in enumerate(bits): self.assertEqual(qc.find_bit(bit), (idx, [])) @data(Qubit, Clbit) def test_registerless_add_bits(self, bit_type): """Verify we find individual bits added via QuantumCircuit.add_bits.""" bits = [bit_type() for _ in range(5)] qc = QuantumCircuit() qc.add_bits(bits) for idx, bit in enumerate(bits): self.assertEqual(qc.find_bit(bit), (idx, [])) def test_registerless_add_int(self): """Verify we find bits and implicit registers added via QuantumCircuit(int, int).""" qc = QuantumCircuit(5, 2) qubits = qc.qubits clbits = qc.clbits # N.B. After deprecation of implicit register creation via # QuantumCircuit(int, int) in PR#6582 and subsequent removal, this test # should be updated to verify no registers are found. qr = qc.qregs[0] cr = qc.cregs[0] for idx, bit in enumerate(qubits): self.assertEqual(qc.find_bit(bit), (idx, [(qr, idx)])) for idx, bit in enumerate(clbits): self.assertEqual(qc.find_bit(bit), (idx, [(cr, idx)])) @data(QuantumRegister, ClassicalRegister) def test_register_bit_reg_constructor(self, reg_type): """Verify we find register bits added via QuantumCicrcuit(reg).""" reg = reg_type(5, "reg") qc = QuantumCircuit(reg) for idx, bit in enumerate(reg): self.assertEqual(qc.find_bit(bit), (idx, [(reg, idx)])) @data(QuantumRegister, ClassicalRegister) def test_register_bit_add_reg(self, reg_type): """Verify we find register bits added QuantumCircuit.add_register.""" reg = reg_type(5, "reg") qc = QuantumCircuit() qc.add_register(reg) for idx, bit in enumerate(reg): self.assertEqual(qc.find_bit(bit), (idx, [(reg, idx)])) def test_ancilla_register_add_register(self): """Verify AncillaRegisters are found by find_bit by their locations in qubits/qregs.""" qreg = QuantumRegister(3, "qr") areg = AncillaRegister(5, "ar") qc = QuantumCircuit() qc.add_register(qreg) qc.add_register(areg) for idx, bit in enumerate(areg): self.assertEqual(qc.find_bit(bit), (idx + len(qreg), [(areg, idx)])) @data([Qubit, QuantumRegister], [Clbit, ClassicalRegister]) @unpack def test_multiple_register_from_bit(self, bit_type, reg_type): """Verify we find individual bits in multiple registers.""" bits = [bit_type() for _ in range(10)] even_reg = reg_type(bits=bits[::2]) odd_reg = reg_type(bits=bits[1::2]) fwd_reg = reg_type(bits=bits) rev_reg = reg_type(bits=bits[::-1]) qc = QuantumCircuit() qc.add_bits(bits) qc.add_register(even_reg, odd_reg, fwd_reg, rev_reg) for idx, bit in enumerate(bits): if idx % 2: self.assertEqual( qc.find_bit(bit), (idx, [(odd_reg, idx // 2), (fwd_reg, idx), (rev_reg, 9 - idx)]), ) else: self.assertEqual( qc.find_bit(bit), (idx, [(even_reg, idx // 2), (fwd_reg, idx), (rev_reg, 9 - idx)]), ) @data(QuantumRegister, ClassicalRegister) def test_multiple_register_from_reg(self, reg_type): """Verify we find register bits in multiple registers.""" reg1 = reg_type(6, "reg1") reg2 = reg_type(4, "reg2") even_reg = reg_type(bits=(reg1[:] + reg2[:])[::2]) odd_reg = reg_type(bits=(reg1[:] + reg2[:])[1::2]) qc = QuantumCircuit(reg1, reg2, even_reg, odd_reg) for idx, bit in enumerate(reg1): if idx % 2: self.assertEqual(qc.find_bit(bit), (idx, [(reg1, idx), (odd_reg, idx // 2)])) else: self.assertEqual(qc.find_bit(bit), (idx, [(reg1, idx), (even_reg, idx // 2)])) for idx, bit in enumerate(reg2): circ_idx = len(reg1) + idx if idx % 2: self.assertEqual( qc.find_bit(bit), (circ_idx, [(reg2, idx), (odd_reg, circ_idx // 2)]) ) else: self.assertEqual( qc.find_bit(bit), (circ_idx, [(reg2, idx), (even_reg, circ_idx // 2)]) )
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2020, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test cases for the circuit qasm_file and qasm_string method.""" import io import json import random import ddt import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, pulse from qiskit.circuit import CASE_DEFAULT from qiskit.circuit.classical import expr, types from qiskit.circuit.classicalregister import Clbit from qiskit.circuit.quantumregister import Qubit from qiskit.circuit.random import random_circuit from qiskit.circuit.gate import Gate from qiskit.circuit.library import ( XGate, QFT, QAOAAnsatz, PauliEvolutionGate, DCXGate, MCU1Gate, MCXGate, MCXGrayCode, MCXRecursive, MCXVChain, ) from qiskit.circuit.instruction import Instruction from qiskit.circuit.parameter import Parameter from qiskit.circuit.parametervector import ParameterVector from qiskit.synthesis import LieTrotter, SuzukiTrotter from qiskit.extensions import UnitaryGate from qiskit.test import QiskitTestCase from qiskit.qpy import dump, load from qiskit.quantum_info import Pauli, SparsePauliOp from qiskit.quantum_info.random import random_unitary from qiskit.circuit.controlledgate import ControlledGate @ddt.ddt class TestLoadFromQPY(QiskitTestCase): """Test circuit.from_qasm_* set of methods.""" def assertDeprecatedBitProperties(self, original, roundtripped): """Test that deprecated bit attributes are equal if they are set in the original circuit.""" owned_qubits = [ (a, b) for a, b in zip(original.qubits, roundtripped.qubits) if a._register is not None ] if owned_qubits: original_qubits, roundtripped_qubits = zip(*owned_qubits) self.assertEqual(original_qubits, roundtripped_qubits) owned_clbits = [ (a, b) for a, b in zip(original.clbits, roundtripped.clbits) if a._register is not None ] if owned_clbits: original_clbits, roundtripped_clbits = zip(*owned_clbits) self.assertEqual(original_clbits, roundtripped_clbits) def test_qpy_full_path(self): """Test full path qpy serialization for basic circuit.""" qr_a = QuantumRegister(4, "a") qr_b = QuantumRegister(4, "b") cr_c = ClassicalRegister(4, "c") cr_d = ClassicalRegister(4, "d") q_circuit = QuantumCircuit( qr_a, qr_b, cr_c, cr_d, name="MyCircuit", metadata={"test": 1, "a": 2}, global_phase=3.14159, ) q_circuit.h(qr_a) q_circuit.cx(qr_a, qr_b) q_circuit.barrier(qr_a) q_circuit.barrier(qr_b) q_circuit.measure(qr_a, cr_c) q_circuit.measure(qr_b, cr_d) qpy_file = io.BytesIO() dump(q_circuit, qpy_file) qpy_file.seek(0) new_circ = load(qpy_file)[0] self.assertEqual(q_circuit, new_circ) self.assertEqual(q_circuit.global_phase, new_circ.global_phase) self.assertEqual(q_circuit.metadata, new_circ.metadata) self.assertEqual(q_circuit.name, new_circ.name) self.assertDeprecatedBitProperties(q_circuit, new_circ) def test_circuit_with_conditional(self): """Test that instructions with conditions are correctly serialized.""" qc = QuantumCircuit(1, 1) qc.x(0).c_if(qc.cregs[0], 1) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circ = load(qpy_file)[0] self.assertEqual(qc, new_circ) self.assertDeprecatedBitProperties(qc, new_circ) def test_int_parameter(self): """Test that integer parameters are correctly serialized.""" qc = QuantumCircuit(1) qc.rx(3, 0) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circ = load(qpy_file)[0] self.assertEqual(qc, new_circ) self.assertDeprecatedBitProperties(qc, new_circ) def test_float_parameter(self): """Test that float parameters are correctly serialized.""" qc = QuantumCircuit(1) qc.rx(3.14, 0) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circ = load(qpy_file)[0] self.assertEqual(qc, new_circ) self.assertDeprecatedBitProperties(qc, new_circ) def test_numpy_float_parameter(self): """Test that numpy float parameters are correctly serialized.""" qc = QuantumCircuit(1) qc.rx(np.float32(3.14), 0) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circ = load(qpy_file)[0] self.assertEqual(qc, new_circ) self.assertDeprecatedBitProperties(qc, new_circ) def test_numpy_int_parameter(self): """Test that numpy integer parameters are correctly serialized.""" qc = QuantumCircuit(1) qc.rx(np.int16(3), 0) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circ = load(qpy_file)[0] self.assertEqual(qc, new_circ) self.assertDeprecatedBitProperties(qc, new_circ) def test_unitary_gate(self): """Test that numpy array parameters are correctly serialized""" qc = QuantumCircuit(1) unitary = np.array([[0, 1], [1, 0]]) qc.unitary(unitary, 0) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circ = load(qpy_file)[0] self.assertEqual(qc, new_circ) self.assertDeprecatedBitProperties(qc, new_circ) def test_opaque_gate(self): """Test that custom opaque gate is correctly serialized""" custom_gate = Gate("black_box", 1, []) qc = QuantumCircuit(1) qc.append(custom_gate, [0]) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circ = load(qpy_file)[0] self.assertEqual(qc, new_circ) self.assertDeprecatedBitProperties(qc, new_circ) def test_opaque_instruction(self): """Test that custom opaque instruction is correctly serialized""" custom_gate = Instruction("black_box", 1, 0, []) qc = QuantumCircuit(1) qc.append(custom_gate, [0]) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circ = load(qpy_file)[0] self.assertEqual(qc, new_circ) self.assertDeprecatedBitProperties(qc, new_circ) def test_custom_gate(self): """Test that custom gate is correctly serialized""" custom_gate = Gate("black_box", 1, []) custom_definition = QuantumCircuit(1) custom_definition.h(0) custom_definition.rz(1.5, 0) custom_definition.sdg(0) custom_gate.definition = custom_definition qc = QuantumCircuit(1) qc.append(custom_gate, [0]) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circ = load(qpy_file)[0] self.assertEqual(qc, new_circ) self.assertEqual(qc.decompose(), new_circ.decompose()) self.assertDeprecatedBitProperties(qc, new_circ) def test_custom_instruction(self): """Test that custom instruction is correctly serialized""" custom_gate = Instruction("black_box", 1, 0, []) custom_definition = QuantumCircuit(1) custom_definition.h(0) custom_definition.rz(1.5, 0) custom_definition.sdg(0) custom_gate.definition = custom_definition qc = QuantumCircuit(1) qc.append(custom_gate, [0]) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circ = load(qpy_file)[0] self.assertEqual(qc, new_circ) self.assertEqual(qc.decompose(), new_circ.decompose()) self.assertDeprecatedBitProperties(qc, new_circ) def test_parameter(self): """Test that a circuit with a parameter is correctly serialized.""" theta = Parameter("theta") qc = QuantumCircuit(5, 1) qc.h(0) for i in range(4): qc.cx(i, i + 1) qc.barrier() qc.rz(theta, range(5)) qc.barrier() for i in reversed(range(4)): qc.cx(i, i + 1) qc.h(0) qc.measure(0, 0) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circ = load(qpy_file)[0] self.assertEqual(qc, new_circ) self.assertEqual(qc.bind_parameters({theta: 3.14}), new_circ.bind_parameters({theta: 3.14})) self.assertDeprecatedBitProperties(qc, new_circ) def test_bound_parameter(self): """Test a circuit with a bound parameter is correctly serialized.""" theta = Parameter("theta") qc = QuantumCircuit(5, 1) qc.h(0) for i in range(4): qc.cx(i, i + 1) qc.barrier() qc.rz(theta, range(5)) qc.barrier() for i in reversed(range(4)): qc.cx(i, i + 1) qc.h(0) qc.measure(0, 0) qc.assign_parameters({theta: 3.14}) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circ = load(qpy_file)[0] self.assertEqual(qc, new_circ) self.assertDeprecatedBitProperties(qc, new_circ) def test_bound_calibration_parameter(self): """Test a circuit with a bound calibration parameter is correctly serialized. In particular, this test ensures that parameters on a circuit instruction are consistent with the circuit's calibrations dictionary after serialization. """ amp = Parameter("amp") with pulse.builder.build() as sched: pulse.builder.play(pulse.Constant(100, amp), pulse.DriveChannel(0)) gate = Gate("custom", 1, [amp]) qc = QuantumCircuit(1) qc.append(gate, (0,)) qc.add_calibration(gate, (0,), sched) qc.assign_parameters({amp: 1 / 3}, inplace=True) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circ = load(qpy_file)[0] self.assertEqual(qc, new_circ) instruction = new_circ.data[0] cal_key = ( tuple(new_circ.find_bit(q).index for q in instruction.qubits), tuple(instruction.operation.params), ) # Make sure that looking for a calibration based on the instruction's # parameters succeeds self.assertIn(cal_key, new_circ.calibrations[gate.name]) def test_parameter_expression(self): """Test a circuit with a parameter expression.""" theta = Parameter("theta") phi = Parameter("phi") sum_param = theta + phi qc = QuantumCircuit(5, 1) qc.h(0) for i in range(4): qc.cx(i, i + 1) qc.barrier() qc.rz(sum_param, range(3)) qc.rz(phi, 3) qc.rz(theta, 4) qc.barrier() for i in reversed(range(4)): qc.cx(i, i + 1) qc.h(0) qc.measure(0, 0) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circuit = load(qpy_file)[0] self.assertEqual(qc, new_circuit) self.assertDeprecatedBitProperties(qc, new_circuit) def test_string_parameter(self): """Test a PauliGate instruction that has string parameters.""" circ = QuantumCircuit(3) circ.z(0) circ.y(1) circ.x(2) qpy_file = io.BytesIO() dump(circ, qpy_file) qpy_file.seek(0) new_circuit = load(qpy_file)[0] self.assertEqual(circ, new_circuit) self.assertDeprecatedBitProperties(circ, new_circuit) def test_multiple_circuits(self): """Test multiple circuits can be serialized together.""" circuits = [] for i in range(10): circuits.append( random_circuit(10, 10, measure=True, conditional=True, reset=True, seed=42 + i) ) qpy_file = io.BytesIO() dump(circuits, qpy_file) qpy_file.seek(0) new_circs = load(qpy_file) self.assertEqual(circuits, new_circs) for old, new in zip(circuits, new_circs): self.assertDeprecatedBitProperties(old, new) def test_shared_bit_register(self): """Test a circuit with shared bit registers.""" qubits = [Qubit() for _ in range(5)] qc = QuantumCircuit() qc.add_bits(qubits) qr = QuantumRegister(bits=qubits) qc.add_register(qr) qc.h(qr) qc.cx(0, 1) qc.cx(0, 2) qc.cx(0, 3) qc.cx(0, 4) qc.measure_all() qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_qc = load(qpy_file)[0] self.assertEqual(qc, new_qc) self.assertDeprecatedBitProperties(qc, new_qc) def test_hybrid_standalone_register(self): """Test qpy serialization with registers that mix bit types""" qr = QuantumRegister(5, "foo") qr = QuantumRegister(name="bar", bits=qr[:3] + [Qubit(), Qubit()]) cr = ClassicalRegister(5, "foo") cr = ClassicalRegister(name="classical_bar", bits=cr[:3] + [Clbit(), Clbit()]) qc = QuantumCircuit(qr, cr) qc.h(0) qc.cx(0, 1) qc.cx(0, 2) qc.cx(0, 3) qc.cx(0, 4) qc.measure(qr, cr) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circ = load(qpy_file)[0] self.assertEqual(qc, new_circ) self.assertDeprecatedBitProperties(qc, new_circ) def test_mixed_registers(self): """Test circuit with mix of standalone and shared registers.""" qubits = [Qubit() for _ in range(5)] clbits = [Clbit() for _ in range(5)] qc = QuantumCircuit() qc.add_bits(qubits) qc.add_bits(clbits) qr = QuantumRegister(bits=qubits) cr = ClassicalRegister(bits=clbits) qc.add_register(qr) qc.add_register(cr) qr_standalone = QuantumRegister(2, "standalone") qc.add_register(qr_standalone) cr_standalone = ClassicalRegister(2, "classical_standalone") qc.add_register(cr_standalone) qc.unitary(random_unitary(32, seed=42), qr) qc.unitary(random_unitary(4, seed=100), qr_standalone) qc.measure(qr, cr) qc.measure(qr_standalone, cr_standalone) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circ = load(qpy_file)[0] self.assertEqual(qc, new_circ) self.assertDeprecatedBitProperties(qc, new_circ) def test_standalone_and_shared_out_of_order(self): """Test circuit with register bits inserted out of order.""" qr_standalone = QuantumRegister(2, "standalone") qubits = [Qubit() for _ in range(5)] clbits = [Clbit() for _ in range(5)] qc = QuantumCircuit() qc.add_bits(qubits) qc.add_bits(clbits) random.shuffle(qubits) random.shuffle(clbits) qr = QuantumRegister(bits=qubits) cr = ClassicalRegister(bits=clbits) qc.add_register(qr) qc.add_register(cr) qr_standalone = QuantumRegister(2, "standalone") cr_standalone = ClassicalRegister(2, "classical_standalone") qc.add_bits([qr_standalone[1], qr_standalone[0]]) qc.add_bits([cr_standalone[1], cr_standalone[0]]) qc.add_register(qr_standalone) qc.add_register(cr_standalone) qc.unitary(random_unitary(32, seed=42), qr) qc.unitary(random_unitary(4, seed=100), qr_standalone) qc.measure(qr, cr) qc.measure(qr_standalone, cr_standalone) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circ = load(qpy_file)[0] self.assertEqual(qc, new_circ) self.assertDeprecatedBitProperties(qc, new_circ) def test_unitary_gate_with_label(self): """Test that numpy array parameters are correctly serialized with a label""" qc = QuantumCircuit(1) unitary = np.array([[0, 1], [1, 0]]) unitary_gate = UnitaryGate(unitary, "My Special unitary") qc.append(unitary_gate, [0]) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circ = load(qpy_file)[0] self.assertEqual(qc, new_circ) self.assertEqual( [x.operation.label for x in qc.data], [x.operation.label for x in new_circ.data] ) self.assertDeprecatedBitProperties(qc, new_circ) def test_opaque_gate_with_label(self): """Test that custom opaque gate is correctly serialized with a label""" custom_gate = Gate("black_box", 1, []) custom_gate.label = "My Special Black Box" qc = QuantumCircuit(1) qc.append(custom_gate, [0]) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circ = load(qpy_file)[0] self.assertEqual(qc, new_circ) self.assertEqual( [x.operation.label for x in qc.data], [x.operation.label for x in new_circ.data] ) self.assertDeprecatedBitProperties(qc, new_circ) def test_opaque_instruction_with_label(self): """Test that custom opaque instruction is correctly serialized with a label""" custom_gate = Instruction("black_box", 1, 0, []) custom_gate.label = "My Special Black Box Instruction" qc = QuantumCircuit(1) qc.append(custom_gate, [0]) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circ = load(qpy_file)[0] self.assertEqual(qc, new_circ) self.assertEqual( [x.operation.label for x in qc.data], [x.operation.label for x in new_circ.data] ) self.assertDeprecatedBitProperties(qc, new_circ) def test_custom_gate_with_label(self): """Test that custom gate is correctly serialized with a label""" custom_gate = Gate("black_box", 1, []) custom_definition = QuantumCircuit(1) custom_definition.h(0) custom_definition.rz(1.5, 0) custom_definition.sdg(0) custom_gate.definition = custom_definition custom_gate.label = "My special black box with a definition" qc = QuantumCircuit(1) qc.append(custom_gate, [0]) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circ = load(qpy_file)[0] self.assertEqual(qc, new_circ) self.assertEqual(qc.decompose(), new_circ.decompose()) self.assertEqual( [x.operation.label for x in qc.data], [x.operation.label for x in new_circ.data] ) self.assertDeprecatedBitProperties(qc, new_circ) def test_custom_instruction_with_label(self): """Test that custom instruction is correctly serialized with a label""" custom_gate = Instruction("black_box", 1, 0, []) custom_definition = QuantumCircuit(1) custom_definition.h(0) custom_definition.rz(1.5, 0) custom_definition.sdg(0) custom_gate.definition = custom_definition custom_gate.label = "My Special Black Box Instruction with a definition" qc = QuantumCircuit(1) qc.append(custom_gate, [0]) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circ = load(qpy_file)[0] self.assertEqual(qc, new_circ) self.assertEqual(qc.decompose(), new_circ.decompose()) self.assertEqual( [x.operation.label for x in qc.data], [x.operation.label for x in new_circ.data] ) self.assertDeprecatedBitProperties(qc, new_circ) def test_custom_gate_with_noop_definition(self): """Test that a custom gate whose definition contains no elements is serialized with a proper definition. Regression test of gh-7429.""" empty = QuantumCircuit(1, name="empty").to_gate() opaque = Gate("opaque", 1, []) qc = QuantumCircuit(2) qc.append(empty, [0], []) qc.append(opaque, [1], []) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circ = load(qpy_file)[0] self.assertEqual(qc, new_circ) self.assertEqual(qc.decompose(), new_circ.decompose()) self.assertEqual(len(new_circ), 2) self.assertIsInstance(new_circ.data[0].operation.definition, QuantumCircuit) self.assertIs(new_circ.data[1].operation.definition, None) self.assertDeprecatedBitProperties(qc, new_circ) def test_custom_instruction_with_noop_definition(self): """Test that a custom instruction whose definition contains no elements is serialized with a proper definition. Regression test of gh-7429.""" empty = QuantumCircuit(1, name="empty").to_instruction() opaque = Instruction("opaque", 1, 0, []) qc = QuantumCircuit(2) qc.append(empty, [0], []) qc.append(opaque, [1], []) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circ = load(qpy_file)[0] self.assertEqual(qc, new_circ) self.assertEqual(qc.decompose(), new_circ.decompose()) self.assertEqual(len(new_circ), 2) self.assertIsInstance(new_circ.data[0].operation.definition, QuantumCircuit) self.assertIs(new_circ.data[1].operation.definition, None) self.assertDeprecatedBitProperties(qc, new_circ) def test_standard_gate_with_label(self): """Test a standard gate with a label.""" qc = QuantumCircuit(1) gate = XGate() gate.label = "My special X gate" qc.append(gate, [0]) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circ = load(qpy_file)[0] self.assertEqual(qc, new_circ) self.assertEqual( [x.operation.label for x in qc.data], [x.operation.label for x in new_circ.data] ) self.assertDeprecatedBitProperties(qc, new_circ) def test_circuit_with_conditional_with_label(self): """Test that instructions with conditions are correctly serialized.""" qc = QuantumCircuit(1, 1) gate = XGate(label="My conditional x gate") gate.c_if(qc.cregs[0], 1) qc.append(gate, [0]) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circ = load(qpy_file)[0] self.assertEqual(qc, new_circ) self.assertEqual( [x.operation.label for x in qc.data], [x.operation.label for x in new_circ.data] ) self.assertDeprecatedBitProperties(qc, new_circ) def test_initialize_qft(self): """Test that initialize with a complex statevector and qft work.""" k = 5 state = (1 / np.sqrt(8)) * np.array( [ np.exp(-1j * 2 * np.pi * k * (0) / 8), np.exp(-1j * 2 * np.pi * k * (1) / 8), np.exp(-1j * 2 * np.pi * k * (2) / 8), np.exp(-1j * 2 * np.pi * k * 3 / 8), np.exp(-1j * 2 * np.pi * k * 4 / 8), np.exp(-1j * 2 * np.pi * k * 5 / 8), np.exp(-1j * 2 * np.pi * k * 6 / 8), np.exp(-1j * 2 * np.pi * k * 7 / 8), ] ) qubits = 3 qc = QuantumCircuit(qubits, qubits) qc.initialize(state) qc.append(QFT(qubits), range(qubits)) qc.measure(range(qubits), range(qubits)) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circ = load(qpy_file)[0] self.assertEqual(qc, new_circ) self.assertEqual( [x.operation.label for x in qc.data], [x.operation.label for x in new_circ.data] ) self.assertDeprecatedBitProperties(qc, new_circ) def test_statepreparation(self): """Test that state preparation with a complex statevector and qft work.""" k = 5 state = (1 / np.sqrt(8)) * np.array( [ np.exp(-1j * 2 * np.pi * k * (0) / 8), np.exp(-1j * 2 * np.pi * k * (1) / 8), np.exp(-1j * 2 * np.pi * k * (2) / 8), np.exp(-1j * 2 * np.pi * k * 3 / 8), np.exp(-1j * 2 * np.pi * k * 4 / 8), np.exp(-1j * 2 * np.pi * k * 5 / 8), np.exp(-1j * 2 * np.pi * k * 6 / 8), np.exp(-1j * 2 * np.pi * k * 7 / 8), ] ) qubits = 3 qc = QuantumCircuit(qubits, qubits) qc.prepare_state(state) qc.append(QFT(qubits), range(qubits)) qc.measure(range(qubits), range(qubits)) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circ = load(qpy_file)[0] self.assertEqual(qc, new_circ) self.assertEqual( [x.operation.label for x in qc.data], [x.operation.label for x in new_circ.data] ) self.assertDeprecatedBitProperties(qc, new_circ) def test_single_bit_teleportation(self): """Test a teleportation circuit with single bit conditions.""" qr = QuantumRegister(1) cr = ClassicalRegister(2, name="name") qc = QuantumCircuit(qr, cr, name="Reset Test") qc.x(0) qc.measure(0, cr[0]) qc.x(0).c_if(cr[0], 1) qc.measure(0, cr[1]) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circ = load(qpy_file)[0] self.assertEqual(qc, new_circ) self.assertEqual( [x.operation.label for x in qc.data], [x.operation.label for x in new_circ.data] ) self.assertDeprecatedBitProperties(qc, new_circ) def test_qaoa(self): """Test loading a QAOA circuit works.""" cost_operator = Pauli("ZIIZ") qaoa = QAOAAnsatz(cost_operator, reps=2) qpy_file = io.BytesIO() dump(qaoa, qpy_file) qpy_file.seek(0) new_circ = load(qpy_file)[0] self.assertEqual(qaoa, new_circ) self.assertEqual( [x.operation.label for x in qaoa.data], [x.operation.label for x in new_circ.data] ) self.assertDeprecatedBitProperties(qaoa, new_circ) def test_evolutiongate(self): """Test loading a circuit with evolution gate works.""" synthesis = LieTrotter(reps=2) evo = PauliEvolutionGate( SparsePauliOp.from_list([("ZI", 1), ("IZ", 1)]), time=2, synthesis=synthesis ) qc = QuantumCircuit(2) qc.append(evo, range(2)) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circ = load(qpy_file)[0] self.assertEqual(qc, new_circ) self.assertEqual( [x.operation.label for x in qc.data], [x.operation.label for x in new_circ.data] ) new_evo = new_circ.data[0].operation self.assertIsInstance(new_evo, PauliEvolutionGate) self.assertDeprecatedBitProperties(qc, new_circ) def test_evolutiongate_param_time(self): """Test loading a circuit with an evolution gate that has a parameter for time.""" synthesis = LieTrotter(reps=2) time = Parameter("t") evo = PauliEvolutionGate( SparsePauliOp.from_list([("ZI", 1), ("IZ", 1)]), time=time, synthesis=synthesis ) qc = QuantumCircuit(2) qc.append(evo, range(2)) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circ = load(qpy_file)[0] self.assertEqual(qc, new_circ) self.assertEqual( [x.operation.label for x in qc.data], [x.operation.label for x in new_circ.data] ) new_evo = new_circ.data[0].operation self.assertIsInstance(new_evo, PauliEvolutionGate) self.assertDeprecatedBitProperties(qc, new_circ) def test_evolutiongate_param_expr_time(self): """Test loading a circuit with an evolution gate that has a parameter for time.""" synthesis = LieTrotter(reps=2) time = Parameter("t") evo = PauliEvolutionGate( SparsePauliOp.from_list([("ZI", 1), ("IZ", 1)]), time=time * time, synthesis=synthesis ) qc = QuantumCircuit(2) qc.append(evo, range(2)) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circ = load(qpy_file)[0] self.assertEqual(qc, new_circ) self.assertEqual( [x.operation.label for x in qc.data], [x.operation.label for x in new_circ.data] ) new_evo = new_circ.data[0].operation self.assertIsInstance(new_evo, PauliEvolutionGate) self.assertDeprecatedBitProperties(qc, new_circ) def test_evolutiongate_param_vec_time(self): """Test loading a an evolution gate that has a param vector element for time.""" synthesis = LieTrotter(reps=2) time = ParameterVector("TimeVec", 1) evo = PauliEvolutionGate( SparsePauliOp.from_list([("ZI", 1), ("IZ", 1)]), time=time[0], synthesis=synthesis ) qc = QuantumCircuit(2) qc.append(evo, range(2)) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circ = load(qpy_file)[0] self.assertEqual(qc, new_circ) self.assertEqual( [x.operation.label for x in qc.data], [x.operation.label for x in new_circ.data] ) new_evo = new_circ.data[0].operation self.assertIsInstance(new_evo, PauliEvolutionGate) self.assertDeprecatedBitProperties(qc, new_circ) def test_op_list_evolutiongate(self): """Test loading a circuit with evolution gate works.""" evo = PauliEvolutionGate( [SparsePauliOp.from_list([("ZI", 1), ("IZ", 1)])] * 5, time=0.2, synthesis=None ) qc = QuantumCircuit(2) qc.append(evo, range(2)) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circ = load(qpy_file)[0] self.assertEqual(qc, new_circ) self.assertEqual( [x.operation.label for x in qc.data], [x.operation.label for x in new_circ.data] ) new_evo = new_circ.data[0].operation self.assertIsInstance(new_evo, PauliEvolutionGate) self.assertDeprecatedBitProperties(qc, new_circ) def test_op_evolution_gate_suzuki_trotter(self): """Test qpy path with a suzuki trotter synthesis method on an evolution gate.""" synthesis = SuzukiTrotter() evo = PauliEvolutionGate( SparsePauliOp.from_list([("ZI", 1), ("IZ", 1)]), time=0.2, synthesis=synthesis ) qc = QuantumCircuit(2) qc.append(evo, range(2)) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circ = load(qpy_file)[0] self.assertEqual(qc, new_circ) self.assertEqual( [x.operation.label for x in qc.data], [x.operation.label for x in new_circ.data] ) new_evo = new_circ.data[0].operation self.assertIsInstance(new_evo, PauliEvolutionGate) self.assertDeprecatedBitProperties(qc, new_circ) def test_parameter_expression_global_phase(self): """Test a circuit with a parameter expression global_phase.""" theta = Parameter("theta") phi = Parameter("phi") sum_param = theta + phi qc = QuantumCircuit(5, 1, global_phase=sum_param) qc.h(0) for i in range(4): qc.cx(i, i + 1) qc.barrier() qc.rz(sum_param, range(3)) qc.rz(phi, 3) qc.rz(theta, 4) qc.barrier() for i in reversed(range(4)): qc.cx(i, i + 1) qc.h(0) qc.measure(0, 0) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circuit = load(qpy_file)[0] self.assertEqual(qc, new_circuit) self.assertDeprecatedBitProperties(qc, new_circuit) def test_parameter_global_phase(self): """Test a circuit with a parameter expression global_phase.""" theta = Parameter("theta") qc = QuantumCircuit(2, global_phase=theta) qc.h(0) qc.cx(0, 1) qc.measure_all() qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circuit = load(qpy_file)[0] self.assertEqual(qc, new_circuit) def test_parameter_vector(self): """Test a circuit with a parameter vector for gate parameters.""" qc = QuantumCircuit(11) input_params = ParameterVector("x_par", 11) user_params = ParameterVector("θ_par", 11) for i, param in enumerate(user_params): qc.ry(param, i) for i, param in enumerate(input_params): qc.rz(param, i) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circuit = load(qpy_file)[0] expected_params = [x.name for x in qc.parameters] self.assertEqual([x.name for x in new_circuit.parameters], expected_params) self.assertDeprecatedBitProperties(qc, new_circuit) def test_parameter_vector_element_in_expression(self): """Test a circuit with a parameter vector used in a parameter expression.""" qc = QuantumCircuit(7) entanglement = [[i, i + 1] for i in range(7 - 1)] input_params = ParameterVector("x_par", 14) user_params = ParameterVector("\u03B8_par", 1) for i in range(qc.num_qubits): qc.ry(user_params[0], qc.qubits[i]) for source, target in entanglement: qc.cz(qc.qubits[source], qc.qubits[target]) for i in range(qc.num_qubits): qc.rz(-2 * input_params[2 * i + 1], qc.qubits[i]) qc.rx(-2 * input_params[2 * i], qc.qubits[i]) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circuit = load(qpy_file)[0] expected_params = [x.name for x in qc.parameters] self.assertEqual([x.name for x in new_circuit.parameters], expected_params) self.assertDeprecatedBitProperties(qc, new_circuit) def test_parameter_vector_incomplete_warns(self): """Test that qpy's deserialization warns if a ParameterVector isn't fully identical.""" vec = ParameterVector("test", 3) qc = QuantumCircuit(1, name="fun") qc.rx(vec[1], 0) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) with self.assertWarnsRegex(UserWarning, r"^The ParameterVector.*Elements 0, 2.*fun$"): new_circuit = load(qpy_file)[0] self.assertEqual(qc, new_circuit) self.assertDeprecatedBitProperties(qc, new_circuit) def test_parameter_vector_global_phase(self): """Test that a circuit with a standalone ParameterVectorElement phase works.""" vec = ParameterVector("phase", 1) qc = QuantumCircuit(1, global_phase=vec[0]) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circuit = load(qpy_file)[0] self.assertEqual(qc, new_circuit) self.assertDeprecatedBitProperties(qc, new_circuit) def test_custom_metadata_serializer_full_path(self): """Test that running with custom metadata serialization works.""" class CustomObject: """Custom string container object.""" def __init__(self, string): self.string = string def __eq__(self, other): return self.string == other.string class CustomSerializer(json.JSONEncoder): """Custom json encoder to handle CustomObject.""" def default(self, o): if isinstance(o, CustomObject): return {"__type__": "Custom", "value": o.string} return json.JSONEncoder.default(self, o) class CustomDeserializer(json.JSONDecoder): """Custom json decoder to handle CustomObject.""" def object_hook(self, o): # pylint: disable=invalid-name,method-hidden """Hook to override default decoder. Normally specified as a kwarg on load() that overloads the default decoder. Done here to avoid reimplementing the decode method. """ if "__type__" in o: obj_type = o["__type__"] if obj_type == "Custom": return CustomObject(o["value"]) return o theta = Parameter("theta") qc = QuantumCircuit(2, global_phase=theta) qc.h(0) qc.cx(0, 1) qc.measure_all() circuits = [qc, qc.copy()] circuits[0].metadata = {"key": CustomObject("Circuit 1")} circuits[1].metadata = {"key": CustomObject("Circuit 2")} qpy_file = io.BytesIO() dump(circuits, qpy_file, metadata_serializer=CustomSerializer) qpy_file.seek(0) new_circuits = load(qpy_file, metadata_deserializer=CustomDeserializer) self.assertEqual(qc, new_circuits[0]) self.assertEqual(circuits[0].metadata["key"], CustomObject("Circuit 1")) self.assertEqual(qc, new_circuits[1]) self.assertEqual(circuits[1].metadata["key"], CustomObject("Circuit 2")) self.assertDeprecatedBitProperties(qc, new_circuits[0]) self.assertDeprecatedBitProperties(qc, new_circuits[1]) def test_qpy_with_ifelseop(self): """Test qpy serialization with an if block.""" qc = QuantumCircuit(2, 2) qc.h(0) qc.measure(0, 0) with qc.if_test((qc.clbits[0], True)): qc.x(1) qc.measure(1, 1) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circuit = load(qpy_file)[0] self.assertEqual(qc, new_circuit) self.assertDeprecatedBitProperties(qc, new_circuit) def test_qpy_with_ifelseop_with_else(self): """Test qpy serialization with an else block.""" qc = QuantumCircuit(2, 2) qc.h(0) qc.measure(0, 0) with qc.if_test((qc.clbits[0], True)) as else_: qc.x(1) with else_: qc.y(1) qc.measure(1, 1) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circuit = load(qpy_file)[0] self.assertEqual(qc, new_circuit) self.assertDeprecatedBitProperties(qc, new_circuit) def test_qpy_with_while_loop(self): """Test qpy serialization with a for loop.""" qc = QuantumCircuit(2, 1) with qc.while_loop((qc.clbits[0], 0)): qc.h(0) qc.cx(0, 1) qc.measure(0, 0) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circuit = load(qpy_file)[0] self.assertEqual(qc, new_circuit) self.assertDeprecatedBitProperties(qc, new_circuit) def test_qpy_with_for_loop(self): """Test qpy serialization with a for loop.""" qc = QuantumCircuit(2, 1) with qc.for_loop(range(5)): qc.h(0) qc.cx(0, 1) qc.measure(0, 0) qc.break_loop().c_if(0, True) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circuit = load(qpy_file)[0] self.assertEqual(qc, new_circuit) self.assertDeprecatedBitProperties(qc, new_circuit) def test_qpy_with_for_loop_iterator(self): """Test qpy serialization with a for loop.""" qc = QuantumCircuit(2, 1) with qc.for_loop(iter(range(5))): qc.h(0) qc.cx(0, 1) qc.measure(0, 0) qc.break_loop().c_if(0, True) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circuit = load(qpy_file)[0] self.assertEqual(qc, new_circuit) self.assertDeprecatedBitProperties(qc, new_circuit) def test_qpy_clbit_switch(self): """Test QPY serialisation for a switch statement with a Clbit target.""" case_t = QuantumCircuit(2, 1) case_t.x(0) case_f = QuantumCircuit(2, 1) case_f.z(0) qc = QuantumCircuit(2, 1) qc.switch(0, [(True, case_t), (False, case_f)], qc.qubits, qc.clbits) with io.BytesIO() as fptr: dump(qc, fptr) fptr.seek(0) new_circuit = load(fptr)[0] self.assertEqual(qc, new_circuit) self.assertDeprecatedBitProperties(qc, new_circuit) def test_qpy_register_switch(self): """Test QPY serialisation for a switch statement with a ClassicalRegister target.""" qreg = QuantumRegister(2, "q") creg = ClassicalRegister(3, "c") case_0 = QuantumCircuit(qreg, creg) case_0.x(0) case_1 = QuantumCircuit(qreg, creg) case_1.z(1) case_2 = QuantumCircuit(qreg, creg) case_2.x(1) qc = QuantumCircuit(qreg, creg) qc.switch(creg, [(0, case_0), ((1, 2), case_1), ((3, 4, CASE_DEFAULT), case_2)], qreg, creg) with io.BytesIO() as fptr: dump(qc, fptr) fptr.seek(0) new_circuit = load(fptr)[0] self.assertEqual(qc, new_circuit) self.assertDeprecatedBitProperties(qc, new_circuit) def test_standalone_register_partial_bit_in_circuit(self): """Test qpy with only some bits from standalone register.""" qr = QuantumRegister(2) qc = QuantumCircuit([qr[0]]) qc.x(0) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circuit = load(qpy_file)[0] self.assertEqual(qc, new_circuit) self.assertDeprecatedBitProperties(qc, new_circuit) def test_nested_tuple_param(self): """Test qpy with an instruction that contains nested tuples.""" inst = Instruction("tuple_test", 1, 0, [((((0, 1), (0, 1)), 2, 3), ("A", "B", "C"))]) qc = QuantumCircuit(1) qc.append(inst, [0]) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circuit = load(qpy_file)[0] self.assertEqual(qc, new_circuit) self.assertDeprecatedBitProperties(qc, new_circuit) def test_empty_tuple_param(self): """Test qpy with an instruction that contains an empty tuple.""" inst = Instruction("empty_tuple_test", 1, 0, [()]) qc = QuantumCircuit(1) qc.append(inst, [0]) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circuit = load(qpy_file)[0] self.assertEqual(qc, new_circuit) self.assertDeprecatedBitProperties(qc, new_circuit) def test_ucr_gates(self): """Test qpy with UCRX, UCRY, and UCRZ gates.""" qc = QuantumCircuit(3) qc.ucrz([0, 0, 0, -np.pi], [0, 1], 2) qc.ucry([0, 0, 0, -np.pi], [0, 2], 1) qc.ucrx([0, 0, 0, -np.pi], [2, 1], 0) qc.measure_all() qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circuit = load(qpy_file)[0] self.assertEqual(qc.decompose().decompose(), new_circuit.decompose().decompose()) self.assertDeprecatedBitProperties(qc, new_circuit) def test_controlled_gate(self): """Test a custom controlled gate.""" qc = QuantumCircuit(3) controlled_gate = DCXGate().control(1) qc.append(controlled_gate, [0, 1, 2]) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circuit = load(qpy_file)[0] self.assertEqual(qc, new_circuit) self.assertDeprecatedBitProperties(qc, new_circuit) def test_controlled_gate_open_controls(self): """Test a controlled gate with open controls round-trips exactly.""" qc = QuantumCircuit(3) controlled_gate = DCXGate().control(1, ctrl_state=0) qc.append(controlled_gate, [0, 1, 2]) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circuit = load(qpy_file)[0] self.assertEqual(qc, new_circuit) self.assertDeprecatedBitProperties(qc, new_circuit) def test_nested_controlled_gate(self): """Test a custom nested controlled gate.""" custom_gate = Gate("black_box", 1, []) custom_definition = QuantumCircuit(1) custom_definition.h(0) custom_definition.rz(1.5, 0) custom_definition.sdg(0) custom_gate.definition = custom_definition qc = QuantumCircuit(3) qc.append(custom_gate, [0]) controlled_gate = custom_gate.control(2) qc.append(controlled_gate, [0, 1, 2]) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circ = load(qpy_file)[0] self.assertEqual(qc, new_circ) self.assertEqual(qc.decompose(), new_circ.decompose()) self.assertDeprecatedBitProperties(qc, new_circ) def test_open_controlled_gate(self): """Test an open control is preserved across serialization.""" qc = QuantumCircuit(2) qc.cx(0, 1, ctrl_state=0) with io.BytesIO() as fd: dump(qc, fd) fd.seek(0) new_circ = load(fd)[0] self.assertEqual(qc, new_circ) self.assertEqual(qc.data[0].operation.ctrl_state, new_circ.data[0].operation.ctrl_state) self.assertDeprecatedBitProperties(qc, new_circ) def test_standard_control_gates(self): """Test standard library controlled gates.""" qc = QuantumCircuit(6) mcu1_gate = MCU1Gate(np.pi, 2) mcx_gate = MCXGate(5) mcx_gray_gate = MCXGrayCode(5) mcx_recursive_gate = MCXRecursive(4) mcx_vchain_gate = MCXVChain(3) qc.append(mcu1_gate, [0, 2, 1]) qc.append(mcx_gate, list(range(0, 6))) qc.append(mcx_gray_gate, list(range(0, 6))) qc.append(mcx_recursive_gate, list(range(0, 5))) qc.append(mcx_vchain_gate, list(range(0, 5))) qc.mcp(np.pi, [0, 2], 1) qc.mct([0, 2], 1) qc.mcx([0, 2], 1) qc.measure_all() qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circuit = load(qpy_file)[0] self.assertEqual(qc, new_circuit) self.assertDeprecatedBitProperties(qc, new_circuit) def test_controlled_gate_subclass_custom_definition(self): """Test controlled gate with overloaded definition. Reproduce from: https://github.com/Qiskit/qiskit-terra/issues/8794 """ class CustomCXGate(ControlledGate): """Custom CX with overloaded _define.""" def __init__(self, label=None, ctrl_state=None): super().__init__( "cx", 2, [], label, num_ctrl_qubits=1, ctrl_state=ctrl_state, base_gate=XGate() ) def _define(self) -> None: qc = QuantumCircuit(2, name=self.name) qc.cx(0, 1) self.definition = qc qc = QuantumCircuit(2) qc.append(CustomCXGate(), [0, 1]) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circ = load(qpy_file)[0] self.assertEqual(qc, new_circ) self.assertEqual(qc.decompose(), new_circ.decompose()) self.assertDeprecatedBitProperties(qc, new_circ) def test_load_with_loose_bits(self): """Test that loading from a circuit with loose bits works.""" qc = QuantumCircuit([Qubit(), Qubit(), Clbit()]) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circuit = load(qpy_file)[0] self.assertEqual(tuple(new_circuit.qregs), ()) self.assertEqual(tuple(new_circuit.cregs), ()) self.assertEqual(qc, new_circuit) self.assertDeprecatedBitProperties(qc, new_circuit) def test_load_with_loose_bits_and_registers(self): """Test that loading from a circuit with loose bits and registers works.""" qc = QuantumCircuit(QuantumRegister(3), ClassicalRegister(1), [Clbit()]) qpy_file = io.BytesIO() dump(qc, qpy_file) qpy_file.seek(0) new_circuit = load(qpy_file)[0] self.assertEqual(qc, new_circuit) self.assertDeprecatedBitProperties(qc, new_circuit) def test_registers_after_loose_bits(self): """Test that a circuit whose registers appear after some loose bits roundtrips. Regression test of gh-9094.""" qc = QuantumCircuit() qc.add_bits([Qubit(), Clbit()]) qc.add_register(QuantumRegister(2, name="q1")) qc.add_register(ClassicalRegister(2, name="c1")) with io.BytesIO() as fptr: dump(qc, fptr) fptr.seek(0) new_circuit = load(fptr)[0] self.assertEqual(qc, new_circuit) self.assertDeprecatedBitProperties(qc, new_circuit) def test_roundtrip_empty_register(self): """Test that empty registers round-trip correctly.""" qc = QuantumCircuit(QuantumRegister(0), ClassicalRegister(0)) with io.BytesIO() as fptr: dump(qc, fptr) fptr.seek(0) new_circuit = load(fptr)[0] self.assertEqual(qc, new_circuit) self.assertEqual(qc.qregs, new_circuit.qregs) self.assertEqual(qc.cregs, new_circuit.cregs) self.assertDeprecatedBitProperties(qc, new_circuit) def test_roundtrip_several_empty_registers(self): """Test that several empty registers round-trip correctly.""" qc = QuantumCircuit( QuantumRegister(0, "a"), QuantumRegister(0, "b"), ClassicalRegister(0, "c"), ClassicalRegister(0, "d"), ) with io.BytesIO() as fptr: dump(qc, fptr) fptr.seek(0) new_circuit = load(fptr)[0] self.assertEqual(qc, new_circuit) self.assertEqual(qc.qregs, new_circuit.qregs) self.assertEqual(qc.cregs, new_circuit.cregs) self.assertDeprecatedBitProperties(qc, new_circuit) def test_roundtrip_empty_registers_with_loose_bits(self): """Test that empty registers still round-trip correctly in the presence of loose bits.""" loose = [Qubit(), Clbit()] qc = QuantumCircuit(loose, QuantumRegister(0), ClassicalRegister(0)) with io.BytesIO() as fptr: dump(qc, fptr) fptr.seek(0) new_circuit = load(fptr)[0] self.assertEqual(qc, new_circuit) self.assertEqual(qc.qregs, new_circuit.qregs) self.assertEqual(qc.cregs, new_circuit.cregs) qc = QuantumCircuit(QuantumRegister(0), ClassicalRegister(0), loose) with io.BytesIO() as fptr: dump(qc, fptr) fptr.seek(0) new_circuit = load(fptr)[0] self.assertEqual(qc, new_circuit) self.assertEqual(qc.qregs, new_circuit.qregs) self.assertEqual(qc.cregs, new_circuit.cregs) self.assertDeprecatedBitProperties(qc, new_circuit) def test_incomplete_owned_bits(self): """Test that a circuit that contains only some bits that are owned by a register are correctly roundtripped.""" reg = QuantumRegister(5, "q") qc = QuantumCircuit(reg[:3]) qc.ccx(0, 1, 2) with io.BytesIO() as fptr: dump(qc, fptr) fptr.seek(0) new_circuit = load(fptr)[0] self.assertEqual(qc, new_circuit) self.assertDeprecatedBitProperties(qc, new_circuit) def test_diagonal_gate(self): """Test that a `DiagonalGate` successfully roundtrips.""" qc = QuantumCircuit(2) qc.diagonal([1, -1, -1, 1], [0, 1]) with io.BytesIO() as fptr: dump(qc, fptr) fptr.seek(0) new_circuit = load(fptr)[0] # DiagonalGate (and a bunch of the qiskit.extensions gates) have non-deterministic # definitions with regard to internal instruction names, so cannot be directly compared for # equality. self.assertIs(type(qc.data[0].operation), type(new_circuit.data[0].operation)) self.assertEqual(qc.data[0].operation.params, new_circuit.data[0].operation.params) self.assertDeprecatedBitProperties(qc, new_circuit) @ddt.data(QuantumCircuit.if_test, QuantumCircuit.while_loop) def test_if_else_while_expr_simple(self, control_flow): """Test that `IfElseOp` and `WhileLoopOp` can have an `Expr` node as their `condition`, and that this round-trips through QPY.""" body = QuantumCircuit(1) qr = QuantumRegister(2, "q1") cr = ClassicalRegister(2, "c1") qc = QuantumCircuit(qr, cr) control_flow(qc, expr.equal(cr, 3), body.copy(), [0], []) control_flow(qc, expr.lift(qc.clbits[0]), body.copy(), [0], []) with io.BytesIO() as fptr: dump(qc, fptr) fptr.seek(0) new_circuit = load(fptr)[0] self.assertEqual(qc, new_circuit) self.assertEqual(qc.qregs, new_circuit.qregs) self.assertEqual(qc.cregs, new_circuit.cregs) self.assertDeprecatedBitProperties(qc, new_circuit) @ddt.data(QuantumCircuit.if_test, QuantumCircuit.while_loop) def test_if_else_while_expr_nested(self, control_flow): """Test that `IfElseOp` and `WhileLoopOp` can have an `Expr` node as their `condition`, and that this round-trips through QPY.""" inner = QuantumCircuit(1) outer = QuantumCircuit(1, 1) control_flow(outer, expr.lift(outer.clbits[0]), inner.copy(), [0], []) qr = QuantumRegister(2, "q1") cr = ClassicalRegister(2, "c1") qc = QuantumCircuit(qr, cr) control_flow(qc, expr.equal(cr, 3), outer.copy(), [1], [1]) with io.BytesIO() as fptr: dump(qc, fptr) fptr.seek(0) new_circuit = load(fptr)[0] self.assertEqual(qc, new_circuit) self.assertEqual(qc.qregs, new_circuit.qregs) self.assertEqual(qc.cregs, new_circuit.cregs) self.assertDeprecatedBitProperties(qc, new_circuit) def test_if_else_expr_stress(self): """Stress-test the `Expr` handling in the condition of an `IfElseOp`. This should hit on every aspect of the `Expr` tree.""" inner = QuantumCircuit(1) inner.x(0) outer = QuantumCircuit(1, 1) outer.if_test(expr.cast(outer.clbits[0], types.Bool()), inner.copy(), [0], []) # Register whose size is deliberately larger that one byte. cr1 = ClassicalRegister(256, "c1") cr2 = ClassicalRegister(4, "c2") loose = Clbit() qc = QuantumCircuit([Qubit(), Qubit(), loose], cr1, cr2) qc.rz(1.0, 0) qc.if_test( expr.logic_and( expr.logic_and( expr.logic_or( expr.cast( expr.less(expr.bit_and(cr1, 0x0F), expr.bit_not(cr1)), types.Bool(), ), expr.cast( expr.less_equal(expr.bit_or(cr2, 7), expr.bit_xor(cr2, 7)), types.Bool(), ), ), expr.logic_and( expr.logic_or(expr.equal(cr2, 2), expr.logic_not(expr.not_equal(cr2, 3))), expr.logic_or( expr.greater(cr2, 3), expr.greater_equal(cr2, 3), ), ), ), expr.logic_not(loose), ), outer.copy(), [1], [0], ) qc.rz(1.0, 0) with io.BytesIO() as fptr: dump(qc, fptr) fptr.seek(0) new_circuit = load(fptr)[0] self.assertEqual(qc, new_circuit) self.assertEqual(qc.qregs, new_circuit.qregs) self.assertEqual(qc.cregs, new_circuit.cregs) self.assertDeprecatedBitProperties(qc, new_circuit) def test_switch_expr_simple(self): """Test that `SwitchCaseOp` can have an `Expr` node as its `target`, and that this round-trips through QPY.""" body = QuantumCircuit(1) qr = QuantumRegister(2, "q1") cr = ClassicalRegister(2, "c1") qc = QuantumCircuit(qr, cr) qc.switch(expr.bit_and(cr, 3), [(1, body.copy())], [0], []) qc.switch(expr.logic_not(qc.clbits[0]), [(False, body.copy())], [0], []) with io.BytesIO() as fptr: dump(qc, fptr) fptr.seek(0) new_circuit = load(fptr)[0] self.assertEqual(qc, new_circuit) self.assertEqual(qc.qregs, new_circuit.qregs) self.assertEqual(qc.cregs, new_circuit.cregs) self.assertDeprecatedBitProperties(qc, new_circuit) def test_switch_expr_nested(self): """Test that `SwitchCaseOp` can have an `Expr` node as its `target`, and that this round-trips through QPY.""" inner = QuantumCircuit(1) outer = QuantumCircuit(1, 1) outer.switch(expr.lift(outer.clbits[0]), [(False, inner.copy())], [0], []) qr = QuantumRegister(2, "q1") cr = ClassicalRegister(2, "c1") qc = QuantumCircuit(qr, cr) qc.switch(expr.lift(cr), [(3, outer.copy())], [1], [1]) with io.BytesIO() as fptr: dump(qc, fptr) fptr.seek(0) new_circuit = load(fptr)[0] self.assertEqual(qc, new_circuit) self.assertEqual(qc.qregs, new_circuit.qregs) self.assertEqual(qc.cregs, new_circuit.cregs) self.assertDeprecatedBitProperties(qc, new_circuit) def test_switch_expr_stress(self): """Stress-test the `Expr` handling in the target of a `SwitchCaseOp`. This should hit on every aspect of the `Expr` tree.""" inner = QuantumCircuit(1) inner.x(0) outer = QuantumCircuit(1, 1) outer.switch(expr.cast(outer.clbits[0], types.Bool()), [(True, inner.copy())], [0], []) # Register whose size is deliberately larger that one byte. cr1 = ClassicalRegister(256, "c1") cr2 = ClassicalRegister(4, "c2") loose = Clbit() qc = QuantumCircuit([Qubit(), Qubit(), loose], cr1, cr2) qc.rz(1.0, 0) qc.switch( expr.logic_and( expr.logic_and( expr.logic_or( expr.cast( expr.less(expr.bit_and(cr1, 0x0F), expr.bit_not(cr1)), types.Bool(), ), expr.cast( expr.less_equal(expr.bit_or(cr2, 7), expr.bit_xor(cr2, 7)), types.Bool(), ), ), expr.logic_and( expr.logic_or(expr.equal(cr2, 2), expr.logic_not(expr.not_equal(cr2, 3))), expr.logic_or( expr.greater(cr2, 3), expr.greater_equal(cr2, 3), ), ), ), expr.logic_not(loose), ), [(False, outer.copy())], [1], [0], ) qc.rz(1.0, 0) with io.BytesIO() as fptr: dump(qc, fptr) fptr.seek(0) new_circuit = load(fptr)[0] self.assertEqual(qc, new_circuit) self.assertEqual(qc.qregs, new_circuit.qregs) self.assertEqual(qc.cregs, new_circuit.cregs) self.assertDeprecatedBitProperties(qc, new_circuit) def test_multiple_nested_control_custom_definitions(self): """Test that circuits with multiple controlled custom gates that in turn depend on custom gates can be exported successfully when there are several such gates in the outer circuit. See gh-9746""" inner_1 = QuantumCircuit(1, name="inner_1") inner_1.x(0) inner_2 = QuantumCircuit(1, name="inner_2") inner_2.y(0) outer_1 = QuantumCircuit(1, name="outer_1") outer_1.append(inner_1.to_gate(), [0], []) outer_2 = QuantumCircuit(1, name="outer_2") outer_2.append(inner_2.to_gate(), [0], []) qc = QuantumCircuit(2) qc.append(outer_1.to_gate().control(1), [0, 1], []) qc.append(outer_2.to_gate().control(1), [0, 1], []) with io.BytesIO() as fptr: dump(qc, fptr) fptr.seek(0) new_circuit = load(fptr)[0] self.assertEqual(qc, new_circuit) self.assertDeprecatedBitProperties(qc, new_circuit) def test_qpy_deprecation(self): """Test the old import path's deprecations fire.""" with self.assertWarnsRegex(DeprecationWarning, "is deprecated"): # pylint: disable=no-name-in-module, unused-import, redefined-outer-name, reimported from qiskit.circuit.qpy_serialization import dump, load
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test Qiskit's QuantumCircuit class for multiple registers.""" from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.converters.circuit_to_dag import circuit_to_dag from qiskit.test import QiskitTestCase from qiskit.circuit.exceptions import CircuitError class TestCircuitMultiRegs(QiskitTestCase): """QuantumCircuit Qasm tests.""" def test_circuit_multi(self): """Test circuit multi regs declared at start.""" qreg0 = QuantumRegister(2, "q0") creg0 = ClassicalRegister(2, "c0") qreg1 = QuantumRegister(2, "q1") creg1 = ClassicalRegister(2, "c1") circ = QuantumCircuit(qreg0, qreg1, creg0, creg1) circ.x(qreg0[1]) circ.x(qreg1[0]) meas = QuantumCircuit(qreg0, qreg1, creg0, creg1) meas.measure(qreg0, creg0) meas.measure(qreg1, creg1) qc = circ.compose(meas) circ2 = QuantumCircuit() circ2.add_register(qreg0) circ2.add_register(qreg1) circ2.add_register(creg0) circ2.add_register(creg1) circ2.x(qreg0[1]) circ2.x(qreg1[0]) meas2 = QuantumCircuit() meas2.add_register(qreg0) meas2.add_register(qreg1) meas2.add_register(creg0) meas2.add_register(creg1) meas2.measure(qreg0, creg0) meas2.measure(qreg1, creg1) qc2 = circ2.compose(meas2) dag_qc = circuit_to_dag(qc) dag_qc2 = circuit_to_dag(qc2) dag_circ2 = circuit_to_dag(circ2) dag_circ = circuit_to_dag(circ) self.assertEqual(dag_qc, dag_qc2) self.assertEqual(dag_circ, dag_circ2) def test_circuit_multi_name_collision(self): """Test circuit multi regs, with name collision.""" qreg0 = QuantumRegister(2, "q") qreg1 = QuantumRegister(3, "q") self.assertRaises(CircuitError, QuantumCircuit, qreg0, qreg1)
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test Qiskit's QuantumCircuit class.""" import numpy as np from ddt import data, ddt from qiskit import BasicAer, ClassicalRegister, QuantumCircuit, QuantumRegister, execute from qiskit.circuit import Gate, Instruction, Measure, Parameter from qiskit.circuit.bit import Bit from qiskit.circuit.classicalregister import Clbit from qiskit.circuit.exceptions import CircuitError from qiskit.circuit.controlflow import IfElseOp from qiskit.circuit.library import CXGate, HGate from qiskit.circuit.library.standard_gates import SGate from qiskit.circuit.quantumcircuit import BitLocations from qiskit.circuit.quantumcircuitdata import CircuitInstruction from qiskit.circuit.quantumregister import AncillaQubit, AncillaRegister, Qubit from qiskit.pulse import DriveChannel, Gaussian, Play, Schedule from qiskit.quantum_info import Operator from qiskit.test import QiskitTestCase @ddt class TestCircuitOperations(QiskitTestCase): """QuantumCircuit Operations tests.""" @data(0, 1, -1, -2) def test_append_resolves_integers(self, index): """Test that integer arguments to append are correctly resolved.""" # We need to assume that appending ``Bit`` instances will always work, so we have something # to test against. qubits = [Qubit(), Qubit()] clbits = [Clbit(), Clbit()] test = QuantumCircuit(qubits, clbits) test.append(Measure(), [index], [index]) expected = QuantumCircuit(qubits, clbits) expected.append(Measure(), [qubits[index]], [clbits[index]]) self.assertEqual(test, expected) @data(np.int32(0), np.int8(-1), np.uint64(1)) def test_append_resolves_numpy_integers(self, index): """Test that Numpy's integers can be used to reference qubits and clbits.""" qubits = [Qubit(), Qubit()] clbits = [Clbit(), Clbit()] test = QuantumCircuit(qubits, clbits) test.append(Measure(), [index], [index]) expected = QuantumCircuit(qubits, clbits) expected.append(Measure(), [qubits[int(index)]], [clbits[int(index)]]) self.assertEqual(test, expected) @data( slice(0, 2), slice(None, 1), slice(1, None), slice(None, None), slice(0, 2, 2), slice(2, -1, -1), slice(1000, 1003), ) def test_append_resolves_slices(self, index): """Test that slices can be used to reference qubits and clbits with the same semantics that they have on lists.""" qregs = [QuantumRegister(2), QuantumRegister(1)] cregs = [ClassicalRegister(1), ClassicalRegister(2)] test = QuantumCircuit(*qregs, *cregs) test.append(Measure(), [index], [index]) expected = QuantumCircuit(*qregs, *cregs) for qubit, clbit in zip(expected.qubits[index], expected.clbits[index]): expected.append(Measure(), [qubit], [clbit]) self.assertEqual(test, expected) def test_append_resolves_scalar_numpy_array(self): """Test that size-1 Numpy arrays can be used to index arguments. These arrays can be passed to ``int``, which means they sometimes might be involved in spurious casts.""" test = QuantumCircuit(1, 1) test.append(Measure(), [np.array([0])], [np.array([0])]) expected = QuantumCircuit(1, 1) expected.measure(0, 0) self.assertEqual(test, expected) @data([3], [-3], [0, 1, 3]) def test_append_rejects_out_of_range_input(self, specifier): """Test that append rejects an integer that's out of range.""" test = QuantumCircuit(2, 2) with self.subTest("qubit"), self.assertRaisesRegex(CircuitError, "out of range"): opaque = Instruction("opaque", len(specifier), 1, []) test.append(opaque, specifier, [0]) with self.subTest("clbit"), self.assertRaisesRegex(CircuitError, "out of range"): opaque = Instruction("opaque", 1, len(specifier), []) test.append(opaque, [0], specifier) def test_append_rejects_bits_not_in_circuit(self): """Test that append rejects bits that are not in the circuit.""" test = QuantumCircuit(2, 2) with self.subTest("qubit"), self.assertRaisesRegex(CircuitError, "not in the circuit"): test.append(Measure(), [Qubit()], [test.clbits[0]]) with self.subTest("clbit"), self.assertRaisesRegex(CircuitError, "not in the circuit"): test.append(Measure(), [test.qubits[0]], [Clbit()]) with self.subTest("qubit list"), self.assertRaisesRegex(CircuitError, "not in the circuit"): test.append(Measure(), [[test.qubits[0], Qubit()]], [test.clbits]) with self.subTest("clbit list"), self.assertRaisesRegex(CircuitError, "not in the circuit"): test.append(Measure(), [test.qubits], [[test.clbits[0], Clbit()]]) def test_append_rejects_bit_of_wrong_type(self): """Test that append rejects bits of the wrong type in an argument list.""" qubits = [Qubit(), Qubit()] clbits = [Clbit(), Clbit()] test = QuantumCircuit(qubits, clbits) with self.subTest("c to q"), self.assertRaisesRegex(CircuitError, "Incorrect bit type"): test.append(Measure(), [clbits[0]], [clbits[1]]) with self.subTest("q to c"), self.assertRaisesRegex(CircuitError, "Incorrect bit type"): test.append(Measure(), [qubits[0]], [qubits[1]]) with self.subTest("none to q"), self.assertRaisesRegex(CircuitError, "Incorrect bit type"): test.append(Measure(), [Bit()], [clbits[0]]) with self.subTest("none to c"), self.assertRaisesRegex(CircuitError, "Incorrect bit type"): test.append(Measure(), [qubits[0]], [Bit()]) with self.subTest("none list"), self.assertRaisesRegex(CircuitError, "Incorrect bit type"): test.append(Measure(), [[qubits[0], Bit()]], [[clbits[0], Bit()]]) @data(0.0, 1.0, 1.0 + 0.0j, "0") def test_append_rejects_wrong_types(self, specifier): """Test that various bad inputs are rejected, both given loose or in sublists.""" test = QuantumCircuit(2, 2) # Use a default Instruction to be sure that there's not overridden broadcasting. opaque = Instruction("opaque", 1, 1, []) with self.subTest("q"), self.assertRaisesRegex(CircuitError, "Invalid bit index"): test.append(opaque, [specifier], [0]) with self.subTest("c"), self.assertRaisesRegex(CircuitError, "Invalid bit index"): test.append(opaque, [0], [specifier]) with self.subTest("q list"), self.assertRaisesRegex(CircuitError, "Invalid bit index"): test.append(opaque, [[specifier]], [[0]]) with self.subTest("c list"), self.assertRaisesRegex(CircuitError, "Invalid bit index"): test.append(opaque, [[0]], [[specifier]]) @data([], [0], [0, 1, 2]) def test_append_rejects_bad_arguments_opaque(self, bad_arg): """Test that a suitable exception is raised when there is an argument mismatch.""" inst = QuantumCircuit(2, 2).to_instruction() qc = QuantumCircuit(3, 3) with self.assertRaisesRegex(CircuitError, "The amount of qubit arguments"): qc.append(inst, bad_arg, [0, 1]) with self.assertRaisesRegex(CircuitError, "The amount of clbit arguments"): qc.append(inst, [0, 1], bad_arg) def test_anding_self(self): """Test that qc &= qc finishes, which can be prone to infinite while-loops. This can occur e.g. when a user tries >>> other_qc = qc >>> other_qc &= qc # or qc2.compose(qc) """ qc = QuantumCircuit(1) qc.x(0) # must contain at least one operation to end up in a infinite while-loop # attempt addition, times out if qc is added via reference qc &= qc # finally, qc should contain two X gates self.assertEqual(["x", "x"], [x.operation.name for x in qc.data]) def test_compose_circuit(self): """Test composing two circuits""" qr = QuantumRegister(2) cr = ClassicalRegister(2) qc1 = QuantumCircuit(qr, cr) qc2 = QuantumCircuit(qr, cr) qc1.h(qr[0]) qc1.measure(qr[0], cr[0]) qc2.measure(qr[1], cr[1]) qc3 = qc1.compose(qc2) backend = BasicAer.get_backend("qasm_simulator") shots = 1024 result = execute(qc3, backend=backend, shots=shots, seed_simulator=78).result() counts = result.get_counts() target = {"00": shots / 2, "01": shots / 2} threshold = 0.04 * shots self.assertDictEqual(qc3.count_ops(), {"h": 1, "measure": 2}) self.assertDictEqual(qc1.count_ops(), {"h": 1, "measure": 1}) # no changes "in-place" self.assertDictEqual(qc2.count_ops(), {"measure": 1}) # no changes "in-place" self.assertDictAlmostEqual(counts, target, threshold) def test_compose_circuit_and(self): """Test composing two circuits using & operator""" qr = QuantumRegister(2) cr = ClassicalRegister(2) qc1 = QuantumCircuit(qr, cr) qc2 = QuantumCircuit(qr, cr) qc1.h(qr[0]) qc1.measure(qr[0], cr[0]) qc2.measure(qr[1], cr[1]) qc3 = qc1 & qc2 backend = BasicAer.get_backend("qasm_simulator") shots = 1024 result = execute(qc3, backend=backend, shots=shots, seed_simulator=78).result() counts = result.get_counts() target = {"00": shots / 2, "01": shots / 2} threshold = 0.04 * shots self.assertDictEqual(qc3.count_ops(), {"h": 1, "measure": 2}) self.assertDictEqual(qc1.count_ops(), {"h": 1, "measure": 1}) # no changes "in-place" self.assertDictEqual(qc2.count_ops(), {"measure": 1}) # no changes "in-place" self.assertDictAlmostEqual(counts, target, threshold) def test_compose_circuit_iand(self): """Test composing circuits using &= operator (in place)""" qr = QuantumRegister(2) cr = ClassicalRegister(2) qc1 = QuantumCircuit(qr, cr) qc2 = QuantumCircuit(qr, cr) qc1.h(qr[0]) qc1.measure(qr[0], cr[0]) qc2.measure(qr[1], cr[1]) qc1 &= qc2 backend = BasicAer.get_backend("qasm_simulator") shots = 1024 result = execute(qc1, backend=backend, shots=shots, seed_simulator=78).result() counts = result.get_counts() target = {"00": shots / 2, "01": shots / 2} threshold = 0.04 * shots self.assertDictEqual(qc1.count_ops(), {"h": 1, "measure": 2}) # changes "in-place" self.assertDictEqual(qc2.count_ops(), {"measure": 1}) # no changes "in-place" self.assertDictAlmostEqual(counts, target, threshold) def test_compose_circuit_fail_circ_size(self): """Test composing circuit fails when number of wires in circuit is not enough""" qr1 = QuantumRegister(2) qr2 = QuantumRegister(4) # Creating our circuits qc1 = QuantumCircuit(qr1) qc1.x(0) qc1.h(1) qc2 = QuantumCircuit(qr2) qc2.h([1, 2]) qc2.cx(2, 3) # Composing will fail because qc2 requires 4 wires self.assertRaises(CircuitError, qc1.compose, qc2) def test_compose_circuit_fail_arg_size(self): """Test composing circuit fails when arg size does not match number of wires""" qr1 = QuantumRegister(2) qr2 = QuantumRegister(2) qc1 = QuantumCircuit(qr1) qc1.h(0) qc2 = QuantumCircuit(qr2) qc2.cx(0, 1) self.assertRaises(CircuitError, qc1.compose, qc2, qubits=[0]) def test_tensor_circuit(self): """Test tensoring two circuits""" qc1 = QuantumCircuit(1, 1) qc2 = QuantumCircuit(1, 1) qc2.h(0) qc2.measure(0, 0) qc1.measure(0, 0) qc3 = qc1.tensor(qc2) backend = BasicAer.get_backend("qasm_simulator") shots = 1024 result = execute(qc3, backend=backend, shots=shots, seed_simulator=78).result() counts = result.get_counts() target = {"00": shots / 2, "01": shots / 2} threshold = 0.04 * shots self.assertDictEqual(qc3.count_ops(), {"h": 1, "measure": 2}) self.assertDictEqual(qc2.count_ops(), {"h": 1, "measure": 1}) # no changes "in-place" self.assertDictEqual(qc1.count_ops(), {"measure": 1}) # no changes "in-place" self.assertDictAlmostEqual(counts, target, threshold) def test_tensor_circuit_xor(self): """Test tensoring two circuits using ^ operator""" qc1 = QuantumCircuit(1, 1) qc2 = QuantumCircuit(1, 1) qc2.h(0) qc2.measure(0, 0) qc1.measure(0, 0) qc3 = qc1 ^ qc2 backend = BasicAer.get_backend("qasm_simulator") shots = 1024 result = execute(qc3, backend=backend, shots=shots, seed_simulator=78).result() counts = result.get_counts() target = {"00": shots / 2, "01": shots / 2} threshold = 0.04 * shots self.assertDictEqual(qc3.count_ops(), {"h": 1, "measure": 2}) self.assertDictEqual(qc2.count_ops(), {"h": 1, "measure": 1}) # no changes "in-place" self.assertDictEqual(qc1.count_ops(), {"measure": 1}) # no changes "in-place" self.assertDictAlmostEqual(counts, target, threshold) def test_tensor_circuit_ixor(self): """Test tensoring two circuits using ^= operator""" qc1 = QuantumCircuit(1, 1) qc2 = QuantumCircuit(1, 1) qc2.h(0) qc2.measure(0, 0) qc1.measure(0, 0) qc1 ^= qc2 backend = BasicAer.get_backend("qasm_simulator") shots = 1024 result = execute(qc1, backend=backend, shots=shots, seed_simulator=78).result() counts = result.get_counts() target = {"00": shots / 2, "01": shots / 2} threshold = 0.04 * shots self.assertDictEqual(qc1.count_ops(), {"h": 1, "measure": 2}) # changes "in-place" self.assertDictEqual(qc2.count_ops(), {"h": 1, "measure": 1}) # no changes "in-place" self.assertDictAlmostEqual(counts, target, threshold) def test_measure_args_type_cohesion(self): """Test for proper args types for measure function.""" quantum_reg = QuantumRegister(3) classical_reg_0 = ClassicalRegister(1) classical_reg_1 = ClassicalRegister(2) quantum_circuit = QuantumCircuit(quantum_reg, classical_reg_0, classical_reg_1) quantum_circuit.h(quantum_reg) with self.assertRaises(CircuitError) as ctx: quantum_circuit.measure(quantum_reg, classical_reg_1) self.assertEqual(ctx.exception.message, "register size error") def test_copy_circuit(self): """Test copy method makes a copy""" qr = QuantumRegister(2) cr = ClassicalRegister(2) qc = QuantumCircuit(qr, cr) qc.h(qr[0]) qc.measure(qr[0], cr[0]) qc.measure(qr[1], cr[1]) self.assertEqual(qc, qc.copy()) def test_copy_copies_registers(self): """Test copy copies the registers not via reference.""" qc = QuantumCircuit(1, 1) copied = qc.copy() copied.add_register(QuantumRegister(1, "additional_q")) copied.add_register(ClassicalRegister(1, "additional_c")) self.assertEqual(len(qc.qregs), 1) self.assertEqual(len(copied.qregs), 2) self.assertEqual(len(qc.cregs), 1) self.assertEqual(len(copied.cregs), 2) def test_copy_empty_like_circuit(self): """Test copy_empty_like method makes a clear copy.""" qr = QuantumRegister(2) cr = ClassicalRegister(2) qc = QuantumCircuit(qr, cr, global_phase=1.0, name="qc", metadata={"key": "value"}) qc.h(qr[0]) qc.measure(qr[0], cr[0]) qc.measure(qr[1], cr[1]) sched = Schedule(Play(Gaussian(160, 0.1, 40), DriveChannel(0))) qc.add_calibration("h", [0, 1], sched) copied = qc.copy_empty_like() qc.clear() self.assertEqual(qc, copied) self.assertEqual(qc.global_phase, copied.global_phase) self.assertEqual(qc.name, copied.name) self.assertEqual(qc.metadata, copied.metadata) self.assertEqual(qc.calibrations, copied.calibrations) copied = qc.copy_empty_like("copy") self.assertEqual(copied.name, "copy") def test_circuit_copy_rejects_invalid_types(self): """Test copy method rejects argument with type other than 'string' and 'None' type.""" qc = QuantumCircuit(1, 1) qc.h(0) with self.assertRaises(TypeError): qc.copy([1, "2", 3]) def test_circuit_copy_empty_like_rejects_invalid_types(self): """Test copy_empty_like method rejects argument with type other than 'string' and 'None' type.""" qc = QuantumCircuit(1, 1) qc.h(0) with self.assertRaises(TypeError): qc.copy_empty_like(123) def test_clear_circuit(self): """Test clear method deletes instructions in circuit.""" qr = QuantumRegister(2) cr = ClassicalRegister(2) qc = QuantumCircuit(qr, cr) qc.h(qr[0]) qc.measure(qr[0], cr[0]) qc.measure(qr[1], cr[1]) qc.clear() self.assertEqual(len(qc.data), 0) self.assertEqual(len(qc._parameter_table), 0) def test_measure_active(self): """Test measure_active Applies measurements only to non-idle qubits. Creates a ClassicalRegister of size equal to the amount of non-idle qubits to store the measured values. """ qr = QuantumRegister(4) cr = ClassicalRegister(2, "measure") circuit = QuantumCircuit(qr) circuit.h(qr[0]) circuit.h(qr[2]) circuit.measure_active() expected = QuantumCircuit(qr) expected.h(qr[0]) expected.h(qr[2]) expected.add_register(cr) expected.barrier() expected.measure([qr[0], qr[2]], [cr[0], cr[1]]) self.assertEqual(expected, circuit) def test_measure_active_copy(self): """Test measure_active copy Applies measurements only to non-idle qubits. Creates a ClassicalRegister of size equal to the amount of non-idle qubits to store the measured values. """ qr = QuantumRegister(4) cr = ClassicalRegister(2, "measure") circuit = QuantumCircuit(qr) circuit.h(qr[0]) circuit.h(qr[2]) new_circuit = circuit.measure_active(inplace=False) expected = QuantumCircuit(qr) expected.h(qr[0]) expected.h(qr[2]) expected.add_register(cr) expected.barrier() expected.measure([qr[0], qr[2]], [cr[0], cr[1]]) self.assertEqual(expected, new_circuit) self.assertFalse("measure" in circuit.count_ops().keys()) def test_measure_active_repetition(self): """Test measure_active in a circuit with a 'measure' creg. measure_active should be aware that the creg 'measure' might exists. """ qr = QuantumRegister(2) cr = ClassicalRegister(2, "measure") circuit = QuantumCircuit(qr, cr) circuit.h(qr) circuit.measure_active() self.assertEqual(len(circuit.cregs), 2) # Two cregs self.assertEqual(len(circuit.cregs[0]), 2) # Both length 2 self.assertEqual(len(circuit.cregs[1]), 2) def test_measure_all(self): """Test measure_all applies measurements to all qubits. Creates a ClassicalRegister of size equal to the total amount of qubits to store those measured values. """ qr = QuantumRegister(2) cr = ClassicalRegister(2, "meas") circuit = QuantumCircuit(qr) circuit.measure_all() expected = QuantumCircuit(qr, cr) expected.barrier() expected.measure(qr, cr) self.assertEqual(expected, circuit) def test_measure_all_not_add_bits_equal(self): """Test measure_all applies measurements to all qubits. Does not create a new ClassicalRegister if the existing one is big enough. """ qr = QuantumRegister(2) cr = ClassicalRegister(2, "meas") circuit = QuantumCircuit(qr, cr) circuit.measure_all(add_bits=False) expected = QuantumCircuit(qr, cr) expected.barrier() expected.measure(qr, cr) self.assertEqual(expected, circuit) def test_measure_all_not_add_bits_bigger(self): """Test measure_all applies measurements to all qubits. Does not create a new ClassicalRegister if the existing one is big enough. """ qr = QuantumRegister(2) cr = ClassicalRegister(3, "meas") circuit = QuantumCircuit(qr, cr) circuit.measure_all(add_bits=False) expected = QuantumCircuit(qr, cr) expected.barrier() expected.measure(qr, cr[0:2]) self.assertEqual(expected, circuit) def test_measure_all_not_add_bits_smaller(self): """Test measure_all applies measurements to all qubits. Raises an error if there are not enough classical bits to store the measurements. """ qr = QuantumRegister(3) cr = ClassicalRegister(2, "meas") circuit = QuantumCircuit(qr, cr) with self.assertRaisesRegex(CircuitError, "The number of classical bits"): circuit.measure_all(add_bits=False) def test_measure_all_copy(self): """Test measure_all with inplace=False""" qr = QuantumRegister(2) cr = ClassicalRegister(2, "meas") circuit = QuantumCircuit(qr) new_circuit = circuit.measure_all(inplace=False) expected = QuantumCircuit(qr, cr) expected.barrier() expected.measure(qr, cr) self.assertEqual(expected, new_circuit) self.assertFalse("measure" in circuit.count_ops().keys()) def test_measure_all_repetition(self): """Test measure_all in a circuit with a 'measure' creg. measure_all should be aware that the creg 'measure' might exists. """ qr = QuantumRegister(2) cr = ClassicalRegister(2, "measure") circuit = QuantumCircuit(qr, cr) circuit.measure_all() self.assertEqual(len(circuit.cregs), 2) # Two cregs self.assertEqual(len(circuit.cregs[0]), 2) # Both length 2 self.assertEqual(len(circuit.cregs[1]), 2) def test_remove_final_measurements(self): """Test remove_final_measurements Removes all measurements at end of circuit. """ qr = QuantumRegister(2) cr = ClassicalRegister(2, "meas") circuit = QuantumCircuit(qr, cr) circuit.measure(qr, cr) circuit.remove_final_measurements() expected = QuantumCircuit(qr) self.assertEqual(expected, circuit) def test_remove_final_measurements_copy(self): """Test remove_final_measurements on copy Removes all measurements at end of circuit. """ qr = QuantumRegister(2) cr = ClassicalRegister(2, "meas") circuit = QuantumCircuit(qr, cr) circuit.measure(qr, cr) new_circuit = circuit.remove_final_measurements(inplace=False) expected = QuantumCircuit(qr) self.assertEqual(expected, new_circuit) self.assertTrue("measure" in circuit.count_ops().keys()) def test_remove_final_measurements_copy_with_parameters(self): """Test remove_final_measurements doesn't corrupt ParameterTable See https://github.com/Qiskit/qiskit-terra/issues/6108 for more details """ qr = QuantumRegister(2) cr = ClassicalRegister(2, "meas") theta = Parameter("theta") circuit = QuantumCircuit(qr, cr) circuit.rz(theta, qr) circuit.measure(qr, cr) circuit.remove_final_measurements() copy = circuit.copy() self.assertEqual(copy, circuit) def test_remove_final_measurements_multiple_measures(self): """Test remove_final_measurements only removes measurements at the end of the circuit remove_final_measurements should not remove measurements in the beginning or middle of the circuit. """ qr = QuantumRegister(2) cr = ClassicalRegister(1) circuit = QuantumCircuit(qr, cr) circuit.measure(qr[0], cr) circuit.h(0) circuit.measure(qr[0], cr) circuit.h(0) circuit.measure(qr[0], cr) circuit.remove_final_measurements() expected = QuantumCircuit(qr, cr) expected.measure(qr[0], cr) expected.h(0) expected.measure(qr[0], cr) expected.h(0) self.assertEqual(expected, circuit) def test_remove_final_measurements_5802(self): """Test remove_final_measurements removes classical bits https://github.com/Qiskit/qiskit-terra/issues/5802. """ qr = QuantumRegister(2) cr = ClassicalRegister(2) circuit = QuantumCircuit(qr, cr) circuit.measure(qr, cr) circuit.remove_final_measurements() self.assertEqual(circuit.cregs, []) self.assertEqual(circuit.clbits, []) def test_remove_final_measurements_7089(self): """Test remove_final_measurements removes resulting unused registers even if not all bits were measured into. https://github.com/Qiskit/qiskit-terra/issues/7089. """ circuit = QuantumCircuit(2, 5) circuit.measure(0, 0) circuit.measure(1, 1) circuit.remove_final_measurements(inplace=True) self.assertEqual(circuit.cregs, []) self.assertEqual(circuit.clbits, []) def test_remove_final_measurements_bit_locations(self): """Test remove_final_measurements properly recalculates clbit indicies and preserves order of remaining cregs and clbits. """ c0 = ClassicalRegister(1) c1_0 = Clbit() c2 = ClassicalRegister(1) c3 = ClassicalRegister(1) # add an individual bit that's not in any register of this circuit circuit = QuantumCircuit(QuantumRegister(1), c0, [c1_0], c2, c3) circuit.measure(0, c1_0) circuit.measure(0, c2[0]) # assert cregs and clbits before measure removal self.assertEqual(circuit.cregs, [c0, c2, c3]) self.assertEqual(circuit.clbits, [c0[0], c1_0, c2[0], c3[0]]) # assert clbit indices prior to measure removal self.assertEqual(circuit.find_bit(c0[0]), BitLocations(0, [(c0, 0)])) self.assertEqual(circuit.find_bit(c1_0), BitLocations(1, [])) self.assertEqual(circuit.find_bit(c2[0]), BitLocations(2, [(c2, 0)])) self.assertEqual(circuit.find_bit(c3[0]), BitLocations(3, [(c3, 0)])) circuit.remove_final_measurements() # after measure removal, creg c2 should be gone, as should lone bit c1_0 # and c0 should still come before c3 self.assertEqual(circuit.cregs, [c0, c3]) self.assertEqual(circuit.clbits, [c0[0], c3[0]]) # there should be no gaps in clbit indices # e.g. c3[0] is now the second clbit self.assertEqual(circuit.find_bit(c0[0]), BitLocations(0, [(c0, 0)])) self.assertEqual(circuit.find_bit(c3[0]), BitLocations(1, [(c3, 0)])) def test_reverse(self): """Test reverse method reverses but does not invert.""" qc = QuantumCircuit(2, 2) qc.h(0) qc.s(1) qc.cx(0, 1) qc.measure([0, 1], [0, 1]) qc.x(0) qc.y(1) expected = QuantumCircuit(2, 2) expected.y(1) expected.x(0) expected.measure([0, 1], [0, 1]) expected.cx(0, 1) expected.s(1) expected.h(0) self.assertEqual(qc.reverse_ops(), expected) def test_repeat(self): """Test repeating the circuit works.""" qr = QuantumRegister(2) cr = ClassicalRegister(2) qc = QuantumCircuit(qr, cr) qc.h(0) qc.cx(0, 1) qc.barrier() qc.h(0).c_if(cr, 1) with self.subTest("repeat 0 times"): rep = qc.repeat(0) self.assertEqual(rep, QuantumCircuit(qr, cr)) with self.subTest("repeat 3 times"): inst = qc.to_instruction() ref = QuantumCircuit(qr, cr) for _ in range(3): ref.append(inst, ref.qubits, ref.clbits) rep = qc.repeat(3) self.assertEqual(rep, ref) @data(0, 1, 4) def test_repeat_global_phase(self, num): """Test the global phase is properly handled upon repeat.""" phase = 0.123 qc = QuantumCircuit(1, global_phase=phase) expected = np.exp(1j * phase * num) * np.identity(2) np.testing.assert_array_almost_equal(Operator(qc.repeat(num)).data, expected) def test_bind_global_phase(self): """Test binding global phase.""" x = Parameter("x") circuit = QuantumCircuit(1, global_phase=x) self.assertEqual(circuit.parameters, {x}) bound = circuit.bind_parameters({x: 2}) self.assertEqual(bound.global_phase, 2) self.assertEqual(bound.parameters, set()) def test_bind_parameter_in_phase_and_gate(self): """Test binding a parameter present in the global phase and the gates.""" x = Parameter("x") circuit = QuantumCircuit(1, global_phase=x) circuit.rx(x, 0) self.assertEqual(circuit.parameters, {x}) ref = QuantumCircuit(1, global_phase=2) ref.rx(2, 0) bound = circuit.bind_parameters({x: 2}) self.assertEqual(bound, ref) self.assertEqual(bound.parameters, set()) def test_power(self): """Test taking the circuit to a power works.""" qc = QuantumCircuit(2) qc.cx(0, 1) qc.rx(0.2, 1) gate = qc.to_gate() with self.subTest("power(int >= 0) equals repeat"): self.assertEqual(qc.power(4), qc.repeat(4)) with self.subTest("explicit matrix power"): self.assertEqual(qc.power(4, matrix_power=True).data[0].operation, gate.power(4)) with self.subTest("float power"): self.assertEqual(qc.power(1.23).data[0].operation, gate.power(1.23)) with self.subTest("negative power"): self.assertEqual(qc.power(-2).data[0].operation, gate.power(-2)) def test_power_parameterized_circuit(self): """Test taking a parameterized circuit to a power.""" theta = Parameter("th") qc = QuantumCircuit(2) qc.cx(0, 1) qc.rx(theta, 1) with self.subTest("power(int >= 0) equals repeat"): self.assertEqual(qc.power(4), qc.repeat(4)) with self.subTest("cannot to matrix power if parameterized"): with self.assertRaises(CircuitError): _ = qc.power(0.5) def test_control(self): """Test controlling the circuit.""" qc = QuantumCircuit(2, name="my_qc") qc.cry(0.2, 0, 1) c_qc = qc.control() with self.subTest("return type is circuit"): self.assertIsInstance(c_qc, QuantumCircuit) with self.subTest("test name"): self.assertEqual(c_qc.name, "c_my_qc") with self.subTest("repeated control"): cc_qc = c_qc.control() self.assertEqual(cc_qc.num_qubits, c_qc.num_qubits + 1) with self.subTest("controlled circuit has same parameter"): param = Parameter("p") qc.rx(param, 0) c_qc = qc.control() self.assertEqual(qc.parameters, c_qc.parameters) with self.subTest("non-unitary operation raises"): qc.reset(0) with self.assertRaises(CircuitError): _ = qc.control() def test_control_implementation(self): """Run a test case for controlling the circuit, which should use ``Gate.control``.""" qc = QuantumCircuit(3) qc.cx(0, 1) qc.cry(0.2, 0, 1) qc.t(0) qc.append(SGate().control(2), [0, 1, 2]) qc.iswap(2, 0) c_qc = qc.control(2, ctrl_state="10") cgate = qc.to_gate().control(2, ctrl_state="10") ref = QuantumCircuit(*c_qc.qregs) ref.append(cgate, ref.qubits) self.assertEqual(ref, c_qc) @data("gate", "instruction") def test_repeat_appended_type(self, subtype): """Test repeat appends Gate if circuit contains only gates and Instructions otherwise.""" sub = QuantumCircuit(2) sub.x(0) if subtype == "gate": sub = sub.to_gate() else: sub = sub.to_instruction() qc = QuantumCircuit(2) qc.append(sub, [0, 1]) rep = qc.repeat(3) if subtype == "gate": self.assertTrue(all(isinstance(op.operation, Gate) for op in rep.data)) else: self.assertTrue(all(isinstance(op.operation, Instruction) for op in rep.data)) def test_reverse_bits(self): """Test reversing order of bits.""" qc = QuantumCircuit(3, 2) qc.h(0) qc.s(1) qc.cx(0, 1) qc.measure(0, 1) qc.x(0) qc.y(1) qc.global_phase = -1 expected = QuantumCircuit(3, 2) expected.h(2) expected.s(1) expected.cx(2, 1) expected.measure(2, 0) expected.x(2) expected.y(1) expected.global_phase = -1 self.assertEqual(qc.reverse_bits(), expected) def test_reverse_bits_boxed(self): """Test reversing order of bits in a hierarchical circuit.""" wide_cx = QuantumCircuit(3) wide_cx.cx(0, 1) wide_cx.cx(1, 2) wide_cxg = wide_cx.to_gate() cx_box = QuantumCircuit(3) cx_box.append(wide_cxg, [0, 1, 2]) expected = QuantumCircuit(3) expected.cx(2, 1) expected.cx(1, 0) self.assertEqual(cx_box.reverse_bits().decompose(), expected) self.assertEqual(cx_box.decompose().reverse_bits(), expected) # box one more layer to be safe. cx_box_g = cx_box.to_gate() cx_box_box = QuantumCircuit(4) cx_box_box.append(cx_box_g, [0, 1, 2]) cx_box_box.cx(0, 3) expected2 = QuantumCircuit(4) expected2.cx(3, 2) expected2.cx(2, 1) expected2.cx(3, 0) self.assertEqual(cx_box_box.reverse_bits().decompose().decompose(), expected2) def test_reverse_bits_with_registers(self): """Test reversing order of bits when registers are present.""" qr1 = QuantumRegister(3, "a") qr2 = QuantumRegister(2, "b") qc = QuantumCircuit(qr1, qr2) qc.h(qr1[0]) qc.cx(qr1[0], qr1[1]) qc.cx(qr1[1], qr1[2]) qc.cx(qr1[2], qr2[0]) qc.cx(qr2[0], qr2[1]) expected = QuantumCircuit(qr2, qr1) expected.h(qr1[2]) expected.cx(qr1[2], qr1[1]) expected.cx(qr1[1], qr1[0]) expected.cx(qr1[0], qr2[1]) expected.cx(qr2[1], qr2[0]) self.assertEqual(qc.reverse_bits(), expected) def test_reverse_bits_with_overlapped_registers(self): """Test reversing order of bits when registers are overlapped.""" qr1 = QuantumRegister(2, "a") qr2 = QuantumRegister(bits=[qr1[0], qr1[1], Qubit()], name="b") qc = QuantumCircuit(qr1, qr2) qc.h(qr1[0]) qc.cx(qr1[0], qr1[1]) qc.cx(qr1[1], qr2[2]) qr2 = QuantumRegister(bits=[Qubit(), qr1[0], qr1[1]], name="b") expected = QuantumCircuit(qr2, qr1) expected.h(qr1[1]) expected.cx(qr1[1], qr1[0]) expected.cx(qr1[0], qr2[0]) self.assertEqual(qc.reverse_bits(), expected) def test_reverse_bits_with_registerless_bits(self): """Test reversing order of registerless bits.""" q0 = Qubit() q1 = Qubit() c0 = Clbit() c1 = Clbit() qc = QuantumCircuit([q0, q1], [c0, c1]) qc.h(0) qc.cx(0, 1) qc.x(0).c_if(1, True) qc.measure(0, 0) expected = QuantumCircuit([c1, c0], [q1, q0]) expected.h(1) expected.cx(1, 0) expected.x(1).c_if(0, True) expected.measure(1, 1) self.assertEqual(qc.reverse_bits(), expected) def test_reverse_bits_with_registers_and_bits(self): """Test reversing order of bits with registers and registerless bits.""" qr = QuantumRegister(2, "a") q = Qubit() qc = QuantumCircuit(qr, [q]) qc.h(qr[0]) qc.cx(qr[0], qr[1]) qc.cx(qr[1], q) expected = QuantumCircuit([q], qr) expected.h(qr[1]) expected.cx(qr[1], qr[0]) expected.cx(qr[0], q) self.assertEqual(qc.reverse_bits(), expected) def test_reverse_bits_with_mixed_overlapped_registers(self): """Test reversing order of bits with overlapped registers and registerless bits.""" q = Qubit() qr1 = QuantumRegister(bits=[q, Qubit()], name="qr1") qr2 = QuantumRegister(bits=[qr1[1], Qubit()], name="qr2") qc = QuantumCircuit(qr1, qr2, [Qubit()]) qc.h(q) qc.cx(qr1[0], qr1[1]) qc.cx(qr1[1], qr2[1]) qc.cx(2, 3) qr2 = QuantumRegister(2, "qr2") qr1 = QuantumRegister(bits=[qr2[1], q], name="qr1") expected = QuantumCircuit([Qubit()], qr2, qr1) expected.h(qr1[1]) expected.cx(qr1[1], qr1[0]) expected.cx(qr1[0], qr2[0]) expected.cx(1, 0) self.assertEqual(qc.reverse_bits(), expected) def test_cnot_alias(self): """Test that the cnot method alias adds a cx gate.""" qc = QuantumCircuit(2) qc.cnot(0, 1) expected = QuantumCircuit(2) expected.cx(0, 1) self.assertEqual(qc, expected) def test_inverse(self): """Test inverse circuit.""" qr = QuantumRegister(2) qc = QuantumCircuit(qr, global_phase=0.5) qc.h(0) qc.barrier(qr) qc.t(1) expected = QuantumCircuit(qr) expected.tdg(1) expected.barrier(qr) expected.h(0) expected.global_phase = -0.5 self.assertEqual(qc.inverse(), expected) def test_compare_two_equal_circuits(self): """Test to compare that 2 circuits are equal.""" qc1 = QuantumCircuit(2, 2) qc1.h(0) qc2 = QuantumCircuit(2, 2) qc2.h(0) self.assertTrue(qc1 == qc2) def test_compare_two_different_circuits(self): """Test to compare that 2 circuits are different.""" qc1 = QuantumCircuit(2, 2) qc1.h(0) qc2 = QuantumCircuit(2, 2) qc2.x(0) self.assertFalse(qc1 == qc2) def test_compare_circuits_with_single_bit_conditions(self): """Test that circuits with single-bit conditions can be compared correctly.""" qreg = QuantumRegister(1, name="q") creg = ClassicalRegister(1, name="c") qc1 = QuantumCircuit(qreg, creg, [Clbit()]) qc1.x(0).c_if(qc1.cregs[0], 1) qc1.x(0).c_if(qc1.clbits[-1], True) qc2 = QuantumCircuit(qreg, creg, [Clbit()]) qc2.x(0).c_if(qc2.cregs[0], 1) qc2.x(0).c_if(qc2.clbits[-1], True) self.assertEqual(qc1, qc2) # Order of operations transposed. qc1 = QuantumCircuit(qreg, creg, [Clbit()]) qc1.x(0).c_if(qc1.cregs[0], 1) qc1.x(0).c_if(qc1.clbits[-1], True) qc2 = QuantumCircuit(qreg, creg, [Clbit()]) qc2.x(0).c_if(qc2.clbits[-1], True) qc2.x(0).c_if(qc2.cregs[0], 1) self.assertNotEqual(qc1, qc2) # Single-bit condition values not the same. qc1 = QuantumCircuit(qreg, creg, [Clbit()]) qc1.x(0).c_if(qc1.cregs[0], 1) qc1.x(0).c_if(qc1.clbits[-1], True) qc2 = QuantumCircuit(qreg, creg, [Clbit()]) qc2.x(0).c_if(qc2.cregs[0], 1) qc2.x(0).c_if(qc2.clbits[-1], False) self.assertNotEqual(qc1, qc2) def test_compare_a_circuit_with_none(self): """Test to compare that a circuit is different to None.""" qc1 = QuantumCircuit(2, 2) qc1.h(0) qc2 = None self.assertFalse(qc1 == qc2) def test_overlapped_add_bits_and_add_register(self): """Test add registers whose bits have already been added by add_bits.""" qc = QuantumCircuit() for bit_type, reg_type in ( [Qubit, QuantumRegister], [Clbit, ClassicalRegister], [AncillaQubit, AncillaRegister], ): bits = [bit_type() for _ in range(10)] reg = reg_type(bits=bits) qc.add_bits(bits) qc.add_register(reg) self.assertEqual(qc.num_qubits, 20) self.assertEqual(qc.num_clbits, 10) self.assertEqual(qc.num_ancillas, 10) def test_overlapped_add_register_and_add_register(self): """Test add registers whose bits have already been added by add_register.""" qc = QuantumCircuit() for bit_type, reg_type in ( [Qubit, QuantumRegister], [Clbit, ClassicalRegister], [AncillaQubit, AncillaRegister], ): bits = [bit_type() for _ in range(10)] reg1 = reg_type(bits=bits) reg2 = reg_type(bits=bits) qc.add_register(reg1) qc.add_register(reg2) self.assertEqual(qc.num_qubits, 20) self.assertEqual(qc.num_clbits, 10) self.assertEqual(qc.num_ancillas, 10) def test_from_instructions(self): """Test from_instructions method.""" qreg = QuantumRegister(4) creg = ClassicalRegister(3) a, b, c, d = qreg x, y, z = creg circuit_1 = QuantumCircuit(2, 1) circuit_1.x(0) circuit_2 = QuantumCircuit(2, 1) circuit_2.y(0) def instructions(): yield CircuitInstruction(HGate(), [a], []) yield CircuitInstruction(CXGate(), [a, b], []) yield CircuitInstruction(Measure(), [a], [x]) yield CircuitInstruction(Measure(), [b], [y]) yield CircuitInstruction(IfElseOp((z, 1), circuit_1, circuit_2), [c, d], [z]) def instruction_tuples(): yield HGate(), [a], [] yield CXGate(), [a, b], [] yield CircuitInstruction(Measure(), [a], [x]) yield Measure(), [b], [y] yield IfElseOp((z, 1), circuit_1, circuit_2), [c, d], [z] def instruction_tuples_partial(): yield HGate(), [a] yield CXGate(), [a, b], [] yield CircuitInstruction(Measure(), [a], [x]) yield Measure(), [b], [y] yield IfElseOp((z, 1), circuit_1, circuit_2), [c, d], [z] circuit = QuantumCircuit.from_instructions(instructions()) circuit_tuples = QuantumCircuit.from_instructions(instruction_tuples()) circuit_tuples_partial = QuantumCircuit.from_instructions(instruction_tuples_partial()) expected = QuantumCircuit([a, b, c, d], [x, y, z]) for instruction in instructions(): expected.append(instruction.operation, instruction.qubits, instruction.clbits) self.assertEqual(circuit, expected) self.assertEqual(circuit_tuples, expected) self.assertEqual(circuit_tuples_partial, expected) def test_from_instructions_bit_order(self): """Test from_instructions method bit order.""" qreg = QuantumRegister(2) creg = ClassicalRegister(2) a, b = qreg c, d = creg def instructions(): yield CircuitInstruction(HGate(), [b], []) yield CircuitInstruction(CXGate(), [a, b], []) yield CircuitInstruction(Measure(), [b], [d]) yield CircuitInstruction(Measure(), [a], [c]) circuit = QuantumCircuit.from_instructions(instructions()) self.assertEqual(circuit.qubits, [b, a]) self.assertEqual(circuit.clbits, [d, c]) circuit = QuantumCircuit.from_instructions(instructions(), qubits=qreg) self.assertEqual(circuit.qubits, [a, b]) self.assertEqual(circuit.clbits, [d, c]) circuit = QuantumCircuit.from_instructions(instructions(), clbits=creg) self.assertEqual(circuit.qubits, [b, a]) self.assertEqual(circuit.clbits, [c, d]) circuit = QuantumCircuit.from_instructions( instructions(), qubits=iter([a, b]), clbits=[c, d] ) self.assertEqual(circuit.qubits, [a, b]) self.assertEqual(circuit.clbits, [c, d]) def test_from_instructions_metadata(self): """Test from_instructions method passes metadata.""" qreg = QuantumRegister(2) a, b = qreg def instructions(): yield CircuitInstruction(HGate(), [a], []) yield CircuitInstruction(CXGate(), [a, b], []) circuit = QuantumCircuit.from_instructions(instructions(), name="test", global_phase=0.1) expected = QuantumCircuit([a, b], global_phase=0.1) for instruction in instructions(): expected.append(instruction.operation, instruction.qubits, instruction.clbits) self.assertEqual(circuit, expected) self.assertEqual(circuit.name, "test") class TestCircuitPrivateOperations(QiskitTestCase): """Direct tests of some of the private methods of QuantumCircuit. These do not represent functionality that we want to expose to users, but there are some cases where private methods are used internally (similar to "protected" access in .NET or "friend" access in C++), and we want to make sure they work in those cases.""" def test_previous_instruction_in_scope_failures(self): """Test the failure paths of the peek and pop methods for retrieving the most recent instruction in a scope.""" test = QuantumCircuit(1, 1) with self.assertRaisesRegex(CircuitError, r"This circuit contains no instructions\."): test._peek_previous_instruction_in_scope() with self.assertRaisesRegex(CircuitError, r"This circuit contains no instructions\."): test._pop_previous_instruction_in_scope() with test.for_loop(range(2)): with self.assertRaisesRegex(CircuitError, r"This scope contains no instructions\."): test._peek_previous_instruction_in_scope() with self.assertRaisesRegex(CircuitError, r"This scope contains no instructions\."): test._pop_previous_instruction_in_scope() def test_pop_previous_instruction_removes_parameters(self): """Test that the private "pop instruction" method removes parameters from the parameter table if that instruction is the only instance.""" x, y = Parameter("x"), Parameter("y") test = QuantumCircuit(1, 1) test.rx(y, 0) last_instructions = test.u(x, y, 0, 0) self.assertEqual({x, y}, set(test.parameters)) instruction = test._pop_previous_instruction_in_scope() self.assertEqual(list(last_instructions), [instruction]) self.assertEqual({y}, set(test.parameters)) def test_decompose_gate_type(self): """Test decompose specifying gate type.""" circuit = QuantumCircuit(1) circuit.append(SGate(label="s_gate"), [0]) decomposed = circuit.decompose(gates_to_decompose=SGate) self.assertNotIn("s", decomposed.count_ops())
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test Qiskit's inverse gate operation.""" import unittest import numpy as np from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, pulse from qiskit.circuit import Clbit from qiskit.circuit.library import RXGate, RYGate from qiskit.test import QiskitTestCase from qiskit.circuit.exceptions import CircuitError from qiskit.extensions.simulator import Snapshot class TestCircuitProperties(QiskitTestCase): """QuantumCircuit properties tests.""" def test_qarg_numpy_int(self): """Test castable to integer args for QuantumCircuit.""" n = np.int64(12) qc1 = QuantumCircuit(n) self.assertEqual(qc1.num_qubits, 12) self.assertEqual(type(qc1), QuantumCircuit) def test_carg_numpy_int(self): """Test castable to integer cargs for QuantumCircuit.""" n = np.int64(12) c1 = ClassicalRegister(n) qc1 = QuantumCircuit(c1) c_regs = qc1.cregs self.assertEqual(c_regs[0], c1) self.assertEqual(type(qc1), QuantumCircuit) def test_carg_numpy_int_2(self): """Test castable to integer cargs for QuantumCircuit.""" qc1 = QuantumCircuit(12, np.int64(12)) self.assertEqual(len(qc1.clbits), 12) self.assertTrue(all(isinstance(bit, Clbit) for bit in qc1.clbits)) self.assertEqual(type(qc1), QuantumCircuit) def test_qarg_numpy_int_exception(self): """Test attempt to pass non-castable arg to QuantumCircuit.""" self.assertRaises(CircuitError, QuantumCircuit, "string") def test_warning_on_noninteger_float(self): """Test warning when passing non-integer float to QuantumCircuit""" self.assertRaises(CircuitError, QuantumCircuit, 2.2) # but an integer float should pass qc = QuantumCircuit(2.0) self.assertEqual(qc.num_qubits, 2) def test_circuit_depth_empty(self): """Test depth of empty circuity""" q = QuantumRegister(5, "q") qc = QuantumCircuit(q) self.assertEqual(qc.depth(), 0) def test_circuit_depth_no_reg(self): """Test depth of no register circuits""" qc = QuantumCircuit() self.assertEqual(qc.depth(), 0) def test_circuit_depth_meas_only(self): """Test depth of measurement only""" q = QuantumRegister(1, "q") c = ClassicalRegister(1, "c") qc = QuantumCircuit(q, c) qc.measure(q, c) self.assertEqual(qc.depth(), 1) def test_circuit_depth_barrier(self): """Make sure barriers do not add to depth""" # ┌───┐ ░ ┌─┐ # q_0: ┤ H ├──■──────────────────░─┤M├──────────── # ├───┤┌─┴─┐ ░ └╥┘┌─┐ # q_1: ┤ H ├┤ X ├──■─────────────░──╫─┤M├───────── # ├───┤└───┘ │ ┌───┐ ░ ║ └╥┘┌─┐ # q_2: ┤ H ├───────┼──┤ X ├──■───░──╫──╫─┤M├────── # ├───┤ │ └─┬─┘┌─┴─┐ ░ ║ ║ └╥┘┌─┐ # q_3: ┤ H ├───────┼────┼──┤ X ├─░──╫──╫──╫─┤M├─── # ├───┤ ┌─┴─┐ │ └───┘ ░ ║ ║ ║ └╥┘┌─┐ # q_4: ┤ H ├─────┤ X ├──■────────░──╫──╫──╫──╫─┤M├ # └───┘ └───┘ ░ ║ ║ ║ ║ └╥┘ # c: 5/═════════════════════════════╩══╩══╩══╩══╩═ # 0 1 2 3 4 q = QuantumRegister(5, "q") c = ClassicalRegister(5, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.h(q[4]) qc.cx(q[0], q[1]) qc.cx(q[1], q[4]) qc.cx(q[4], q[2]) qc.cx(q[2], q[3]) qc.barrier(q) qc.measure(q, c) self.assertEqual(qc.depth(), 6) def test_circuit_depth_simple(self): """Test depth for simple circuit""" # ┌───┐ # q_0: ┤ H ├──■──────────────────── # └───┘ │ ┌───┐┌─┐ # q_1: ───────┼────────────┤ X ├┤M├ # ┌───┐ │ ┌───┐┌───┐└─┬─┘└╥┘ # q_2: ┤ X ├──┼──┤ X ├┤ X ├──┼───╫─ # └───┘ │ └───┘└───┘ │ ║ # q_3: ───────┼──────────────┼───╫─ # ┌─┴─┐┌───┐ │ ║ # q_4: ─────┤ X ├┤ X ├───────■───╫─ # └───┘└───┘ ║ # c: 1/══════════════════════════╩═ # 0 q = QuantumRegister(5, "q") c = ClassicalRegister(1, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.cx(q[0], q[4]) qc.x(q[2]) qc.x(q[2]) qc.x(q[2]) qc.x(q[4]) qc.cx(q[4], q[1]) qc.measure(q[1], c[0]) self.assertEqual(qc.depth(), 5) def test_circuit_depth_multi_reg(self): """Test depth for multiple registers""" # ┌───┐ # q1_0: ┤ H ├──■───────────────── # ├───┤┌─┴─┐ # q1_1: ┤ H ├┤ X ├──■──────────── # ├───┤└───┘ │ ┌───┐ # q1_2: ┤ H ├───────┼──┤ X ├──■── # ├───┤ │ └─┬─┘┌─┴─┐ # q2_0: ┤ H ├───────┼────┼──┤ X ├ # ├───┤ ┌─┴─┐ │ └───┘ # q2_1: ┤ H ├─────┤ X ├──■─────── # └───┘ └───┘ q1 = QuantumRegister(3, "q1") q2 = QuantumRegister(2, "q2") c = ClassicalRegister(5, "c") qc = QuantumCircuit(q1, q2, c) qc.h(q1[0]) qc.h(q1[1]) qc.h(q1[2]) qc.h(q2[0]) qc.h(q2[1]) qc.cx(q1[0], q1[1]) qc.cx(q1[1], q2[1]) qc.cx(q2[1], q1[2]) qc.cx(q1[2], q2[0]) self.assertEqual(qc.depth(), 5) def test_circuit_depth_3q_gate(self): """Test depth for 3q gate""" # ┌───┐ # q1_0: ┤ H ├──■────■───────────────── # ├───┤ │ ┌─┴─┐ # q1_1: ┤ H ├──┼──┤ X ├──■──────────── # ├───┤ │ └───┘ │ ┌───┐ # q1_2: ┤ H ├──┼─────────┼──┤ X ├──■── # ├───┤┌─┴─┐ │ └─┬─┘┌─┴─┐ # q2_0: ┤ H ├┤ X ├───────┼────┼──┤ X ├ # ├───┤└─┬─┘ ┌─┴─┐ │ └───┘ # q2_1: ┤ H ├──■───────┤ X ├──■─────── # └───┘ └───┘ q1 = QuantumRegister(3, "q1") q2 = QuantumRegister(2, "q2") c = ClassicalRegister(5, "c") qc = QuantumCircuit(q1, q2, c) qc.h(q1[0]) qc.h(q1[1]) qc.h(q1[2]) qc.h(q2[0]) qc.h(q2[1]) qc.ccx(q2[1], q1[0], q2[0]) qc.cx(q1[0], q1[1]) qc.cx(q1[1], q2[1]) qc.cx(q2[1], q1[2]) qc.cx(q1[2], q2[0]) self.assertEqual(qc.depth(), 6) def test_circuit_depth_conditionals1(self): """Test circuit depth for conditional gates #1.""" # ┌───┐ ┌─┐ # q_0: ┤ H ├──■──┤M├───────────────── # ├───┤┌─┴─┐└╥┘┌─┐ # q_1: ┤ H ├┤ X ├─╫─┤M├────────────── # ├───┤└───┘ ║ └╥┘ ┌───┐ # q_2: ┤ H ├──■───╫──╫──┤ H ├──────── # ├───┤┌─┴─┐ ║ ║ └─╥─┘ ┌───┐ # q_3: ┤ H ├┤ X ├─╫──╫────╫────┤ H ├─ # └───┘└───┘ ║ ║ ║ └─╥─┘ # ║ ║ ┌──╨──┐┌──╨──┐ # c: 4/═══════════╩══╩═╡ 0x2 ╞╡ 0x4 ╞ # 0 1 └─────┘└─────┘ size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.cx(q[0], q[1]) qc.cx(q[2], q[3]) qc.measure(q[0], c[0]) qc.measure(q[1], c[1]) qc.h(q[2]).c_if(c, 2) qc.h(q[3]).c_if(c, 4) self.assertEqual(qc.depth(), 5) def test_circuit_depth_conditionals2(self): """Test circuit depth for conditional gates #2.""" # ┌───┐ ┌─┐┌─┐ # q_0: ┤ H ├──■──┤M├┤M├────────────── # ├───┤┌─┴─┐└╥┘└╥┘ # q_1: ┤ H ├┤ X ├─╫──╫─────────────── # ├───┤└───┘ ║ ║ ┌───┐ # q_2: ┤ H ├──■───╫──╫──┤ H ├──────── # ├───┤┌─┴─┐ ║ ║ └─╥─┘ ┌───┐ # q_3: ┤ H ├┤ X ├─╫──╫────╫────┤ H ├─ # └───┘└───┘ ║ ║ ║ └─╥─┘ # ║ ║ ┌──╨──┐┌──╨──┐ # c: 4/═══════════╩══╩═╡ 0x2 ╞╡ 0x4 ╞ # 0 0 └─────┘└─────┘ size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.cx(q[0], q[1]) qc.cx(q[2], q[3]) qc.measure(q[0], c[0]) qc.measure(q[0], c[0]) qc.h(q[2]).c_if(c, 2) qc.h(q[3]).c_if(c, 4) self.assertEqual(qc.depth(), 6) def test_circuit_depth_conditionals3(self): """Test circuit depth for conditional gates #3.""" # ┌───┐┌─┐ # q_0: ┤ H ├┤M├───■──────────── # ├───┤└╥┘ │ ┌─┐ # q_1: ┤ H ├─╫────┼───┤M├────── # ├───┤ ║ │ └╥┘┌─┐ # q_2: ┤ H ├─╫────┼────╫─┤M├─── # ├───┤ ║ ┌─┴─┐ ║ └╥┘┌─┐ # q_3: ┤ H ├─╫──┤ X ├──╫──╫─┤M├ # └───┘ ║ └─╥─┘ ║ ║ └╥┘ # ║ ┌──╨──┐ ║ ║ ║ # c: 4/══════╩═╡ 0x2 ╞═╩══╩══╩═ # 0 └─────┘ 1 2 3 size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.measure(q[0], c[0]) qc.cx(q[0], q[3]).c_if(c, 2) qc.measure(q[1], c[1]) qc.measure(q[2], c[2]) qc.measure(q[3], c[3]) self.assertEqual(qc.depth(), 4) def test_circuit_depth_bit_conditionals1(self): """Test circuit depth for single bit conditional gates #1.""" # ┌───┐┌─┐ # q_0: ┤ H ├┤M├───────────────────────── # ├───┤└╥┘ ┌───┐ # q_1: ┤ H ├─╫───────┤ H ├────────────── # ├───┤ ║ ┌─┐ └─╥─┘ # q_2: ┤ H ├─╫─┤M├─────╫──────────────── # ├───┤ ║ └╥┘ ║ ┌───┐ # q_3: ┤ H ├─╫──╫──────╫────────┤ H ├─── # └───┘ ║ ║ ║ └─╥─┘ # ║ ║ ┌────╨────┐┌────╨────┐ # c: 4/══════╩══╩═╡ c_0=0x1 ╞╡ c_2=0x0 ╞ # 0 2 └─────────┘└─────────┘ size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.measure(q[0], c[0]) qc.measure(q[2], c[2]) qc.h(q[1]).c_if(c[0], True) qc.h(q[3]).c_if(c[2], False) self.assertEqual(qc.depth(), 3) def test_circuit_depth_bit_conditionals2(self): """Test circuit depth for single bit conditional gates #2.""" # ┌───┐┌─┐ » # q_0: ┤ H ├┤M├──────────────────────────────■─────────────────────■─────» # ├───┤└╥┘ ┌───┐ ┌─┴─┐ │ » # q_1: ┤ H ├─╫───────┤ H ├─────────────────┤ X ├───────────────────┼─────» # ├───┤ ║ ┌─┐ └─╥─┘ └─╥─┘ ┌─┴─┐ » # q_2: ┤ H ├─╫─┤M├─────╫─────────────────────╫──────────■────────┤ H ├───» # ├───┤ ║ └╥┘ ║ ┌───┐ ║ ┌─┴─┐ └─╥─┘ » # q_3: ┤ H ├─╫──╫──────╫────────┤ H ├────────╫────────┤ X ├────────╫─────» # └───┘ ║ ║ ║ └─╥─┘ ║ └─╥─┘ ║ » # ║ ║ ┌────╨────┐┌────╨────┐┌────╨────┐┌────╨────┐┌────╨────┐» # c: 4/══════╩══╩═╡ c_1=0x1 ╞╡ c_3=0x1 ╞╡ c_0=0x0 ╞╡ c_2=0x0 ╞╡ c_1=0x1 ╞» # 0 2 └─────────┘└─────────┘└─────────┘└─────────┘└─────────┘» # « # «q_0: ─────────── # « # «q_1: ─────■───── # « │ # «q_2: ─────┼───── # « ┌─┴─┐ # «q_3: ───┤ H ├─── # « └─╥─┘ # « ┌────╨────┐ # «c: 4/╡ c_3=0x1 ╞ # « └─────────┘ size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.measure(q[0], c[0]) qc.measure(q[2], c[2]) qc.h(q[1]).c_if(c[1], True) qc.h(q[3]).c_if(c[3], True) qc.cx(0, 1).c_if(c[0], False) qc.cx(2, 3).c_if(c[2], False) qc.ch(0, 2).c_if(c[1], True) qc.ch(1, 3).c_if(c[3], True) self.assertEqual(qc.depth(), 4) def test_circuit_depth_bit_conditionals3(self): """Test circuit depth for single bit conditional gates #3.""" # ┌───┐┌─┐ # q_0: ┤ H ├┤M├────────────────────────────────────── # ├───┤└╥┘ ┌───┐ ┌─┐ # q_1: ┤ H ├─╫────┤ H ├─────────────────────┤M├────── # ├───┤ ║ └─╥─┘ ┌───┐ └╥┘┌─┐ # q_2: ┤ H ├─╫──────╫──────┤ H ├─────────────╫─┤M├─── # ├───┤ ║ ║ └─╥─┘ ┌───┐ ║ └╥┘┌─┐ # q_3: ┤ H ├─╫──────╫────────╫──────┤ H ├────╫──╫─┤M├ # └───┘ ║ ║ ║ └─╥─┘ ║ ║ └╥┘ # ║ ┌────╨────┐┌──╨──┐┌────╨────┐ ║ ║ ║ # c: 4/══════╩═╡ c_0=0x1 ╞╡ 0x2 ╞╡ c_3=0x1 ╞═╩══╩══╩═ # 0 └─────────┘└─────┘└─────────┘ 1 2 3 size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.measure(q[0], c[0]) qc.h(1).c_if(c[0], True) qc.h(q[2]).c_if(c, 2) qc.h(3).c_if(c[3], True) qc.measure(q[1], c[1]) qc.measure(q[2], c[2]) qc.measure(q[3], c[3]) self.assertEqual(qc.depth(), 6) def test_circuit_depth_measurements1(self): """Test circuit depth for measurements #1.""" # ┌───┐┌─┐ # q_0: ┤ H ├┤M├───────── # ├───┤└╥┘┌─┐ # q_1: ┤ H ├─╫─┤M├────── # ├───┤ ║ └╥┘┌─┐ # q_2: ┤ H ├─╫──╫─┤M├─── # ├───┤ ║ ║ └╥┘┌─┐ # q_3: ┤ H ├─╫──╫──╫─┤M├ # └───┘ ║ ║ ║ └╥┘ # c: 4/══════╩══╩══╩══╩═ # 0 1 2 3 size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.measure(q[0], c[0]) qc.measure(q[1], c[1]) qc.measure(q[2], c[2]) qc.measure(q[3], c[3]) self.assertEqual(qc.depth(), 2) def test_circuit_depth_measurements2(self): """Test circuit depth for measurements #2.""" # ┌───┐┌─┐┌─┐┌─┐┌─┐ # q_0: ┤ H ├┤M├┤M├┤M├┤M├ # ├───┤└╥┘└╥┘└╥┘└╥┘ # q_1: ┤ H ├─╫──╫──╫──╫─ # ├───┤ ║ ║ ║ ║ # q_2: ┤ H ├─╫──╫──╫──╫─ # ├───┤ ║ ║ ║ ║ # q_3: ┤ H ├─╫──╫──╫──╫─ # └───┘ ║ ║ ║ ║ # c: 4/══════╩══╩══╩══╩═ # 0 1 2 3 size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.measure(q[0], c[0]) qc.measure(q[0], c[1]) qc.measure(q[0], c[2]) qc.measure(q[0], c[3]) self.assertEqual(qc.depth(), 5) def test_circuit_depth_measurements3(self): """Test circuit depth for measurements #3.""" # ┌───┐┌─┐ # q_0: ┤ H ├┤M├───────── # ├───┤└╥┘┌─┐ # q_1: ┤ H ├─╫─┤M├────── # ├───┤ ║ └╥┘┌─┐ # q_2: ┤ H ├─╫──╫─┤M├─── # ├───┤ ║ ║ └╥┘┌─┐ # q_3: ┤ H ├─╫──╫──╫─┤M├ # └───┘ ║ ║ ║ └╥┘ # c: 4/══════╩══╩══╩══╩═ # 0 0 0 0 size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.measure(q[0], c[0]) qc.measure(q[1], c[0]) qc.measure(q[2], c[0]) qc.measure(q[3], c[0]) self.assertEqual(qc.depth(), 5) def test_circuit_depth_barriers1(self): """Test circuit depth for barriers #1.""" # ┌───┐ ░ # q_0: ┤ H ├──■───░─────────── # └───┘┌─┴─┐ ░ # q_1: ─────┤ X ├─░─────────── # └───┘ ░ ┌───┐ # q_2: ───────────░─┤ H ├──■── # ░ └───┘┌─┴─┐ # q_3: ───────────░──────┤ X ├ # ░ └───┘ q = QuantumRegister(4, "q") c = ClassicalRegister(4, "c") circ = QuantumCircuit(q, c) circ.h(0) circ.cx(0, 1) circ.barrier(q) circ.h(2) circ.cx(2, 3) self.assertEqual(circ.depth(), 4) def test_circuit_depth_barriers2(self): """Test circuit depth for barriers #2.""" # ┌───┐ ░ ░ ░ # q_0: ┤ H ├─░───■───░───────░────── # └───┘ ░ ┌─┴─┐ ░ ░ # q_1: ──────░─┤ X ├─░───────░────── # ░ └───┘ ░ ┌───┐ ░ # q_2: ──────░───────░─┤ H ├─░───■── # ░ ░ └───┘ ░ ┌─┴─┐ # q_3: ──────░───────░───────░─┤ X ├ # ░ ░ ░ └───┘ q = QuantumRegister(4, "q") c = ClassicalRegister(4, "c") circ = QuantumCircuit(q, c) circ.h(0) circ.barrier(q) circ.cx(0, 1) circ.barrier(q) circ.h(2) circ.barrier(q) circ.cx(2, 3) self.assertEqual(circ.depth(), 4) def test_circuit_depth_barriers3(self): """Test circuit depth for barriers #3.""" # ┌───┐ ░ ░ ░ ░ ░ # q_0: ┤ H ├─░───■───░──░──░───────░────── # └───┘ ░ ┌─┴─┐ ░ ░ ░ ░ # q_1: ──────░─┤ X ├─░──░──░───────░────── # ░ └───┘ ░ ░ ░ ┌───┐ ░ # q_2: ──────░───────░──░──░─┤ H ├─░───■── # ░ ░ ░ ░ └───┘ ░ ┌─┴─┐ # q_3: ──────░───────░──░──░───────░─┤ X ├ # ░ ░ ░ ░ ░ └───┘ q = QuantumRegister(4, "q") c = ClassicalRegister(4, "c") circ = QuantumCircuit(q, c) circ.h(0) circ.barrier(q) circ.cx(0, 1) circ.barrier(q) circ.barrier(q) circ.barrier(q) circ.h(2) circ.barrier(q) circ.cx(2, 3) self.assertEqual(circ.depth(), 4) def test_circuit_depth_snap1(self): """Test circuit depth for snapshots #1.""" # ┌───┐ ░ # q_0: ┤ H ├──■───░─────────── # └───┘┌─┴─┐ ░ # q_1: ─────┤ X ├─░─────────── # └───┘ ░ ┌───┐ # q_2: ───────────░─┤ H ├──■── # ░ └───┘┌─┴─┐ # q_3: ───────────░──────┤ X ├ # ░ └───┘ q = QuantumRegister(4, "q") c = ClassicalRegister(4, "c") circ = QuantumCircuit(q, c) circ.h(0) circ.cx(0, 1) circ.append(Snapshot("snap", num_qubits=4), [0, 1, 2, 3]) circ.h(2) circ.cx(2, 3) self.assertEqual(circ.depth(), 4) def test_circuit_depth_snap2(self): """Test circuit depth for snapshots #2.""" # ┌───┐ ░ ░ ░ # q_0: ┤ H ├─░───■───░───────░────── # └───┘ ░ ┌─┴─┐ ░ ░ # q_1: ──────░─┤ X ├─░───────░────── # ░ └───┘ ░ ┌───┐ ░ # q_2: ──────░───────░─┤ H ├─░───■── # ░ ░ └───┘ ░ ┌─┴─┐ # q_3: ──────░───────░───────░─┤ X ├ # ░ ░ ░ └───┘ q = QuantumRegister(4, "q") c = ClassicalRegister(4, "c") circ = QuantumCircuit(q, c) circ.h(0) circ.append(Snapshot("snap0", num_qubits=4), [0, 1, 2, 3]) circ.cx(0, 1) circ.append(Snapshot("snap1", num_qubits=4), [0, 1, 2, 3]) circ.h(2) circ.append(Snapshot("snap2", num_qubits=4), [0, 1, 2, 3]) circ.cx(2, 3) self.assertEqual(circ.depth(), 4) def test_circuit_depth_snap3(self): """Test circuit depth for snapshots #3.""" # ┌───┐ ░ ░ # q_0: ┤ H ├──■───░──░─────────── # └───┘┌─┴─┐ ░ ░ # q_1: ─────┤ X ├─░──░─────────── # └───┘ ░ ░ ┌───┐ # q_2: ───────────░──░─┤ H ├──■── # ░ ░ └───┘┌─┴─┐ # q_3: ───────────░──░──────┤ X ├ # ░ ░ └───┘ q = QuantumRegister(4, "q") c = ClassicalRegister(4, "c") circ = QuantumCircuit(q, c) circ.h(0) circ.cx(0, 1) circ.append(Snapshot("snap0", num_qubits=4), [0, 1, 2, 3]) circ.append(Snapshot("snap1", num_qubits=4), [0, 1, 2, 3]) circ.h(2) circ.cx(2, 3) self.assertEqual(circ.depth(), 4) def test_circuit_depth_2qubit(self): """Test finding depth of two-qubit gates only.""" # ┌───┐ # q_0: ┤ H ├──■─────────────────── # └───┘┌─┴─┐┌─────────┐ ┌─┐ # q_1: ─────┤ X ├┤ Rz(0.1) ├─■─┤M├ # ┌───┐└───┘└─────────┘ │ └╥┘ # q_2: ┤ H ├──■──────────────┼──╫─ # └───┘┌─┴─┐ │ ║ # q_3: ─────┤ X ├────────────■──╫─ # └───┘ ║ # c: 1/═════════════════════════╩═ # 0 circ = QuantumCircuit(4, 1) circ.h(0) circ.cx(0, 1) circ.h(2) circ.cx(2, 3) circ.rz(0.1, 1) circ.cz(1, 3) circ.measure(1, 0) self.assertEqual(circ.depth(lambda x: x.operation.num_qubits == 2), 2) def test_circuit_depth_multiqubit_or_conditional(self): """Test finding depth of multi-qubit or conditional gates.""" # ┌───┐ ┌───┐ # q_0: ┤ H ├──■───────────────────────────┤ X ├─── # └───┘ │ ┌─────────┐ ┌─┐ └─╥─┘ # q_1: ───────■──┤ Rz(0.1) ├──────■─┤M├─────╫───── # ┌─┴─┐└──┬───┬──┘ │ └╥┘ ║ # q_2: ─────┤ X ├───┤ H ├─────■───┼──╫──────╫───── # └───┘ └───┘ ┌─┴─┐ │ ║ ║ # q_3: ─────────────────────┤ X ├─■──╫──────╫───── # └───┘ ║ ┌────╨────┐ # c: 1/══════════════════════════════╩═╡ c_0 = T ╞ # 0 └─────────┘ circ = QuantumCircuit(4, 1) circ.h(0) circ.ccx(0, 1, 2) circ.h(2) circ.cx(2, 3) circ.rz(0.1, 1) circ.cz(1, 3) circ.measure(1, 0) circ.x(0).c_if(0, 1) self.assertEqual( circ.depth(lambda x: x.operation.num_qubits >= 2 or x.operation.condition is not None), 4, ) def test_circuit_depth_first_qubit(self): """Test finding depth of gates touching q0 only.""" # ┌───┐ ┌───┐ # q_0: ┤ H ├──■─────┤ T ├───────── # └───┘┌─┴─┐┌──┴───┴──┐ ┌─┐ # q_1: ─────┤ X ├┤ Rz(0.1) ├─■─┤M├ # ┌───┐└───┘└─────────┘ │ └╥┘ # q_2: ┤ H ├──■──────────────┼──╫─ # └───┘┌─┴─┐ │ ║ # q_3: ─────┤ X ├────────────■──╫─ # └───┘ ║ # c: 1/═════════════════════════╩═ # 0 circ = QuantumCircuit(4, 1) circ.h(0) circ.cx(0, 1) circ.t(0) circ.h(2) circ.cx(2, 3) circ.rz(0.1, 1) circ.cz(1, 3) circ.measure(1, 0) self.assertEqual(circ.depth(lambda x: circ.qubits[0] in x.qubits), 3) def test_circuit_size_empty(self): """Circuit.size should return 0 for an empty circuit.""" size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) self.assertEqual(qc.size(), 0) def test_circuit_size_single_qubit_gates(self): """Circuit.size should increment for each added single qubit gate.""" size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) self.assertEqual(qc.size(), 1) qc.h(q[1]) self.assertEqual(qc.size(), 2) def test_circuit_size_2qubit(self): """Circuit.size of only 2-qubit gates.""" size = 3 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.cx(q[0], q[1]) qc.rz(0.1, q[1]) qc.rzz(0.1, q[1], q[2]) self.assertEqual(qc.size(lambda x: x.operation.num_qubits == 2), 2) def test_circuit_size_ignores_barriers_snapshots(self): """Circuit.size should not count barriers or snapshots.""" q = QuantumRegister(4, "q") c = ClassicalRegister(4, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.cx(q[0], q[1]) self.assertEqual(qc.size(), 2) qc.barrier(q) self.assertEqual(qc.size(), 2) qc.append(Snapshot("snapshot_label", num_qubits=4), [0, 1, 2, 3]) self.assertEqual(qc.size(), 2) def test_circuit_count_ops(self): """Test circuit count ops.""" q = QuantumRegister(6, "q") qc = QuantumCircuit(q) qc.h(q) qc.x(q[1]) qc.y(q[2:4]) qc.z(q[3:]) result = qc.count_ops() expected = {"h": 6, "z": 3, "y": 2, "x": 1} self.assertIsInstance(result, dict) self.assertEqual(expected, result) def test_circuit_nonlocal_gates(self): """Test num_nonlocal_gates.""" # ┌───┐ ┌────────┐ # q_0: ┤ H ├───────────────────┤0 ├ # ├───┤ ┌───┐ │ │ # q_1: ┤ H ├───┤ X ├─────────■─┤ ├ # ├───┤ └───┘ │ │ │ # q_2: ┤ H ├─────■───────────X─┤ Iswap ├ # ├───┤ │ ┌───┐ │ │ │ # q_3: ┤ H ├─────┼─────┤ Z ├─X─┤ ├ # ├───┤┌────┴────┐├───┤ │ │ # q_4: ┤ H ├┤ Ry(0.1) ├┤ Z ├───┤1 ├ # ├───┤└──┬───┬──┘└───┘ └───╥────┘ # q_5: ┤ H ├───┤ Z ├───────────────╫───── # └───┘ └───┘ ┌──╨──┐ # c: 2/═════════════════════════╡ 0x2 ╞══ # └─────┘ q = QuantumRegister(6, "q") c = ClassicalRegister(2, "c") qc = QuantumCircuit(q, c) qc.h(q) qc.x(q[1]) qc.cry(0.1, q[2], q[4]) qc.z(q[3:]) qc.cswap(q[1], q[2], q[3]) qc.iswap(q[0], q[4]).c_if(c, 2) result = qc.num_nonlocal_gates() expected = 3 self.assertEqual(expected, result) def test_circuit_nonlocal_gates_no_instruction(self): """Verify num_nunlocal_gates does not include barriers.""" # ref: https://github.com/Qiskit/qiskit-terra/issues/4500 n = 3 qc = QuantumCircuit(n) qc.h(range(n)) qc.barrier() self.assertEqual(qc.num_nonlocal_gates(), 0) def test_circuit_connected_components_empty(self): """Verify num_connected_components is width for empty""" q = QuantumRegister(7, "q") qc = QuantumCircuit(q) self.assertEqual(7, qc.num_connected_components()) def test_circuit_connected_components_multi_reg(self): """Test tensor factors works over multi registers""" # ┌───┐ # q1_0: ┤ H ├──■───────────────── # ├───┤┌─┴─┐ # q1_1: ┤ H ├┤ X ├──■──────────── # ├───┤└───┘ │ ┌───┐ # q1_2: ┤ H ├───────┼──┤ X ├──■── # ├───┤ │ └─┬─┘┌─┴─┐ # q2_0: ┤ H ├───────┼────┼──┤ X ├ # ├───┤ ┌─┴─┐ │ └───┘ # q2_1: ┤ H ├─────┤ X ├──■─────── # └───┘ └───┘ q1 = QuantumRegister(3, "q1") q2 = QuantumRegister(2, "q2") qc = QuantumCircuit(q1, q2) qc.h(q1[0]) qc.h(q1[1]) qc.h(q1[2]) qc.h(q2[0]) qc.h(q2[1]) qc.cx(q1[0], q1[1]) qc.cx(q1[1], q2[1]) qc.cx(q2[1], q1[2]) qc.cx(q1[2], q2[0]) self.assertEqual(qc.num_connected_components(), 1) def test_circuit_connected_components_multi_reg2(self): """Test tensor factors works over multi registers #2.""" # q1_0: ──■──────────── # │ # q1_1: ──┼─────────■── # │ ┌───┐ │ # q1_2: ──┼──┤ X ├──┼── # │ └─┬─┘┌─┴─┐ # q2_0: ──┼────■──┤ X ├ # ┌─┴─┐ └───┘ # q2_1: ┤ X ├────────── # └───┘ q1 = QuantumRegister(3, "q1") q2 = QuantumRegister(2, "q2") qc = QuantumCircuit(q1, q2) qc.cx(q1[0], q2[1]) qc.cx(q2[0], q1[2]) qc.cx(q1[1], q2[0]) self.assertEqual(qc.num_connected_components(), 2) def test_circuit_connected_components_disconnected(self): """Test tensor factors works with 2q subspaces.""" # q1_0: ──■────────────────────── # │ # q1_1: ──┼────■───────────────── # │ │ # q1_2: ──┼────┼────■──────────── # │ │ │ # q1_3: ──┼────┼────┼────■─────── # │ │ │ │ # q1_4: ──┼────┼────┼────┼────■── # │ │ │ │ ┌─┴─┐ # q2_0: ──┼────┼────┼────┼──┤ X ├ # │ │ │ ┌─┴─┐└───┘ # q2_1: ──┼────┼────┼──┤ X ├───── # │ │ ┌─┴─┐└───┘ # q2_2: ──┼────┼──┤ X ├────────── # │ ┌─┴─┐└───┘ # q2_3: ──┼──┤ X ├─────────────── # ┌─┴─┐└───┘ # q2_4: ┤ X ├──────────────────── # └───┘ q1 = QuantumRegister(5, "q1") q2 = QuantumRegister(5, "q2") qc = QuantumCircuit(q1, q2) qc.cx(q1[0], q2[4]) qc.cx(q1[1], q2[3]) qc.cx(q1[2], q2[2]) qc.cx(q1[3], q2[1]) qc.cx(q1[4], q2[0]) self.assertEqual(qc.num_connected_components(), 5) def test_circuit_connected_components_with_clbits(self): """Test tensor components with classical register.""" # ┌───┐┌─┐ # q_0: ┤ H ├┤M├───────── # ├───┤└╥┘┌─┐ # q_1: ┤ H ├─╫─┤M├────── # ├───┤ ║ └╥┘┌─┐ # q_2: ┤ H ├─╫──╫─┤M├─── # ├───┤ ║ ║ └╥┘┌─┐ # q_3: ┤ H ├─╫──╫──╫─┤M├ # └───┘ ║ ║ ║ └╥┘ # c: 4/══════╩══╩══╩══╩═ # 0 1 2 3 size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.measure(q[0], c[0]) qc.measure(q[1], c[1]) qc.measure(q[2], c[2]) qc.measure(q[3], c[3]) self.assertEqual(qc.num_connected_components(), 4) def test_circuit_connected_components_with_cond(self): """Test tensor components with one conditional gate.""" # ┌───┐┌─┐ # q_0: ┤ H ├┤M├───■──────────── # ├───┤└╥┘ │ ┌─┐ # q_1: ┤ H ├─╫────┼───┤M├────── # ├───┤ ║ │ └╥┘┌─┐ # q_2: ┤ H ├─╫────┼────╫─┤M├─── # ├───┤ ║ ┌─┴─┐ ║ └╥┘┌─┐ # q_3: ┤ H ├─╫──┤ X ├──╫──╫─┤M├ # └───┘ ║ └─╥─┘ ║ ║ └╥┘ # ║ ┌──╨──┐ ║ ║ ║ # c: 4/══════╩═╡ 0x2 ╞═╩══╩══╩═ # 0 └─────┘ 1 2 3 size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.measure(q[0], c[0]) qc.cx(q[0], q[3]).c_if(c, 2) qc.measure(q[1], c[1]) qc.measure(q[2], c[2]) qc.measure(q[3], c[3]) self.assertEqual(qc.num_connected_components(), 1) def test_circuit_connected_components_with_cond2(self): """Test tensor components with two conditional gates.""" # ┌───┐ ┌───┐ # q_0: ┤ H ├─┤ H ├──────── # ├───┤ └─╥─┘ # q_1: ┤ H ├───╫──────■─── # ├───┤ ║ ┌─┴─┐ # q_2: ┤ H ├───╫────┤ X ├─ # ├───┤ ║ └─╥─┘ # q_3: ┤ H ├───╫──────╫─── # └───┘┌──╨──┐┌──╨──┐ # c: 8/═════╡ 0x0 ╞╡ 0x4 ╞ # └─────┘└─────┘ size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(2 * size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.h(0).c_if(c, 0) qc.cx(1, 2).c_if(c, 4) self.assertEqual(qc.num_connected_components(), 2) def test_circuit_connected_components_with_cond3(self): """Test tensor components with three conditional gates and measurements.""" # ┌───┐┌─┐ ┌───┐ # q0_0: ┤ H ├┤M├─┤ H ├────────────────── # ├───┤└╥┘ └─╥─┘ # q0_1: ┤ H ├─╫────╫──────■───────────── # ├───┤ ║ ║ ┌─┴─┐ ┌─┐ # q0_2: ┤ H ├─╫────╫────┤ X ├─┤M├─────── # ├───┤ ║ ║ └─╥─┘ └╥┘ ┌───┐ # q0_3: ┤ H ├─╫────╫──────╫────╫──┤ X ├─ # └───┘ ║ ║ ║ ║ └─╥─┘ # ║ ┌──╨──┐┌──╨──┐ ║ ┌──╨──┐ # c0: 4/══════╩═╡ 0x0 ╞╡ 0x1 ╞═╩═╡ 0x2 ╞ # 0 └─────┘└─────┘ 2 └─────┘ size = 4 q = QuantumRegister(size) c = ClassicalRegister(size) qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.measure(q[0], c[0]) qc.h(q[0]).c_if(c, 0) qc.cx(q[1], q[2]).c_if(c, 1) qc.measure(q[2], c[2]) qc.x(q[3]).c_if(c, 2) self.assertEqual(qc.num_connected_components(), 1) def test_circuit_connected_components_with_bit_cond(self): """Test tensor components with one single bit conditional gate.""" # ┌───┐┌─┐ # q_0: ┤ H ├┤M├───────────■──────── # ├───┤└╥┘┌─┐ │ # q_1: ┤ H ├─╫─┤M├────────┼──────── # ├───┤ ║ └╥┘┌─┐ │ # q_2: ┤ H ├─╫──╫─┤M├─────┼──────── # ├───┤ ║ ║ └╥┘ ┌─┴─┐ ┌─┐ # q_3: ┤ H ├─╫──╫──╫────┤ X ├───┤M├ # └───┘ ║ ║ ║ └─╥─┘ └╥┘ # ║ ║ ║ ┌────╨────┐ ║ # c: 4/══════╩══╩══╩═╡ c_0=0x1 ╞═╩═ # 0 1 2 └─────────┘ 3 size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.measure(q[0], c[0]) qc.cx(q[0], q[3]).c_if(c[0], True) qc.measure(q[1], c[1]) qc.measure(q[2], c[2]) qc.measure(q[3], c[3]) self.assertEqual(qc.num_connected_components(), 3) def test_circuit_connected_components_with_bit_cond2(self): """Test tensor components with two bit conditional gates.""" # ┌───┐ ┌───┐ ┌───┐ # q_0: ┤ H ├───┤ H ├─────────────────┤ X ├─── # ├───┤ └─╥─┘ └─┬─┘ # q_1: ┤ H ├─────╫─────────────────────■───── # ├───┤ ║ ║ # q_2: ┤ H ├─────╫──────────■──────────╫───── # ├───┤ ║ │ ║ # q_3: ┤ H ├─────╫──────────■──────────╫───── # └───┘┌────╨────┐┌────╨────┐┌────╨────┐ # c: 6/═════╡ c_1=0x1 ╞╡ c_0=0x1 ╞╡ c_4=0x0 ╞ # └─────────┘└─────────┘└─────────┘ size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size + 2, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.h(0).c_if(c[1], True) qc.cx(1, 0).c_if(c[4], False) qc.cz(2, 3).c_if(c[0], True) self.assertEqual(qc.num_connected_components(), 5) def test_circuit_connected_components_with_bit_cond3(self): """Test tensor components with register and bit conditional gates.""" # ┌───┐ ┌───┐ # q0_0: ┤ H ├───┤ H ├─────────────────────── # ├───┤ └─╥─┘ # q0_1: ┤ H ├─────╫─────────■─────────────── # ├───┤ ║ ┌─┴─┐ # q0_2: ┤ H ├─────╫───────┤ X ├───────────── # ├───┤ ║ └─╥─┘ ┌───┐ # q0_3: ┤ H ├─────╫─────────╫──────┤ X ├──── # └───┘ ║ ║ └─╥─┘ # ┌────╨─────┐┌──╨──┐┌────╨─────┐ # c0: 4/═════╡ c0_0=0x1 ╞╡ 0x1 ╞╡ c0_2=0x1 ╞ # └──────────┘└─────┘└──────────┘ size = 4 q = QuantumRegister(size) c = ClassicalRegister(size) qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.h(q[0]).c_if(c[0], True) qc.cx(q[1], q[2]).c_if(c, 1) qc.x(q[3]).c_if(c[2], True) self.assertEqual(qc.num_connected_components(), 1) def test_circuit_unitary_factors1(self): """Test unitary factors empty circuit.""" size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) self.assertEqual(qc.num_unitary_factors(), 4) def test_circuit_unitary_factors2(self): """Test unitary factors multi qregs""" q1 = QuantumRegister(2, "q1") q2 = QuantumRegister(2, "q2") c = ClassicalRegister(4, "c") qc = QuantumCircuit(q1, q2, c) self.assertEqual(qc.num_unitary_factors(), 4) def test_circuit_unitary_factors3(self): """Test unitary factors measurements and conditionals.""" # ┌───┐ ┌─┐ # q_0: ┤ H ├────────■──────────■────■──────────■──┤M├─── # ├───┤ │ │ │ ┌─┐ │ └╥┘ # q_1: ┤ H ├──■─────┼─────■────┼────┼──┤M├─────┼───╫──── # ├───┤┌─┴─┐ │ ┌─┴─┐ │ │ └╥┘┌─┐ │ ║ # q_2: ┤ H ├┤ X ├───┼───┤ X ├──┼────┼───╫─┤M├──┼───╫──── # ├───┤└───┘ ┌─┴─┐ └───┘┌─┴─┐┌─┴─┐ ║ └╥┘┌─┴─┐ ║ ┌─┐ # q_3: ┤ H ├──────┤ X ├──────┤ X ├┤ X ├─╫──╫─┤ X ├─╫─┤M├ # └───┘ └─╥─┘ └───┘└───┘ ║ ║ └───┘ ║ └╥┘ # ┌──╨──┐ ║ ║ ║ ║ # c: 4/══════════╡ 0x2 ╞════════════════╩══╩═══════╩══╩═ # └─────┘ 1 2 0 3 size = 4 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.cx(q[1], q[2]) qc.cx(q[1], q[2]) qc.cx(q[0], q[3]).c_if(c, 2) qc.cx(q[0], q[3]) qc.cx(q[0], q[3]) qc.cx(q[0], q[3]) qc.measure(q[0], c[0]) qc.measure(q[1], c[1]) qc.measure(q[2], c[2]) qc.measure(q[3], c[3]) self.assertEqual(qc.num_unitary_factors(), 2) def test_circuit_unitary_factors4(self): """Test unitary factors measurements go to same cbit.""" # ┌───┐┌─┐ # q_0: ┤ H ├┤M├───────── # ├───┤└╥┘┌─┐ # q_1: ┤ H ├─╫─┤M├────── # ├───┤ ║ └╥┘┌─┐ # q_2: ┤ H ├─╫──╫─┤M├─── # ├───┤ ║ ║ └╥┘┌─┐ # q_3: ┤ H ├─╫──╫──╫─┤M├ # └───┘ ║ ║ ║ └╥┘ # q_4: ──────╫──╫──╫──╫─ # ║ ║ ║ ║ # c: 5/══════╩══╩══╩══╩═ # 0 0 0 0 size = 5 q = QuantumRegister(size, "q") c = ClassicalRegister(size, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.h(q[3]) qc.measure(q[0], c[0]) qc.measure(q[1], c[0]) qc.measure(q[2], c[0]) qc.measure(q[3], c[0]) self.assertEqual(qc.num_unitary_factors(), 5) def test_num_qubits_qubitless_circuit(self): """Check output in absence of qubits.""" c_reg = ClassicalRegister(3) circ = QuantumCircuit(c_reg) self.assertEqual(circ.num_qubits, 0) def test_num_qubits_qubitfull_circuit(self): """Check output in presence of qubits""" q_reg = QuantumRegister(4) c_reg = ClassicalRegister(3) circ = QuantumCircuit(q_reg, c_reg) self.assertEqual(circ.num_qubits, 4) def test_num_qubits_registerless_circuit(self): """Check output for circuits with direct argument for qubits.""" circ = QuantumCircuit(5) self.assertEqual(circ.num_qubits, 5) def test_num_qubits_multiple_register_circuit(self): """Check output for circuits with multiple quantum registers.""" q_reg1 = QuantumRegister(5) q_reg2 = QuantumRegister(6) q_reg3 = QuantumRegister(7) circ = QuantumCircuit(q_reg1, q_reg2, q_reg3) self.assertEqual(circ.num_qubits, 18) def test_calibrations_basis_gates(self): """Check if the calibrations for basis gates provided are added correctly.""" circ = QuantumCircuit(2) with pulse.build() as q0_x180: pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0)) with pulse.build() as q1_y90: pulse.play(pulse.library.Gaussian(20, -1.0, 3.0), pulse.DriveChannel(1)) # Add calibration circ.add_calibration(RXGate(3.14), [0], q0_x180) circ.add_calibration(RYGate(1.57), [1], q1_y90) self.assertEqual(set(circ.calibrations.keys()), {"rx", "ry"}) self.assertEqual(set(circ.calibrations["rx"].keys()), {((0,), (3.14,))}) self.assertEqual(set(circ.calibrations["ry"].keys()), {((1,), (1.57,))}) self.assertEqual( circ.calibrations["rx"][((0,), (3.14,))].instructions, q0_x180.instructions ) self.assertEqual(circ.calibrations["ry"][((1,), (1.57,))].instructions, q1_y90.instructions) def test_calibrations_custom_gates(self): """Check if the calibrations for custom gates with params provided are added correctly.""" circ = QuantumCircuit(3) with pulse.build() as q0_x180: pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0)) # Add calibrations with a custom gate 'rxt' circ.add_calibration("rxt", [0], q0_x180, params=[1.57, 3.14, 4.71]) self.assertEqual(set(circ.calibrations.keys()), {"rxt"}) self.assertEqual(set(circ.calibrations["rxt"].keys()), {((0,), (1.57, 3.14, 4.71))}) self.assertEqual( circ.calibrations["rxt"][((0,), (1.57, 3.14, 4.71))].instructions, q0_x180.instructions ) def test_calibrations_no_params(self): """Check calibrations if the no params is provided with just gate name.""" circ = QuantumCircuit(3) with pulse.build() as q0_x180: pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0)) circ.add_calibration("h", [0], q0_x180) self.assertEqual(set(circ.calibrations.keys()), {"h"}) self.assertEqual(set(circ.calibrations["h"].keys()), {((0,), ())}) self.assertEqual(circ.calibrations["h"][((0,), ())].instructions, q0_x180.instructions) def test_has_calibration_for(self): """Test that `has_calibration_for` returns a correct answer.""" qc = QuantumCircuit(3) with pulse.build() as q0_x180: pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0)) qc.add_calibration("h", [0], q0_x180) qc.h(0) qc.h(1) self.assertTrue(qc.has_calibration_for(qc.data[0])) self.assertFalse(qc.has_calibration_for(qc.data[1])) def test_has_calibration_for_legacy(self): """Test that `has_calibration_for` returns a correct answer when presented with a legacy 3 tuple.""" qc = QuantumCircuit(3) with pulse.build() as q0_x180: pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0)) qc.add_calibration("h", [0], q0_x180) qc.h(0) qc.h(1) self.assertTrue( qc.has_calibration_for( (qc.data[0].operation, list(qc.data[0].qubits), list(qc.data[0].clbits)) ) ) self.assertFalse( qc.has_calibration_for( (qc.data[1].operation, list(qc.data[1].qubits), list(qc.data[1].clbits)) ) ) def test_metadata_copy_does_not_share_state(self): """Verify mutating the metadata of a circuit copy does not impact original.""" # ref: https://github.com/Qiskit/qiskit-terra/issues/6057 qc1 = QuantumCircuit(1) qc1.metadata = {"a": 0} qc2 = qc1.copy() qc2.metadata["a"] = 1000 self.assertEqual(qc1.metadata["a"], 0) def test_metadata_is_dict(self): """Verify setting metadata to None in the constructor results in an empty dict.""" qc = QuantumCircuit(1) metadata1 = qc.metadata self.assertEqual(metadata1, {}) def test_metadata_raises(self): """Test that we must set metadata to a dict.""" qc = QuantumCircuit(1) with self.assertRaises(TypeError): qc.metadata = 1 def test_metdata_deprectation(self): """Test that setting metadata to None emits a deprecation warning.""" qc = QuantumCircuit(1) with self.assertWarns(DeprecationWarning): qc.metadata = None self.assertEqual(qc.metadata, {}) def test_scheduling(self): """Test cannot return schedule information without scheduling.""" qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) with self.assertRaises(AttributeError): # pylint: disable=pointless-statement qc.op_start_times if __name__ == "__main__": unittest.main()
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test Qiskit's gates in QASM2.""" import unittest from math import pi import re from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.test import QiskitTestCase from qiskit.circuit import Parameter, Qubit, Clbit, Gate from qiskit.circuit.library import C3SXGate, CCZGate, CSGate, CSdgGate, PermutationGate from qiskit.qasm.exceptions import QasmError # Regex pattern to match valid OpenQASM identifiers VALID_QASM2_IDENTIFIER = re.compile("[a-z][a-zA-Z_0-9]*") class TestCircuitQasm(QiskitTestCase): """QuantumCircuit QASM2 tests.""" def test_circuit_qasm(self): """Test circuit qasm() method.""" qr1 = QuantumRegister(1, "qr1") qr2 = QuantumRegister(2, "qr2") cr = ClassicalRegister(3, "cr") qc = QuantumCircuit(qr1, qr2, cr) qc.p(0.3, qr1[0]) qc.u(0.3, 0.2, 0.1, qr2[1]) qc.s(qr2[1]) qc.sdg(qr2[1]) qc.cx(qr1[0], qr2[1]) qc.barrier(qr2) qc.cx(qr2[1], qr1[0]) qc.h(qr2[1]) qc.x(qr2[1]).c_if(cr, 0) qc.y(qr1[0]).c_if(cr, 1) qc.z(qr1[0]).c_if(cr, 2) qc.barrier(qr1, qr2) qc.measure(qr1[0], cr[0]) qc.measure(qr2[0], cr[1]) qc.measure(qr2[1], cr[2]) expected_qasm = """OPENQASM 2.0; include "qelib1.inc"; qreg qr1[1]; qreg qr2[2]; creg cr[3]; p(0.3) qr1[0]; u(0.3,0.2,0.1) qr2[1]; s qr2[1]; sdg qr2[1]; cx qr1[0],qr2[1]; barrier qr2[0],qr2[1]; cx qr2[1],qr1[0]; h qr2[1]; if(cr==0) x qr2[1]; if(cr==1) y qr1[0]; if(cr==2) z qr1[0]; barrier qr1[0],qr2[0],qr2[1]; measure qr1[0] -> cr[0]; measure qr2[0] -> cr[1]; measure qr2[1] -> cr[2];\n""" self.assertEqual(qc.qasm(), expected_qasm) def test_circuit_qasm_with_composite_circuit(self): """Test circuit qasm() method when a composite circuit instruction is included within circuit. """ composite_circ_qreg = QuantumRegister(2) composite_circ = QuantumCircuit(composite_circ_qreg, name="composite_circ") composite_circ.h(0) composite_circ.x(1) composite_circ.cx(0, 1) composite_circ_instr = composite_circ.to_instruction() qr = QuantumRegister(2, "qr") cr = ClassicalRegister(2, "cr") qc = QuantumCircuit(qr, cr) qc.h(0) qc.cx(0, 1) qc.barrier() qc.append(composite_circ_instr, [0, 1]) qc.measure([0, 1], [0, 1]) expected_qasm = """OPENQASM 2.0; include "qelib1.inc"; gate composite_circ q0,q1 { h q0; x q1; cx q0,q1; } qreg qr[2]; creg cr[2]; h qr[0]; cx qr[0],qr[1]; barrier qr[0],qr[1]; composite_circ qr[0],qr[1]; measure qr[0] -> cr[0]; measure qr[1] -> cr[1];\n""" self.assertEqual(qc.qasm(), expected_qasm) def test_circuit_qasm_with_multiple_same_composite_circuits(self): """Test circuit qasm() method when a composite circuit is added to the circuit multiple times """ composite_circ_qreg = QuantumRegister(2) composite_circ = QuantumCircuit(composite_circ_qreg, name="composite_circ") composite_circ.h(0) composite_circ.x(1) composite_circ.cx(0, 1) composite_circ_instr = composite_circ.to_instruction() qr = QuantumRegister(2, "qr") cr = ClassicalRegister(2, "cr") qc = QuantumCircuit(qr, cr) qc.h(0) qc.cx(0, 1) qc.barrier() qc.append(composite_circ_instr, [0, 1]) qc.append(composite_circ_instr, [0, 1]) qc.measure([0, 1], [0, 1]) expected_qasm = """OPENQASM 2.0; include "qelib1.inc"; gate composite_circ q0,q1 { h q0; x q1; cx q0,q1; } qreg qr[2]; creg cr[2]; h qr[0]; cx qr[0],qr[1]; barrier qr[0],qr[1]; composite_circ qr[0],qr[1]; composite_circ qr[0],qr[1]; measure qr[0] -> cr[0]; measure qr[1] -> cr[1];\n""" self.assertEqual(qc.qasm(), expected_qasm) def test_circuit_qasm_with_multiple_composite_circuits_with_same_name(self): """Test circuit qasm() method when multiple composite circuit instructions with the same circuit name are added to the circuit """ my_gate = QuantumCircuit(1, name="my_gate") my_gate.h(0) my_gate_inst1 = my_gate.to_instruction() my_gate = QuantumCircuit(1, name="my_gate") my_gate.x(0) my_gate_inst2 = my_gate.to_instruction() my_gate = QuantumCircuit(1, name="my_gate") my_gate.x(0) my_gate_inst3 = my_gate.to_instruction() qr = QuantumRegister(1, name="qr") circuit = QuantumCircuit(qr, name="circuit") circuit.append(my_gate_inst1, [qr[0]]) circuit.append(my_gate_inst2, [qr[0]]) my_gate_inst2_id = id(circuit.data[-1].operation) circuit.append(my_gate_inst3, [qr[0]]) my_gate_inst3_id = id(circuit.data[-1].operation) expected_qasm = """OPENQASM 2.0; include "qelib1.inc"; gate my_gate q0 {{ h q0; }} gate my_gate_{1} q0 {{ x q0; }} gate my_gate_{0} q0 {{ x q0; }} qreg qr[1]; my_gate qr[0]; my_gate_{1} qr[0]; my_gate_{0} qr[0];\n""".format( my_gate_inst3_id, my_gate_inst2_id ) self.assertEqual(circuit.qasm(), expected_qasm) def test_circuit_qasm_with_composite_circuit_with_children_composite_circuit(self): """Test circuit qasm() method when composite circuits with children composite circuits in the definitions are added to the circuit""" child_circ = QuantumCircuit(2, name="child_circ") child_circ.h(0) child_circ.cx(0, 1) parent_circ = QuantumCircuit(3, name="parent_circ") parent_circ.append(child_circ, range(2)) parent_circ.h(2) grandparent_circ = QuantumCircuit(4, name="grandparent_circ") grandparent_circ.append(parent_circ, range(3)) grandparent_circ.x(3) qc = QuantumCircuit(4) qc.append(grandparent_circ, range(4)) expected_qasm = """OPENQASM 2.0; include "qelib1.inc"; gate child_circ q0,q1 { h q0; cx q0,q1; } gate parent_circ q0,q1,q2 { child_circ q0,q1; h q2; } gate grandparent_circ q0,q1,q2,q3 { parent_circ q0,q1,q2; x q3; } qreg q[4]; grandparent_circ q[0],q[1],q[2],q[3];\n""" self.assertEqual(qc.qasm(), expected_qasm) def test_circuit_qasm_pi(self): """Test circuit qasm() method with pi params.""" circuit = QuantumCircuit(2) circuit.cz(0, 1) circuit.u(2 * pi, 3 * pi, -5 * pi, 0) qasm_str = circuit.qasm() circuit2 = QuantumCircuit.from_qasm_str(qasm_str) self.assertEqual(circuit, circuit2) def test_circuit_qasm_with_composite_circuit_with_one_param(self): """Test circuit qasm() method when a composite circuit instruction has one param """ original_str = """OPENQASM 2.0; include "qelib1.inc"; gate nG0(param0) q0 { h q0; } qreg q[3]; creg c[3]; nG0(pi) q[0];\n""" qc = QuantumCircuit.from_qasm_str(original_str) self.assertEqual(original_str, qc.qasm()) def test_circuit_qasm_with_composite_circuit_with_many_params_and_qubits(self): """Test circuit qasm() method when a composite circuit instruction has many params and qubits """ original_str = """OPENQASM 2.0; include "qelib1.inc"; gate nG0(param0,param1) q0,q1 { h q0; h q1; } qreg q[3]; qreg r[3]; creg c[3]; creg d[3]; nG0(pi,pi/2) q[0],r[0];\n""" qc = QuantumCircuit.from_qasm_str(original_str) self.assertEqual(original_str, qc.qasm()) def test_c3sxgate_roundtrips(self): """Test that C3SXGate correctly round trips. Qiskit gives this gate a different name ('c3sx') to the name in Qiskit's version of qelib1.inc ('c3sqrtx') gate, which can lead to resolution issues.""" qc = QuantumCircuit(4) qc.append(C3SXGate(), qc.qubits, []) qasm = qc.qasm() expected = """OPENQASM 2.0; include "qelib1.inc"; qreg q[4]; c3sqrtx q[0],q[1],q[2],q[3]; """ self.assertEqual(qasm, expected) parsed = QuantumCircuit.from_qasm_str(qasm) self.assertIsInstance(parsed.data[0].operation, C3SXGate) def test_c3sxgate_qasm_deprecation_warning(self): """Test deprecation warning for C3SXGate.""" with self.assertWarnsRegex(DeprecationWarning, r"Correct exporting to OpenQASM 2"): C3SXGate().qasm() def test_cczgate_qasm(self): """Test that CCZ dumps definition as a non-qelib1 gate.""" qc = QuantumCircuit(3) qc.append(CCZGate(), qc.qubits, []) qasm = qc.qasm() expected = """OPENQASM 2.0; include "qelib1.inc"; gate ccz q0,q1,q2 { h q2; ccx q0,q1,q2; h q2; } qreg q[3]; ccz q[0],q[1],q[2]; """ self.assertEqual(qasm, expected) def test_csgate_qasm(self): """Test that CS dumps definition as a non-qelib1 gate.""" qc = QuantumCircuit(2) qc.append(CSGate(), qc.qubits, []) qasm = qc.qasm() expected = """OPENQASM 2.0; include "qelib1.inc"; gate cs q0,q1 { p(pi/4) q0; cx q0,q1; p(-pi/4) q1; cx q0,q1; p(pi/4) q1; } qreg q[2]; cs q[0],q[1]; """ self.assertEqual(qasm, expected) def test_csdggate_qasm(self): """Test that CSdg dumps definition as a non-qelib1 gate.""" qc = QuantumCircuit(2) qc.append(CSdgGate(), qc.qubits, []) qasm = qc.qasm() expected = """OPENQASM 2.0; include "qelib1.inc"; gate csdg q0,q1 { p(-pi/4) q0; cx q0,q1; p(pi/4) q1; cx q0,q1; p(-pi/4) q1; } qreg q[2]; csdg q[0],q[1]; """ self.assertEqual(qasm, expected) def test_rzxgate_qasm(self): """Test that RZX dumps definition as a non-qelib1 gate.""" qc = QuantumCircuit(2) qc.rzx(0, 0, 1) qc.rzx(pi / 2, 1, 0) qasm = qc.qasm() expected = """OPENQASM 2.0; include "qelib1.inc"; gate rzx(param0) q0,q1 { h q1; cx q0,q1; rz(param0) q1; cx q0,q1; h q1; } qreg q[2]; rzx(0) q[0],q[1]; rzx(pi/2) q[1],q[0]; """ self.assertEqual(qasm, expected) def test_ecrgate_qasm(self): """Test that ECR dumps its definition as a non-qelib1 gate.""" qc = QuantumCircuit(2) qc.ecr(0, 1) qc.ecr(1, 0) qasm = qc.qasm() expected = """OPENQASM 2.0; include "qelib1.inc"; gate rzx(param0) q0,q1 { h q1; cx q0,q1; rz(param0) q1; cx q0,q1; h q1; } gate ecr q0,q1 { rzx(pi/4) q0,q1; x q0; rzx(-pi/4) q0,q1; } qreg q[2]; ecr q[0],q[1]; ecr q[1],q[0]; """ self.assertEqual(qasm, expected) def test_unitary_qasm(self): """Test that UnitaryGate can be dumped to OQ2 correctly.""" qc = QuantumCircuit(1) qc.unitary([[1, 0], [0, 1]], 0) qasm = qc.qasm() expected = """OPENQASM 2.0; include "qelib1.inc"; gate unitary q0 { u(0,0,0) q0; } qreg q[1]; unitary q[0]; """ self.assertEqual(qasm, expected) def test_multiple_unitary_qasm(self): """Test that multiple UnitaryGate instances can all dump successfully.""" custom = QuantumCircuit(1, name="custom") custom.unitary([[1, 0], [0, -1]], 0) qc = QuantumCircuit(2) qc.unitary([[1, 0], [0, 1]], 0) qc.unitary([[0, 1], [1, 0]], 1) qc.append(custom.to_gate(), [0], []) qasm = qc.qasm() expected = re.compile( r"""OPENQASM 2.0; include "qelib1.inc"; gate unitary q0 { u\(0,0,0\) q0; } gate (?P<u1>unitary_[0-9]*) q0 { u\(pi,-pi/2,pi/2\) q0; } gate (?P<u2>unitary_[0-9]*) q0 { u\(0,pi/2,pi/2\) q0; } gate custom q0 { (?P=u2) q0; } qreg q\[2\]; unitary q\[0\]; (?P=u1) q\[1\]; custom q\[0\]; """, re.MULTILINE, ) self.assertRegex(qasm, expected) def test_unbound_circuit_raises(self): """Test circuits with unbound parameters raises.""" qc = QuantumCircuit(1) theta = Parameter("θ") qc.rz(theta, 0) with self.assertRaises(QasmError): qc.qasm() def test_gate_qasm_with_ctrl_state(self): """Test gate qasm() with controlled gate that has ctrl_state setting.""" from qiskit.quantum_info import Operator qc = QuantumCircuit(2) qc.ch(0, 1, ctrl_state=0) qasm_str = qc.qasm() self.assertEqual(Operator(qc), Operator(QuantumCircuit.from_qasm_str(qasm_str))) def test_circuit_qasm_with_mcx_gate(self): """Test circuit qasm() method with MCXGate See https://github.com/Qiskit/qiskit-terra/issues/4943 """ qc = QuantumCircuit(4) qc.mcx([0, 1, 2], 3) # qasm output doesn't support parameterized gate yet. # param0 for "gate mcuq(param0) is not used inside the definition expected_qasm = """OPENQASM 2.0; include "qelib1.inc"; gate mcx q0,q1,q2,q3 { h q3; p(pi/8) q0; p(pi/8) q1; p(pi/8) q2; p(pi/8) q3; cx q0,q1; p(-pi/8) q1; cx q0,q1; cx q1,q2; p(-pi/8) q2; cx q0,q2; p(pi/8) q2; cx q1,q2; p(-pi/8) q2; cx q0,q2; cx q2,q3; p(-pi/8) q3; cx q1,q3; p(pi/8) q3; cx q2,q3; p(-pi/8) q3; cx q0,q3; p(pi/8) q3; cx q2,q3; p(-pi/8) q3; cx q1,q3; p(pi/8) q3; cx q2,q3; p(-pi/8) q3; cx q0,q3; h q3; } qreg q[4]; mcx q[0],q[1],q[2],q[3];\n""" self.assertEqual(qc.qasm(), expected_qasm) def test_circuit_qasm_with_mcx_gate_variants(self): """Test circuit qasm() method with MCXGrayCode, MCXRecursive, MCXVChain""" import qiskit.circuit.library as cl n = 5 qc = QuantumCircuit(2 * n - 1) qc.append(cl.MCXGrayCode(n), range(n + 1)) qc.append(cl.MCXRecursive(n), range(n + 2)) qc.append(cl.MCXVChain(n), range(2 * n - 1)) # qasm output doesn't support parameterized gate yet. # param0 for "gate mcuq(param0) is not used inside the definition expected_qasm = """OPENQASM 2.0; include "qelib1.inc"; gate mcu1(param0) q0,q1,q2,q3,q4,q5 { cu1(pi/16) q4,q5; cx q4,q3; cu1(-pi/16) q3,q5; cx q4,q3; cu1(pi/16) q3,q5; cx q3,q2; cu1(-pi/16) q2,q5; cx q4,q2; cu1(pi/16) q2,q5; cx q3,q2; cu1(-pi/16) q2,q5; cx q4,q2; cu1(pi/16) q2,q5; cx q2,q1; cu1(-pi/16) q1,q5; cx q4,q1; cu1(pi/16) q1,q5; cx q3,q1; cu1(-pi/16) q1,q5; cx q4,q1; cu1(pi/16) q1,q5; cx q2,q1; cu1(-pi/16) q1,q5; cx q4,q1; cu1(pi/16) q1,q5; cx q3,q1; cu1(-pi/16) q1,q5; cx q4,q1; cu1(pi/16) q1,q5; cx q1,q0; cu1(-pi/16) q0,q5; cx q4,q0; cu1(pi/16) q0,q5; cx q3,q0; cu1(-pi/16) q0,q5; cx q4,q0; cu1(pi/16) q0,q5; cx q2,q0; cu1(-pi/16) q0,q5; cx q4,q0; cu1(pi/16) q0,q5; cx q3,q0; cu1(-pi/16) q0,q5; cx q4,q0; cu1(pi/16) q0,q5; cx q1,q0; cu1(-pi/16) q0,q5; cx q4,q0; cu1(pi/16) q0,q5; cx q3,q0; cu1(-pi/16) q0,q5; cx q4,q0; cu1(pi/16) q0,q5; cx q2,q0; cu1(-pi/16) q0,q5; cx q4,q0; cu1(pi/16) q0,q5; cx q3,q0; cu1(-pi/16) q0,q5; cx q4,q0; cu1(pi/16) q0,q5; } gate mcx_gray q0,q1,q2,q3,q4,q5 { h q5; mcu1(pi) q0,q1,q2,q3,q4,q5; h q5; } gate mcx q0,q1,q2,q3 { h q3; p(pi/8) q0; p(pi/8) q1; p(pi/8) q2; p(pi/8) q3; cx q0,q1; p(-pi/8) q1; cx q0,q1; cx q1,q2; p(-pi/8) q2; cx q0,q2; p(pi/8) q2; cx q1,q2; p(-pi/8) q2; cx q0,q2; cx q2,q3; p(-pi/8) q3; cx q1,q3; p(pi/8) q3; cx q2,q3; p(-pi/8) q3; cx q0,q3; p(pi/8) q3; cx q2,q3; p(-pi/8) q3; cx q1,q3; p(pi/8) q3; cx q2,q3; p(-pi/8) q3; cx q0,q3; h q3; } gate mcx_recursive q0,q1,q2,q3,q4,q5,q6 { mcx q0,q1,q2,q6; mcx q3,q4,q6,q5; mcx q0,q1,q2,q6; mcx q3,q4,q6,q5; } gate mcx_vchain q0,q1,q2,q3,q4,q5,q6,q7,q8 { rccx q0,q1,q6; rccx q2,q6,q7; rccx q3,q7,q8; ccx q4,q8,q5; rccx q3,q7,q8; rccx q2,q6,q7; rccx q0,q1,q6; } qreg q[9]; mcx_gray q[0],q[1],q[2],q[3],q[4],q[5]; mcx_recursive q[0],q[1],q[2],q[3],q[4],q[5],q[6]; mcx_vchain q[0],q[1],q[2],q[3],q[4],q[5],q[6],q[7],q[8];\n""" self.assertEqual(qc.qasm(), expected_qasm) def test_circuit_qasm_with_registerless_bits(self): """Test that registerless bits do not have naming collisions in their registers.""" initial_registers = [QuantumRegister(2), ClassicalRegister(2)] qc = QuantumCircuit(*initial_registers, [Qubit(), Clbit()]) # Match a 'qreg identifier[3];'-like QASM register declaration. register_regex = re.compile(r"\s*[cq]reg\s+(\w+)\s*\[\d+\]\s*", re.M) qasm_register_names = set() for statement in qc.qasm().split(";"): match = register_regex.match(statement) if match: qasm_register_names.add(match.group(1)) self.assertEqual(len(qasm_register_names), 4) # Check that no additional registers were added to the circuit. self.assertEqual(len(qc.qregs), 1) self.assertEqual(len(qc.cregs), 1) # Check that the registerless-register names are recalculated after adding more registers, # to avoid naming clashes in this case. generated_names = qasm_register_names - {register.name for register in initial_registers} for generated_name in generated_names: qc.add_register(QuantumRegister(1, name=generated_name)) qasm_register_names = set() for statement in qc.qasm().split(";"): match = register_regex.match(statement) if match: qasm_register_names.add(match.group(1)) self.assertEqual(len(qasm_register_names), 6) def test_circuit_qasm_with_repeated_instruction_names(self): """Test that qasm() doesn't change the name of the instructions that live in circuit.data, but a copy of them when there are repeated names.""" qc = QuantumCircuit(2) qc.h(0) qc.x(1) # Create some random custom gate and name it "custom" custom = QuantumCircuit(1) custom.h(0) custom.y(0) gate = custom.to_gate() gate.name = "custom" # Another random custom gate named "custom" as well custom2 = QuantumCircuit(2) custom2.x(0) custom2.z(1) gate2 = custom2.to_gate() gate2.name = "custom" # Append custom gates with same name to original circuit qc.append(gate, [0]) qc.append(gate2, [1, 0]) # Expected qasm string will append the id to the second gate with repeated name expected_qasm = f"""OPENQASM 2.0; include "qelib1.inc"; gate custom q0 {{ h q0; y q0; }} gate custom_{id(gate2)} q0,q1 {{ x q0; z q1; }} qreg q[2]; h q[0]; x q[1]; custom q[0]; custom_{id(gate2)} q[1],q[0];\n""" # Check qasm() produced the correct string self.assertEqual(expected_qasm, qc.qasm()) # Check instruction names were not changed by qasm() names = ["h", "x", "custom", "custom"] for idx, instruction in enumerate(qc._data): self.assertEqual(instruction.operation.name, names[idx]) def test_circuit_qasm_with_invalid_identifiers(self): """Test that qasm() detects and corrects invalid OpenQASM gate identifiers, while not changing the instructions on the original circuit""" qc = QuantumCircuit(2) # Create some gate and give it an invalid name custom = QuantumCircuit(1) custom.x(0) custom.u(0, 0, pi, 0) gate = custom.to_gate() gate.name = "A[$]" # Another gate also with invalid name custom2 = QuantumCircuit(2) custom2.x(0) custom2.append(gate, [1]) gate2 = custom2.to_gate() gate2.name = "invalid[name]" # Append gates qc.append(gate, [0]) qc.append(gate2, [1, 0]) # Expected qasm with valid identifiers expected_qasm = "\n".join( [ "OPENQASM 2.0;", 'include "qelib1.inc";', "gate gate_A___ q0 { x q0; u(0,0,pi) q0; }", "gate invalid_name_ q0,q1 { x q0; gate_A___ q1; }", "qreg q[2];", "gate_A___ q[0];", "invalid_name_ q[1],q[0];", "", ] ) # Check qasm() produces the correct string self.assertEqual(expected_qasm, qc.qasm()) # Check instruction names were not changed by qasm() names = ["A[$]", "invalid[name]"] for idx, instruction in enumerate(qc._data): self.assertEqual(instruction.operation.name, names[idx]) def test_circuit_qasm_with_duplicate_invalid_identifiers(self): """Test that qasm() corrects invalid identifiers and the de-duplication code runs correctly, without altering original instructions""" base = QuantumCircuit(1) # First gate with invalid name, escapes to "invalid__" clash1 = QuantumCircuit(1, name="invalid??") clash1.x(0) base.append(clash1, [0]) # Second gate with invalid name that also escapes to "invalid__" clash2 = QuantumCircuit(1, name="invalid[]") clash2.z(0) base.append(clash2, [0]) # Check qasm is correctly produced names = set() for match in re.findall(r"gate (\S+)", base.qasm()): self.assertTrue(VALID_QASM2_IDENTIFIER.fullmatch(match)) names.add(match) self.assertEqual(len(names), 2) # Check instruction names were not changed by qasm() names = ["invalid??", "invalid[]"] for idx, instruction in enumerate(base._data): self.assertEqual(instruction.operation.name, names[idx]) def test_circuit_qasm_escapes_register_names(self): """Test that registers that have invalid OpenQASM 2 names get correctly escaped, even when they would escape to the same value.""" qc = QuantumCircuit(QuantumRegister(2, "?invalid"), QuantumRegister(2, "!invalid")) qc.cx(0, 1) qc.cx(2, 3) qasm = qc.qasm() match = re.fullmatch( rf"""OPENQASM 2.0; include "qelib1.inc"; qreg ({VALID_QASM2_IDENTIFIER.pattern})\[2\]; qreg ({VALID_QASM2_IDENTIFIER.pattern})\[2\]; cx \1\[0\],\1\[1\]; cx \2\[0\],\2\[1\]; """, qasm, ) self.assertTrue(match) self.assertNotEqual(match.group(1), match.group(2)) def test_circuit_qasm_escapes_reserved(self): """Test that the OpenQASM 2 exporter won't export reserved names.""" qc = QuantumCircuit(QuantumRegister(1, "qreg")) gate = Gate("gate", 1, []) gate.definition = QuantumCircuit(1) qc.append(gate, [qc.qubits[0]]) qasm = qc.qasm() match = re.fullmatch( rf"""OPENQASM 2.0; include "qelib1.inc"; gate ({VALID_QASM2_IDENTIFIER.pattern}) q0 {{ }} qreg ({VALID_QASM2_IDENTIFIER.pattern})\[1\]; \1 \2\[0\]; """, qasm, ) self.assertTrue(match) self.assertNotEqual(match.group(1), "gate") self.assertNotEqual(match.group(1), "qreg") def test_circuit_qasm_with_double_precision_rotation_angle(self): """Test that qasm() emits high precision rotation angles per default.""" from qiskit.circuit.tools.pi_check import MAX_FRAC qc = QuantumCircuit(1) qc.p(0.123456789, 0) qc.p(pi * pi, 0) qc.p(MAX_FRAC * pi + 1, 0) expected_qasm = """OPENQASM 2.0; include "qelib1.inc"; qreg q[1]; p(0.123456789) q[0]; p(9.869604401089358) q[0]; p(51.26548245743669) q[0];\n""" self.assertEqual(qc.qasm(), expected_qasm) def test_circuit_qasm_with_rotation_angles_close_to_pi(self): """Test that qasm() properly rounds values closer than 1e-12 to pi.""" qc = QuantumCircuit(1) qc.p(pi + 1e-11, 0) qc.p(pi + 1e-12, 0) expected_qasm = """OPENQASM 2.0; include "qelib1.inc"; qreg q[1]; p(3.141592653599793) q[0]; p(pi) q[0];\n""" self.assertEqual(qc.qasm(), expected_qasm) def test_circuit_raises_on_single_bit_condition(self): """OpenQASM 2 can't represent single-bit conditions, so test that a suitable error is printed if this is attempted.""" qc = QuantumCircuit(1, 1) qc.x(0).c_if(0, True) with self.assertRaisesRegex(QasmError, "OpenQASM 2 can only condition on registers"): qc.qasm() def test_circuit_raises_invalid_custom_gate_no_qubits(self): """OpenQASM 2 exporter of custom gates with no qubits. See: https://github.com/Qiskit/qiskit-terra/issues/10435""" legit_circuit = QuantumCircuit(5, name="legit_circuit") empty_circuit = QuantumCircuit(name="empty_circuit") legit_circuit.append(empty_circuit) with self.assertRaisesRegex(QasmError, "acts on zero qubits"): legit_circuit.qasm() def test_circuit_raises_invalid_custom_gate_clbits(self): """OpenQASM 2 exporter of custom instruction. See: https://github.com/Qiskit/qiskit-terra/issues/7351""" instruction = QuantumCircuit(2, 2, name="inst") instruction.cx(0, 1) instruction.measure([0, 1], [0, 1]) custom_instruction = instruction.to_instruction() qc = QuantumCircuit(2, 2) qc.append(custom_instruction, [0, 1], [0, 1]) with self.assertRaisesRegex(QasmError, "acts on 2 classical bits"): qc.qasm() def test_circuit_qasm_with_permutations(self): """Test circuit qasm() method with Permutation gates.""" qc = QuantumCircuit(4) qc.append(PermutationGate([2, 1, 0]), [0, 1, 2]) expected_qasm = """OPENQASM 2.0; include "qelib1.inc"; gate permutation__2_1_0_ q0,q1,q2 { swap q0,q2; } qreg q[4]; permutation__2_1_0_ q[0],q[1],q[2];\n""" self.assertEqual(qc.qasm(), expected_qasm) def test_multiple_permutation(self): """Test that multiple PermutationGates can be added to a circuit.""" custom = QuantumCircuit(3, name="custom") custom.append(PermutationGate([2, 1, 0]), [0, 1, 2]) custom.append(PermutationGate([0, 1, 2]), [0, 1, 2]) qc = QuantumCircuit(4) qc.append(PermutationGate([2, 1, 0]), [0, 1, 2], []) qc.append(PermutationGate([1, 2, 0]), [0, 1, 2], []) qc.append(custom.to_gate(), [1, 3, 2], []) qasm = qc.qasm() expected = """OPENQASM 2.0; include "qelib1.inc"; gate permutation__2_1_0_ q0,q1,q2 { swap q0,q2; } gate permutation__1_2_0_ q0,q1,q2 { swap q1,q2; swap q0,q2; } gate permutation__0_1_2_ q0,q1,q2 { } gate custom q0,q1,q2 { permutation__2_1_0_ q0,q1,q2; permutation__0_1_2_ q0,q1,q2; } qreg q[4]; permutation__2_1_0_ q[0],q[1],q[2]; permutation__1_2_0_ q[0],q[1],q[2]; custom q[1],q[3],q[2]; """ self.assertEqual(qasm, expected) def test_circuit_qasm_with_reset(self): """Test circuit qasm() method with Reset.""" qc = QuantumCircuit(2) qc.reset([0, 1]) expected_qasm = """OPENQASM 2.0; include "qelib1.inc"; qreg q[2]; reset q[0]; reset q[1];\n""" self.assertEqual(qc.qasm(), expected_qasm) def test_nested_gate_naming_clashes(self): """Test that gates that have naming clashes but only appear in the body of another gate still get exported correctly.""" # pylint: disable=missing-class-docstring class Inner(Gate): def __init__(self, param): super().__init__("inner", 1, [param]) def _define(self): self._definition = QuantumCircuit(1) self._definition.rx(self.params[0], 0) class Outer(Gate): def __init__(self, param): super().__init__("outer", 1, [param]) def _define(self): self._definition = QuantumCircuit(1) self._definition.append(Inner(self.params[0]), [0], []) qc = QuantumCircuit(1) qc.append(Outer(1.0), [0], []) qc.append(Outer(2.0), [0], []) qasm = qc.qasm() expected = re.compile( r"""OPENQASM 2\.0; include "qelib1\.inc"; gate inner\(param0\) q0 { rx\(1\.0\) q0; } gate outer\(param0\) q0 { inner\(1\.0\) q0; } gate (?P<inner1>inner_[0-9]*)\(param0\) q0 { rx\(2\.0\) q0; } gate (?P<outer1>outer_[0-9]*)\(param0\) q0 { (?P=inner1)\(2\.0\) q0; } qreg q\[1\]; outer\(1\.0\) q\[0\]; (?P=outer1)\(2\.0\) q\[0\]; """, re.MULTILINE, ) self.assertRegex(qasm, expected) def test_opaque_output(self): """Test that gates with no definition are exported as `opaque`.""" custom = QuantumCircuit(1, name="custom") custom.append(Gate("my_c", 1, []), [0]) qc = QuantumCircuit(2) qc.append(Gate("my_a", 1, []), [0]) qc.append(Gate("my_a", 1, []), [1]) qc.append(Gate("my_b", 2, [1.0]), [1, 0]) qc.append(custom.to_gate(), [0], []) qasm = qc.qasm() expected = """OPENQASM 2.0; include "qelib1.inc"; opaque my_a q0; opaque my_b(param0) q0,q1; opaque my_c q0; gate custom q0 { my_c q0; } qreg q[2]; my_a q[0]; my_a q[1]; my_b(1.0) q[1],q[0]; custom q[0]; """ self.assertEqual(qasm, expected) def test_sequencial_inner_gates_with_same_name(self): """Test if inner gates sequentially added with the same name result in the correct qasm""" qubits_range = range(3) gate_a = QuantumCircuit(3, name="a") gate_a.h(qubits_range) gate_a = gate_a.to_instruction() gate_b = QuantumCircuit(3, name="a") gate_b.append(gate_a, qubits_range) gate_b.x(qubits_range) gate_b = gate_b.to_instruction() qc = QuantumCircuit(3) qc.append(gate_b, qubits_range) qc.z(qubits_range) gate_a_id = id(qc.data[0].operation) expected_output = f"""OPENQASM 2.0; include "qelib1.inc"; gate a q0,q1,q2 {{ h q0; h q1; h q2; }} gate a_{gate_a_id} q0,q1,q2 {{ a q0,q1,q2; x q0; x q1; x q2; }} qreg q[3]; a_{gate_a_id} q[0],q[1],q[2]; z q[0]; z q[1]; z q[2]; """ self.assertEqual(qc.qasm(), expected_output) def test_empty_barrier(self): """Test that a blank barrier statement in _Qiskit_ acts over all qubits, while an explicitly no-op barrier (assuming Qiskit continues to allow this) is not output to OQ2 at all, since the statement requires an argument in the spec.""" qc = QuantumCircuit(QuantumRegister(2, "qr1"), QuantumRegister(3, "qr2")) qc.barrier() # In Qiskit land, this affects _all_ qubits. qc.barrier([]) # This explicitly affects _no_ qubits (so is totally meaningless). expected = """\ OPENQASM 2.0; include "qelib1.inc"; qreg qr1[2]; qreg qr2[3]; barrier qr1[0],qr1[1],qr2[0],qr2[1],qr2[2]; """ self.assertEqual(qc.qasm(), expected) def test_small_angle_valid(self): """Test that small angles do not get converted to invalid OQ2 floating-point values.""" # OQ2 _technically_ requires a decimal point in all floating-point values, even ones that # are followed by an exponent. qc = QuantumCircuit(1) qc.rx(0.000001, 0) expected = """\ OPENQASM 2.0; include "qelib1.inc"; qreg q[1]; rx(1.e-06) q[0]; """ self.assertEqual(qc.qasm(), expected) if __name__ == "__main__": unittest.main()
https://github.com/swe-train/qiskit__qiskit
swe-train
# 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. """Test commutation checker class .""" import unittest import numpy as np from qiskit import ClassicalRegister from qiskit.test import QiskitTestCase from qiskit.circuit import QuantumRegister, Parameter, Qubit from qiskit.circuit import CommutationChecker from qiskit.circuit.library import ( ZGate, XGate, CXGate, CCXGate, MCXGate, RZGate, Measure, Barrier, Reset, LinearFunction, ) class TestCommutationChecker(QiskitTestCase): """Test CommutationChecker class.""" def test_simple_gates(self): """Check simple commutation relations between gates, experimenting with different orders of gates, different orders of qubits, different sets of qubits over which gates are defined, and so on.""" comm_checker = CommutationChecker() # should commute res = comm_checker.commute(ZGate(), [0], [], CXGate(), [0, 1], []) self.assertTrue(res) # should not commute res = comm_checker.commute(ZGate(), [1], [], CXGate(), [0, 1], []) self.assertFalse(res) # should not commute res = comm_checker.commute(XGate(), [0], [], CXGate(), [0, 1], []) self.assertFalse(res) # should commute res = comm_checker.commute(XGate(), [1], [], CXGate(), [0, 1], []) self.assertTrue(res) # should not commute res = comm_checker.commute(XGate(), [1], [], CXGate(), [1, 0], []) self.assertFalse(res) # should commute res = comm_checker.commute(XGate(), [0], [], CXGate(), [1, 0], []) self.assertTrue(res) # should commute res = comm_checker.commute(CXGate(), [1, 0], [], XGate(), [0], []) self.assertTrue(res) # should not commute res = comm_checker.commute(CXGate(), [1, 0], [], XGate(), [1], []) self.assertFalse(res) # should commute res = comm_checker.commute( CXGate(), [1, 0], [], CXGate(), [1, 0], [], ) self.assertTrue(res) # should not commute res = comm_checker.commute( CXGate(), [1, 0], [], CXGate(), [0, 1], [], ) self.assertFalse(res) # should commute res = comm_checker.commute( CXGate(), [1, 0], [], CXGate(), [1, 2], [], ) self.assertTrue(res) # should not commute res = comm_checker.commute( CXGate(), [1, 0], [], CXGate(), [2, 1], [], ) self.assertFalse(res) # should commute res = comm_checker.commute( CXGate(), [1, 0], [], CXGate(), [2, 3], [], ) self.assertTrue(res) res = comm_checker.commute(XGate(), [2], [], CCXGate(), [0, 1, 2], []) self.assertTrue(res) res = comm_checker.commute(CCXGate(), [0, 1, 2], [], CCXGate(), [0, 2, 1], []) self.assertFalse(res) def test_passing_quantum_registers(self): """Check that passing QuantumRegisters works correctly.""" comm_checker = CommutationChecker() qr = QuantumRegister(4) # should commute res = comm_checker.commute(CXGate(), [qr[1], qr[0]], [], CXGate(), [qr[1], qr[2]], []) self.assertTrue(res) # should not commute res = comm_checker.commute(CXGate(), [qr[0], qr[1]], [], CXGate(), [qr[1], qr[2]], []) self.assertFalse(res) def test_caching_positive_results(self): """Check that hashing positive results in commutativity checker works as expected.""" comm_checker = CommutationChecker() res = comm_checker.commute(ZGate(), [0], [], CXGate(), [0, 1], []) self.assertTrue(res) self.assertGreater(len(comm_checker.cache), 0) def test_caching_negative_results(self): """Check that hashing negative results in commutativity checker works as expected.""" comm_checker = CommutationChecker() res = comm_checker.commute(XGate(), [0], [], CXGate(), [0, 1], []) self.assertFalse(res) self.assertGreater(len(comm_checker.cache), 0) def test_caching_different_qubit_sets(self): """Check that hashing same commutativity results over different qubit sets works as expected.""" comm_checker = CommutationChecker() # All the following should be cached in the same way # though each relation gets cached twice: (A, B) and (B, A) comm_checker.commute(XGate(), [0], [], CXGate(), [0, 1], []) comm_checker.commute(XGate(), [10], [], CXGate(), [10, 20], []) comm_checker.commute(XGate(), [10], [], CXGate(), [10, 5], []) comm_checker.commute(XGate(), [5], [], CXGate(), [5, 7], []) self.assertEqual(len(comm_checker.cache), 2) def test_gates_with_parameters(self): """Check commutativity between (non-parameterized) gates with parameters.""" comm_checker = CommutationChecker() res = comm_checker.commute(RZGate(0), [0], [], XGate(), [0], []) self.assertTrue(res) res = comm_checker.commute(RZGate(np.pi / 2), [0], [], XGate(), [0], []) self.assertFalse(res) res = comm_checker.commute(RZGate(np.pi / 2), [0], [], RZGate(0), [0], []) self.assertTrue(res) def test_parameterized_gates(self): """Check commutativity between parameterized gates, both with free and with bound parameters.""" comm_checker = CommutationChecker() # gate that has parameters but is not considered parameterized rz_gate = RZGate(np.pi / 2) self.assertEqual(len(rz_gate.params), 1) self.assertFalse(rz_gate.is_parameterized()) # gate that has parameters and is considered parameterized rz_gate_theta = RZGate(Parameter("Theta")) rz_gate_phi = RZGate(Parameter("Phi")) self.assertEqual(len(rz_gate_theta.params), 1) self.assertTrue(rz_gate_theta.is_parameterized()) # gate that has no parameters and is not considered parameterized cx_gate = CXGate() self.assertEqual(len(cx_gate.params), 0) self.assertFalse(cx_gate.is_parameterized()) # We should detect that these gates commute res = comm_checker.commute(rz_gate, [0], [], cx_gate, [0, 1], []) self.assertTrue(res) # We should detect that these gates commute res = comm_checker.commute(rz_gate, [0], [], rz_gate, [0], []) self.assertTrue(res) # We should detect that parameterized gates over disjoint qubit subsets commute res = comm_checker.commute(rz_gate_theta, [0], [], rz_gate_theta, [1], []) self.assertTrue(res) # We should detect that parameterized gates over disjoint qubit subsets commute res = comm_checker.commute(rz_gate_theta, [0], [], rz_gate_phi, [1], []) self.assertTrue(res) # We should detect that parameterized gates over disjoint qubit subsets commute res = comm_checker.commute(rz_gate_theta, [2], [], cx_gate, [1, 3], []) self.assertTrue(res) # However, for now commutativity checker should return False when checking # commutativity between a parameterized gate and some other gate, when # the two gates are over intersecting qubit subsets. # This check should be changed if commutativity checker is extended to # handle parameterized gates better. res = comm_checker.commute(rz_gate_theta, [0], [], cx_gate, [0, 1], []) self.assertFalse(res) res = comm_checker.commute(rz_gate_theta, [0], [], rz_gate, [0], []) self.assertFalse(res) def test_measure(self): """Check commutativity involving measures.""" comm_checker = CommutationChecker() # Measure is over qubit 0, while gate is over a disjoint subset of qubits # We should be able to swap these. res = comm_checker.commute(Measure(), [0], [0], CXGate(), [1, 2], []) self.assertTrue(res) # Measure and gate have intersecting set of qubits # We should not be able to swap these. res = comm_checker.commute(Measure(), [0], [0], CXGate(), [0, 2], []) self.assertFalse(res) # Measures over different qubits and clbits res = comm_checker.commute(Measure(), [0], [0], Measure(), [1], [1]) self.assertTrue(res) # Measures over different qubits but same classical bit # We should not be able to swap these. res = comm_checker.commute(Measure(), [0], [0], Measure(), [1], [0]) self.assertFalse(res) # Measures over same qubits but different classical bit # ToDo: can we swap these? # Currently checker takes the safe approach and returns False. res = comm_checker.commute(Measure(), [0], [0], Measure(), [0], [1]) self.assertFalse(res) def test_barrier(self): """Check commutativity involving barriers.""" comm_checker = CommutationChecker() # A gate should not commute with a barrier # (at least if these are over intersecting qubit sets). res = comm_checker.commute(Barrier(4), [0, 1, 2, 3], [], CXGate(), [1, 2], []) self.assertFalse(res) # Does it even make sense to have a barrier over a subset of qubits? # Though in this case, it probably makes sense to say that barrier and gate can be swapped. res = comm_checker.commute(Barrier(4), [0, 1, 2, 3], [], CXGate(), [5, 6], []) self.assertTrue(res) def test_reset(self): """Check commutativity involving resets.""" comm_checker = CommutationChecker() # A gate should not commute with reset when the qubits intersect. res = comm_checker.commute(Reset(), [0], [], CXGate(), [0, 2], []) self.assertFalse(res) # A gate should commute with reset when the qubits are disjoint. res = comm_checker.commute(Reset(), [0], [], CXGate(), [1, 2], []) self.assertTrue(res) def test_conditional_gates(self): """Check commutativity involving conditional gates.""" comm_checker = CommutationChecker() qr = QuantumRegister(3) cr = ClassicalRegister(2) # Currently, in all cases commutativity checker should returns False. # This is definitely suboptimal. res = comm_checker.commute( CXGate().c_if(cr[0], 0), [qr[0], qr[1]], [], XGate(), [qr[2]], [] ) self.assertFalse(res) res = comm_checker.commute( CXGate().c_if(cr[0], 0), [qr[0], qr[1]], [], XGate(), [qr[1]], [] ) self.assertFalse(res) res = comm_checker.commute( CXGate().c_if(cr[0], 0), [qr[0], qr[1]], [], CXGate().c_if(cr[0], 0), [qr[0], qr[1]], [] ) self.assertFalse(res) res = comm_checker.commute( XGate().c_if(cr[0], 0), [qr[0]], [], XGate().c_if(cr[0], 1), [qr[0]], [] ) self.assertFalse(res) res = comm_checker.commute(XGate().c_if(cr[0], 0), [qr[0]], [], XGate(), [qr[0]], []) self.assertFalse(res) def test_complex_gates(self): """Check commutativity involving more complex gates.""" comm_checker = CommutationChecker() lf1 = LinearFunction([[0, 1, 0], [1, 0, 0], [0, 0, 1]]) lf2 = LinearFunction([[1, 0, 0], [0, 0, 1], [0, 1, 0]]) # lf1 is equivalent to swap(0, 1), and lf2 to swap(1, 2). # These do not commute. res = comm_checker.commute(lf1, [0, 1, 2], [], lf2, [0, 1, 2], []) self.assertFalse(res) lf3 = LinearFunction([[0, 1, 0], [0, 0, 1], [1, 0, 0]]) lf4 = LinearFunction([[0, 0, 1], [1, 0, 0], [0, 1, 0]]) # lf3 is permutation 1->2, 2->3, 3->1. # lf3 is the inverse permutation 1->3, 2->1, 3->2. # These commute. res = comm_checker.commute(lf3, [0, 1, 2], [], lf4, [0, 1, 2], []) self.assertTrue(res) def test_c7x_gate(self): """Test wide gate works correctly.""" qargs = [Qubit() for _ in [None] * 8] res = CommutationChecker().commute(XGate(), qargs[:1], [], XGate().control(7), qargs, []) self.assertFalse(res) def test_wide_gates_over_nondisjoint_qubits(self): """Test that checking wide gates does not lead to memory problems.""" res = CommutationChecker().commute(MCXGate(29), list(range(30)), [], XGate(), [0], []) self.assertFalse(res) res = CommutationChecker().commute(XGate(), [0], [], MCXGate(29), list(range(30)), []) self.assertFalse(res) def test_wide_gates_over_disjoint_qubits(self): """Test that wide gates still commute when they are over disjoint sets of qubits.""" res = CommutationChecker().commute(MCXGate(29), list(range(30)), [], XGate(), [30], []) self.assertTrue(res) res = CommutationChecker().commute(XGate(), [30], [], MCXGate(29), list(range(30)), []) self.assertTrue(res) if __name__ == "__main__": unittest.main()
https://github.com/swe-train/qiskit__qiskit
swe-train
# 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. # pylint: disable=invalid-name """Test QuantumCircuit.compose().""" import unittest import numpy as np from qiskit import transpile from qiskit.pulse import Schedule from qiskit.circuit import ( QuantumRegister, ClassicalRegister, Clbit, QuantumCircuit, Qubit, Parameter, Gate, Instruction, CASE_DEFAULT, SwitchCaseOp, ) from qiskit.circuit.library import HGate, RZGate, CXGate, CCXGate, TwoLocal from qiskit.circuit.classical import expr from qiskit.test import QiskitTestCase class TestCircuitCompose(QiskitTestCase): """Test composition of two circuits.""" def setUp(self): super().setUp() qreg1 = QuantumRegister(3, "lqr_1") qreg2 = QuantumRegister(2, "lqr_2") creg = ClassicalRegister(2, "lcr") self.circuit_left = QuantumCircuit(qreg1, qreg2, creg) self.circuit_left.h(qreg1[0]) self.circuit_left.x(qreg1[1]) self.circuit_left.p(0.1, qreg1[2]) self.circuit_left.cx(qreg2[0], qreg2[1]) self.left_qubit0 = qreg1[0] self.left_qubit1 = qreg1[1] self.left_qubit2 = qreg1[2] self.left_qubit3 = qreg2[0] self.left_qubit4 = qreg2[1] self.left_clbit0 = creg[0] self.left_clbit1 = creg[1] self.condition = (creg, 3) def test_compose_inorder(self): """Composing two circuits of the same width, default order. ┌───┐ lqr_1_0: |0>──┤ H ├─── rqr_0: |0>──■─────── ├───┤ │ ┌───┐ lqr_1_1: |0>──┤ X ├─── rqr_1: |0>──┼──┤ X ├ ┌─┴───┴──┐ │ ├───┤ lqr_1_2: |0>┤ P(0.1) ├ + rqr_2: |0>──┼──┤ Y ├ = └────────┘ ┌─┴─┐└───┘ lqr_2_0: |0>────■───── rqr_3: |0>┤ X ├───── ┌─┴─┐ └───┘┌───┐ lqr_2_1: |0>──┤ X ├─── rqr_4: |0>─────┤ Z ├ └───┘ └───┘ lcr_0: 0 ═══════════ lcr_1: 0 ═══════════ ┌───┐ lqr_1_0: |0>──┤ H ├─────■─────── ├───┤ │ ┌───┐ lqr_1_1: |0>──┤ X ├─────┼──┤ X ├ ┌─┴───┴──┐ │ ├───┤ lqr_1_2: |0>┤ P(0.1) ├──┼──┤ Y ├ └────────┘┌─┴─┐└───┘ lqr_2_0: |0>────■─────┤ X ├───── ┌─┴─┐ └───┘┌───┐ lqr_2_1: |0>──┤ X ├────────┤ Z ├ └───┘ └───┘ lcr_0: 0 ═══════════════════════ lcr_1: 0 ═══════════════════════ """ qreg = QuantumRegister(5, "rqr") circuit_right = QuantumCircuit(qreg) circuit_right.cx(qreg[0], qreg[3]) circuit_right.x(qreg[1]) circuit_right.y(qreg[2]) circuit_right.z(qreg[4]) circuit_expected = self.circuit_left.copy() circuit_expected.cx(self.left_qubit0, self.left_qubit3) circuit_expected.x(self.left_qubit1) circuit_expected.y(self.left_qubit2) circuit_expected.z(self.left_qubit4) circuit_composed = self.circuit_left.compose(circuit_right, inplace=False) self.assertEqual(circuit_composed, circuit_expected) def test_compose_inorder_unusual_types(self): """Test that composition works in order, using Numpy integer types as well as regular integer types. In general, it should be permissible to use any of the same `QubitSpecifier` types (or similar for `Clbit`) that `QuantumCircuit.append` uses.""" qreg = QuantumRegister(5, "rqr") creg = ClassicalRegister(2, "rcr") circuit_right = QuantumCircuit(qreg, creg) circuit_right.cx(qreg[0], qreg[3]) circuit_right.x(qreg[1]) circuit_right.y(qreg[2]) circuit_right.z(qreg[4]) circuit_right.measure([0, 1], [0, 1]) circuit_expected = self.circuit_left.copy() circuit_expected.cx(self.left_qubit0, self.left_qubit3) circuit_expected.x(self.left_qubit1) circuit_expected.y(self.left_qubit2) circuit_expected.z(self.left_qubit4) circuit_expected.measure(self.left_qubit0, self.left_clbit0) circuit_expected.measure(self.left_qubit1, self.left_clbit1) circuit_composed = self.circuit_left.compose(circuit_right, np.arange(5), slice(0, 2)) self.assertEqual(circuit_composed, circuit_expected) def test_compose_inorder_inplace(self): """Composing two circuits of the same width, default order, inplace. ┌───┐ lqr_1_0: |0>───┤ H ├─── rqr_0: |0>──■─────── ├───┤ │ ┌───┐ lqr_1_1: |0>───┤ X ├─── rqr_1: |0>──┼──┤ X ├ ┌──┴───┴──┐ │ ├───┤ lqr_1_2: |0>┤ U1(0.1) ├ + rqr_2: |0>──┼──┤ Y ├ = └─────────┘ ┌─┴─┐└───┘ lqr_2_0: |0>─────■───── rqr_3: |0>┤ X ├───── ┌─┴─┐ └───┘┌───┐ lqr_2_1: |0>───┤ X ├─── rqr_4: |0>─────┤ Z ├ └───┘ └───┘ lcr_0: 0 ═══════════ lcr_1: 0 ═══════════ ┌───┐ lqr_1_0: |0>───┤ H ├─────■─────── ├───┤ │ ┌───┐ lqr_1_1: |0>───┤ X ├─────┼──┤ X ├ ┌──┴───┴──┐ │ ├───┤ lqr_1_2: |0>┤ U1(0.1) ├──┼──┤ Y ├ └─────────┘┌─┴─┐└───┘ lqr_2_0: |0>─────■─────┤ X ├───── ┌─┴─┐ └───┘┌───┐ lqr_2_1: |0>───┤ X ├────────┤ Z ├ └───┘ └───┘ lcr_0: 0 ════════════════════════ lcr_1: 0 ════════════════════════ """ qreg = QuantumRegister(5, "rqr") circuit_right = QuantumCircuit(qreg) circuit_right.cx(qreg[0], qreg[3]) circuit_right.x(qreg[1]) circuit_right.y(qreg[2]) circuit_right.z(qreg[4]) circuit_expected = self.circuit_left.copy() circuit_expected.cx(self.left_qubit0, self.left_qubit3) circuit_expected.x(self.left_qubit1) circuit_expected.y(self.left_qubit2) circuit_expected.z(self.left_qubit4) # inplace circuit_left = self.circuit_left.copy() circuit_left.compose(circuit_right, inplace=True) self.assertEqual(circuit_left, circuit_expected) def test_compose_inorder_smaller(self): """Composing with a smaller RHS dag, default order. ┌───┐ ┌─────┐ lqr_1_0: |0>───┤ H ├─── rqr_0: |0>──■──┤ Tdg ├ ├───┤ ┌─┴─┐└─────┘ lqr_1_1: |0>───┤ X ├─── rqr_1: |0>┤ X ├─────── ┌──┴───┴──┐ └───┘ lqr_1_2: |0>┤ U1(0.1) ├ + = └─────────┘ lqr_2_0: |0>─────■───── ┌─┴─┐ lqr_2_1: |0>───┤ X ├─── └───┘ lcr_0: 0 ══════════════ lcr_1: 0 ══════════════ ┌───┐ ┌─────┐ lqr_1_0: |0>───┤ H ├─────■──┤ Tdg ├ ├───┤ ┌─┴─┐└─────┘ lqr_1_1: |0>───┤ X ├───┤ X ├─────── ┌──┴───┴──┐└───┘ lqr_1_2: |0>┤ U1(0.1) ├──────────── └─────────┘ lqr_2_0: |0>─────■───────────────── ┌─┴─┐ lqr_2_1: |0>───┤ X ├─────────────── └───┘ lcr_0: 0 ══════════════════════════ lcr_1: 0 ══════════════════════════ """ qreg = QuantumRegister(2, "rqr") circuit_right = QuantumCircuit(qreg) circuit_right.cx(qreg[0], qreg[1]) circuit_right.tdg(qreg[0]) circuit_expected = self.circuit_left.copy() circuit_expected.cx(self.left_qubit0, self.left_qubit1) circuit_expected.tdg(self.left_qubit0) circuit_composed = self.circuit_left.compose(circuit_right) self.assertEqual(circuit_composed, circuit_expected) def test_compose_permuted(self): """Composing two dags of the same width, permuted wires. ┌───┐ lqr_1_0: |0>──┤ H ├─── rqr_0: |0>──■─────── ├───┤ │ ┌───┐ lqr_1_1: |0>──┤ X ├─── rqr_1: |0>──┼──┤ X ├ ┌─┴───┴──┐ │ ├───┤ lqr_1_2: |0>┤ P(0.1) ├ rqr_2: |0>──┼──┤ Y ├ └────────┘ ┌─┴─┐└───┘ lqr_2_0: |0>────■───── + rqr_3: |0>┤ X ├───── = ┌─┴─┐ └───┘┌───┐ lqr_2_1: |0>──┤ X ├─── rqr_4: |0>─────┤ Z ├ └───┘ └───┘ lcr_0: 0 ══════════════ lcr_1: 0 ══════════════ ┌───┐ ┌───┐ lqr_1_0: |0>──┤ H ├───┤ Z ├ ├───┤ ├───┤ lqr_1_1: |0>──┤ X ├───┤ X ├ ┌─┴───┴──┐├───┤ lqr_1_2: |0>┤ P(0.1) ├┤ Y ├ └────────┘└───┘ lqr_2_0: |0>────■───────■── ┌─┴─┐ ┌─┴─┐ lqr_2_1: |0>──┤ X ├───┤ X ├ └───┘ └───┘ lcr_0: 0 ══════════════════ lcr_1: 0 ══════════════════ """ qreg = QuantumRegister(5, "rqr") circuit_right = QuantumCircuit(qreg) circuit_right.cx(qreg[0], qreg[3]) circuit_right.x(qreg[1]) circuit_right.y(qreg[2]) circuit_right.z(qreg[4]) circuit_expected = self.circuit_left.copy() circuit_expected.z(self.left_qubit0) circuit_expected.x(self.left_qubit1) circuit_expected.y(self.left_qubit2) circuit_expected.cx(self.left_qubit3, self.left_qubit4) # permuted wiring circuit_composed = self.circuit_left.compose( circuit_right, qubits=[ self.left_qubit3, self.left_qubit1, self.left_qubit2, self.left_qubit4, self.left_qubit0, ], inplace=False, ) self.assertEqual(circuit_composed, circuit_expected) def test_compose_permuted_smaller(self): """Composing with a smaller RHS dag, and permuted wires. Compose using indices. ┌───┐ ┌─────┐ lqr_1_0: |0>──┤ H ├─── rqr_0: |0>──■──┤ Tdg ├ ├───┤ ┌─┴─┐└─────┘ lqr_1_1: |0>──┤ X ├─── rqr_1: |0>┤ X ├─────── ┌─┴───┴──┐ └───┘ lqr_1_2: |0>┤ P(0.1) ├ + = └────────┘ lqr_2_0: |0>────■───── ┌─┴─┐ lqr_2_1: |0>──┤ X ├─── └───┘ lcr_0: 0 ═════════════ lcr_1: 0 ═════════════ ┌───┐ lqr_1_0: |0>──┤ H ├─────────────── ├───┤ lqr_1_1: |0>──┤ X ├─────────────── ┌─┴───┴──┐┌───┐ lqr_1_2: |0>┤ P(0.1) ├┤ X ├─────── └────────┘└─┬─┘┌─────┐ lqr_2_0: |0>────■───────■──┤ Tdg ├ ┌─┴─┐ └─────┘ lqr_2_1: |0>──┤ X ├─────────────── └───┘ lcr_0: 0 ═════════════════════════ lcr_1: 0 ═════════════════════════ """ qreg = QuantumRegister(2, "rqr") circuit_right = QuantumCircuit(qreg) circuit_right.cx(qreg[0], qreg[1]) circuit_right.tdg(qreg[0]) # permuted wiring of subset circuit_composed = self.circuit_left.compose(circuit_right, qubits=[3, 2]) circuit_expected = self.circuit_left.copy() circuit_expected.cx(self.left_qubit3, self.left_qubit2) circuit_expected.tdg(self.left_qubit3) self.assertEqual(circuit_composed, circuit_expected) def test_compose_classical(self): """Composing on classical bits. ┌───┐ ┌─────┐┌─┐ lqr_1_0: |0>──┤ H ├─── rqr_0: |0>──■──┤ Tdg ├┤M├ ├───┤ ┌─┴─┐└─┬─┬─┘└╥┘ lqr_1_1: |0>──┤ X ├─── rqr_1: |0>┤ X ├──┤M├───╫─ ┌─┴───┴──┐ └───┘ └╥┘ ║ lqr_1_2: |0>┤ P(0.1) ├ + rcr_0: 0 ════════╬════╩═ = └────────┘ ║ lqr_2_0: |0>────■───── rcr_1: 0 ════════╩══════ ┌─┴─┐ lqr_2_1: |0>──┤ X ├─── └───┘ lcr_0: 0 ══════════════ lcr_1: 0 ══════════════ ┌───┐ lqr_1_0: |0>──┤ H ├────────────────── ├───┤ ┌─────┐┌─┐ lqr_1_1: |0>──┤ X ├─────■──┤ Tdg ├┤M├ ┌─┴───┴──┐ │ └─────┘└╥┘ lqr_1_2: |0>┤ P(0.1) ├──┼──────────╫─ └────────┘ │ ║ lqr_2_0: |0>────■───────┼──────────╫─ ┌─┴─┐ ┌─┴─┐ ┌─┐ ║ lqr_2_1: |0>──┤ X ├───┤ X ├──┤M├───╫─ └───┘ └───┘ └╥┘ ║ lcr_0: 0 ══════════════════╩════╬═ ║ lcr_1: 0 ═══════════════════════╩═ """ qreg = QuantumRegister(2, "rqr") creg = ClassicalRegister(2, "rcr") circuit_right = QuantumCircuit(qreg, creg) circuit_right.cx(qreg[0], qreg[1]) circuit_right.tdg(qreg[0]) circuit_right.measure(qreg, creg) # permuted subset of qubits and clbits circuit_composed = self.circuit_left.compose(circuit_right, qubits=[1, 4], clbits=[1, 0]) circuit_expected = self.circuit_left.copy() circuit_expected.cx(self.left_qubit1, self.left_qubit4) circuit_expected.tdg(self.left_qubit1) circuit_expected.measure(self.left_qubit4, self.left_clbit0) circuit_expected.measure(self.left_qubit1, self.left_clbit1) self.assertEqual(circuit_composed, circuit_expected) def test_compose_conditional(self): """Composing on classical bits. ┌───┐ ┌───┐ ┌─┐ lqr_1_0: |0>──┤ H ├─── rqr_0: ────────┤ H ├─┤M├─── ├───┤ ┌───┐ └─┬─┘ └╥┘┌─┐ lqr_1_1: |0>──┤ X ├─── rqr_1: ─┤ X ├────┼────╫─┤M├ ┌─┴───┴──┐ └─┬─┘ │ ║ └╥┘ lqr_1_2: |0>┤ P(0.1) ├ + ┌──┴──┐┌──┴──┐ ║ ║ └────────┘ rcr_0: ╡ ╞╡ ╞═╩══╬═ lqr_2_0: |0>────■───── │ = 3 ││ = 3 │ ║ ┌─┴─┐ rcr_1: ╡ ╞╡ ╞════╩═ lqr_2_1: |0>──┤ X ├─── └─────┘└─────┘ └───┘ lcr_0: 0 ══════════════ lcr_1: 0 ══════════════ ┌───┐ lqr_1_0: ──┤ H ├─────────────────────── ├───┤ ┌───┐ ┌─┐ lqr_1_1: ──┤ X ├───────────┤ H ├────┤M├ ┌─┴───┴──┐ └─┬─┘ └╥┘ lqr_1_2: ┤ P(0.1) ├──────────┼───────╫─ └────────┘ │ ║ lqr_2_0: ────■───────────────┼───────╫─ ┌─┴─┐ ┌───┐ │ ┌─┐ ║ lqr_2_1: ──┤ X ├────┤ X ├────┼───┤M├─╫─ └───┘ └─┬─┘ │ └╥┘ ║ ┌──┴──┐┌──┴──┐ ║ ║ lcr_0: ════════════╡ ╞╡ ╞═╬══╩═ │ = 3 ││ = 3 │ ║ lcr_1: ════════════╡ ╞╡ ╞═╩════ └─────┘└─────┘ """ qreg = QuantumRegister(2, "rqr") creg = ClassicalRegister(2, "rcr") circuit_right = QuantumCircuit(qreg, creg) circuit_right.x(qreg[1]).c_if(creg, 3) circuit_right.h(qreg[0]).c_if(creg, 3) circuit_right.measure(qreg, creg) # permuted subset of qubits and clbits circuit_composed = self.circuit_left.compose(circuit_right, qubits=[1, 4], clbits=[0, 1]) circuit_expected = self.circuit_left.copy() circuit_expected.x(self.left_qubit4).c_if(*self.condition) circuit_expected.h(self.left_qubit1).c_if(*self.condition) circuit_expected.measure(self.left_qubit1, self.left_clbit0) circuit_expected.measure(self.left_qubit4, self.left_clbit1) self.assertEqual(circuit_composed, circuit_expected) def test_compose_conditional_no_match(self): """Test that compose correctly maps registers in conditions to the new circuit, even when there are no matching registers in the destination circuit. Regression test of gh-6583 and gh-6584.""" right = QuantumCircuit(QuantumRegister(3), ClassicalRegister(1), ClassicalRegister(1)) right.h(1) right.cx(1, 2) right.cx(0, 1) right.h(0) right.measure([0, 1], [0, 1]) right.z(2).c_if(right.cregs[0], 1) right.x(2).c_if(right.cregs[1], 1) test = QuantumCircuit(3, 3).compose(right, range(3), range(2)) z = next(ins.operation for ins in test.data[::-1] if ins.operation.name == "z") x = next(ins.operation for ins in test.data[::-1] if ins.operation.name == "x") # The registers should have been mapped, including the bits inside them. Unlike the # previous test, there are no matching registers in the destination circuit, so the # composition needs to add new registers (bit groupings) over the existing mapped bits. self.assertIsNot(z.condition, None) self.assertIsInstance(z.condition[0], ClassicalRegister) self.assertEqual(len(z.condition[0]), len(right.cregs[0])) self.assertIs(z.condition[0][0], test.clbits[0]) self.assertEqual(z.condition[1], 1) self.assertIsNot(x.condition, None) self.assertIsInstance(x.condition[0], ClassicalRegister) self.assertEqual(len(x.condition[0]), len(right.cregs[1])) self.assertEqual(z.condition[1], 1) self.assertIs(x.condition[0][0], test.clbits[1]) def test_compose_switch_match(self): """Test that composition containing a `switch` with a register that matches proceeds correctly.""" case_0 = QuantumCircuit(1, 2) case_0.x(0) case_1 = QuantumCircuit(1, 2) case_1.z(0) case_default = QuantumCircuit(1, 2) cr = ClassicalRegister(2, "target") right = QuantumCircuit(QuantumRegister(1), cr) right.switch(cr, [(0, case_0), (1, case_1), (CASE_DEFAULT, case_default)], [0], [0, 1]) test = QuantumCircuit(QuantumRegister(3), cr, ClassicalRegister(2)).compose( right, [1], [0, 1] ) expected = test.copy_empty_like() expected.switch(cr, [(0, case_0), (1, case_1), (CASE_DEFAULT, case_default)], [1], [0, 1]) self.assertEqual(test, expected) def test_compose_switch_no_match(self): """Test that composition containing a `switch` with a register that matches proceeds correctly.""" case_0 = QuantumCircuit(1, 2) case_0.x(0) case_1 = QuantumCircuit(1, 2) case_1.z(0) case_default = QuantumCircuit(1, 2) cr = ClassicalRegister(2, "target") right = QuantumCircuit(QuantumRegister(1), cr) right.switch(cr, [(0, case_0), (1, case_1), (CASE_DEFAULT, case_default)], [0], [0, 1]) test = QuantumCircuit(3, 3).compose(right, [1], [0, 1]) self.assertEqual(len(test.data), 1) self.assertIsInstance(test.data[0].operation, SwitchCaseOp) target = test.data[0].operation.target self.assertIn(target, test.cregs) self.assertEqual(list(target), test.clbits[0:2]) def test_compose_gate(self): """Composing with a gate. ┌───┐ ┌───┐ ┌───┐ lqr_1_0: ──┤ H ├─── lqr_1_0: ──┤ H ├────┤ X ├ ├───┤ ├───┤ └─┬─┘ lqr_1_1: ──┤ X ├─── lqr_1_1: ──┤ X ├──────┼─── ┌─┴───┴──┐ ───■─── ┌─┴───┴──┐ │ lqr_1_2: ┤ P(0.1) ├ + ┌─┴─┐ = lqr_1_2: ┤ P(0.1) ├───┼─── └────────┘ ─┤ X ├─ └────────┘ │ lqr_2_0: ────■───── └───┘ lqr_2_0: ────■────────┼── ┌─┴─┐ ┌─┴─┐ │ lqr_2_1: ──┤ X ├─── lqr_2_1: ──┤ X ├──────■─── └───┘ └───┘ lcr_0: 0 ══════════ lcr_0: 0 ═════════════════ lcr_1: 0 ══════════ lcr_1: 0 ═════════════════ """ circuit_composed = self.circuit_left.compose(CXGate(), qubits=[4, 0]) circuit_expected = self.circuit_left.copy() circuit_expected.cx(self.left_qubit4, self.left_qubit0) self.assertEqual(circuit_composed, circuit_expected) def test_compose_calibrations(self): """Test that composing two circuits updates calibrations.""" circ_left = QuantumCircuit(1) circ_left.add_calibration("h", [0], None) circ_right = QuantumCircuit(1) circ_right.add_calibration("rx", [0], None) circ = circ_left.compose(circ_right) self.assertEqual(len(circ.calibrations), 2) self.assertEqual(len(circ_left.calibrations), 1) circ_left = QuantumCircuit(1) circ_left.add_calibration("h", [0], None) circ_right = QuantumCircuit(1) circ_right.add_calibration("h", [1], None) circ = circ_left.compose(circ_right) self.assertEqual(len(circ.calibrations), 1) self.assertEqual(len(circ.calibrations["h"]), 2) self.assertEqual(len(circ_left.calibrations), 1) # Ensure that transpiled _calibration is defaultdict qc = QuantumCircuit(2, 2) qc.h(0) qc.cx(0, 1) qc.measure(0, 0) qc = transpile(qc, None, basis_gates=["h", "cx"], coupling_map=[[0, 1], [1, 0]]) qc.add_calibration("cx", [0, 1], Schedule()) def test_compose_one_liner(self): """Test building a circuit in one line, for fun.""" circ = QuantumCircuit(3) h = HGate() rz = RZGate(0.1) cx = CXGate() ccx = CCXGate() circ = circ.compose(h, [0]).compose(cx, [0, 2]).compose(ccx, [2, 1, 0]).compose(rz, [1]) expected = QuantumCircuit(3) expected.h(0) expected.cx(0, 2) expected.ccx(2, 1, 0) expected.rz(0.1, 1) self.assertEqual(circ, expected) def test_compose_global_phase(self): """Composing with global phase.""" circ1 = QuantumCircuit(1, global_phase=1) circ1.rz(0.5, 0) circ2 = QuantumCircuit(1, global_phase=2) circ3 = QuantumCircuit(1, global_phase=3) circ4 = circ1.compose(circ2).compose(circ3) self.assertEqual( circ4.global_phase, circ1.global_phase + circ2.global_phase + circ3.global_phase ) def test_compose_front_circuit(self): """Test composing a circuit at the front of a circuit.""" qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) other = QuantumCircuit(2) other.cz(1, 0) other.z(1) output = qc.compose(other, front=True) expected = QuantumCircuit(2) expected.cz(1, 0) expected.z(1) expected.h(0) expected.cx(0, 1) self.assertEqual(output, expected) def test_compose_front_gate(self): """Test composing a gate at the front of a circuit.""" qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) output = qc.compose(CXGate(), [1, 0], front=True) expected = QuantumCircuit(2) expected.cx(1, 0) expected.h(0) expected.cx(0, 1) self.assertEqual(output, expected) def test_compose_adds_parameters(self): """Test the composed circuit contains all parameters.""" a, b = Parameter("a"), Parameter("b") qc_a = QuantumCircuit(1) qc_a.rx(a, 0) qc_b = QuantumCircuit(1) qc_b.rx(b, 0) with self.subTest("compose with other circuit out-of-place"): qc_1 = qc_a.compose(qc_b) self.assertEqual(qc_1.parameters, {a, b}) with self.subTest("compose with other instruction out-of-place"): instr_b = qc_b.to_instruction() qc_2 = qc_a.compose(instr_b, [0]) self.assertEqual(qc_2.parameters, {a, b}) with self.subTest("compose with other circuit in-place"): qc_a.compose(qc_b, inplace=True) self.assertEqual(qc_a.parameters, {a, b}) def test_wrapped_compose(self): """Test wrapping the circuit upon composition works.""" qc_a = QuantumCircuit(1) qc_a.x(0) qc_b = QuantumCircuit(1, name="B") qc_b.h(0) qc_a.compose(qc_b, wrap=True, inplace=True) self.assertDictEqual(qc_a.count_ops(), {"B": 1, "x": 1}) self.assertDictEqual(qc_a.decompose().count_ops(), {"h": 1, "u3": 1}) def test_wrapping_unitary_circuit(self): """Test a unitary circuit will be wrapped as Gate, else as Instruction.""" qc_init = QuantumCircuit(1) qc_init.x(0) qc_unitary = QuantumCircuit(1, name="a") qc_unitary.ry(0.23, 0) qc_nonunitary = QuantumCircuit(1) qc_nonunitary.reset(0) with self.subTest("wrapping a unitary circuit"): qc = qc_init.compose(qc_unitary, wrap=True) self.assertIsInstance(qc.data[1].operation, Gate) with self.subTest("wrapping a non-unitary circuit"): qc = qc_init.compose(qc_nonunitary, wrap=True) self.assertIsInstance(qc.data[1].operation, Instruction) def test_single_bit_condition(self): """Test that compose can correctly handle circuits that contain conditions on single bits. This is a regression test of the bug that broke qiskit-experiments in gh-7653.""" base = QuantumCircuit(1, 1) base.x(0).c_if(0, True) test = QuantumCircuit(1, 1).compose(base) self.assertIsNot(base.clbits[0], test.clbits[0]) self.assertEqual(base, test) self.assertIs(test.data[0].operation.condition[0], test.clbits[0]) def test_condition_mapping_ifelseop(self): """Test that the condition in an `IfElseOp` is correctly mapped to a new set of bits and registers.""" base_loose = Clbit() base_creg = ClassicalRegister(2) base_qreg = QuantumRegister(1) base = QuantumCircuit(base_qreg, [base_loose], base_creg) with base.if_test((base_loose, True)): base.x(0) with base.if_test((base_creg, 3)): base.x(0) test_loose = Clbit() test_creg = ClassicalRegister(2) test_qreg = QuantumRegister(1) test = QuantumCircuit(test_qreg, [test_loose], test_creg).compose(base) bit_instruction = test.data[0].operation reg_instruction = test.data[1].operation self.assertIs(bit_instruction.condition[0], test_loose) self.assertEqual(bit_instruction.condition, (test_loose, True)) self.assertIs(reg_instruction.condition[0], test_creg) self.assertEqual(reg_instruction.condition, (test_creg, 3)) def test_condition_mapping_whileloopop(self): """Test that the condition in a `WhileLoopOp` is correctly mapped to a new set of bits and registers.""" base_loose = Clbit() base_creg = ClassicalRegister(2) base_qreg = QuantumRegister(1) base = QuantumCircuit(base_qreg, [base_loose], base_creg) with base.while_loop((base_loose, True)): base.x(0) with base.while_loop((base_creg, 3)): base.x(0) test_loose = Clbit() test_creg = ClassicalRegister(2) test_qreg = QuantumRegister(1) test = QuantumCircuit(test_qreg, [test_loose], test_creg).compose(base) bit_instruction = test.data[0].operation reg_instruction = test.data[1].operation self.assertIs(bit_instruction.condition[0], test_loose) self.assertEqual(bit_instruction.condition, (test_loose, True)) self.assertIs(reg_instruction.condition[0], test_creg) self.assertEqual(reg_instruction.condition, (test_creg, 3)) def test_compose_no_clbits_in_one(self): """Test combining a circuit with cregs to one without""" ansatz = TwoLocal(2, rotation_blocks="ry", entanglement_blocks="cx") qc = QuantumCircuit(2) qc.measure_all() out = ansatz.compose(qc) self.assertEqual(out.clbits, qc.clbits) def test_compose_no_clbits_in_one_inplace(self): """Test combining a circuit with cregs to one without inplace""" ansatz = TwoLocal(2, rotation_blocks="ry", entanglement_blocks="cx") qc = QuantumCircuit(2) qc.measure_all() ansatz.compose(qc, inplace=True) self.assertEqual(ansatz.clbits, qc.clbits) def test_compose_no_clbits_in_one_multireg(self): """Test combining a circuit with cregs to one without, multi cregs""" ansatz = TwoLocal(2, rotation_blocks="ry", entanglement_blocks="cx") qa = QuantumRegister(2, "q") ca = ClassicalRegister(2, "a") cb = ClassicalRegister(2, "b") qc = QuantumCircuit(qa, ca, cb) qc.measure(0, cb[1]) out = ansatz.compose(qc) self.assertEqual(out.clbits, qc.clbits) self.assertEqual(out.cregs, qc.cregs) def test_compose_noclbits_registerless(self): """Combining a circuit with cregs to one without, registerless case""" inner = QuantumCircuit([Qubit(), Qubit()], [Clbit(), Clbit()]) inner.measure([0, 1], [0, 1]) outer = QuantumCircuit(2) outer.compose(inner, inplace=True) self.assertEqual(outer.clbits, inner.clbits) self.assertEqual(outer.cregs, []) def test_expr_condition_is_mapped(self): """Test that an expression in a condition involving several registers is mapped correctly to the destination circuit.""" inner = QuantumCircuit(1) inner.x(0) a_src = ClassicalRegister(2, "a_src") b_src = ClassicalRegister(2, "b_src") c_src = ClassicalRegister(name="c_src", bits=list(a_src) + list(b_src)) source = QuantumCircuit(QuantumRegister(1), a_src, b_src, c_src) test_1 = lambda: expr.lift(a_src[0]) test_2 = lambda: expr.logic_not(b_src[1]) test_3 = lambda: expr.logic_and(expr.bit_and(b_src, 2), expr.less(c_src, 7)) source.if_test(test_1(), inner.copy(), [0], []) source.if_else(test_2(), inner.copy(), inner.copy(), [0], []) source.while_loop(test_3(), inner.copy(), [0], []) a_dest = ClassicalRegister(2, "a_dest") b_dest = ClassicalRegister(2, "b_dest") dest = QuantumCircuit(QuantumRegister(1), a_dest, b_dest).compose(source) # Check that the input conditions weren't mutated. for in_condition, instruction in zip((test_1, test_2, test_3), source.data): self.assertEqual(in_condition(), instruction.operation.condition) # Should be `a_dest`, `b_dest` and an added one to account for `c_src`. self.assertEqual(len(dest.cregs), 3) mapped_reg = dest.cregs[-1] expected = QuantumCircuit(dest.qregs[0], a_dest, b_dest, mapped_reg) expected.if_test(expr.lift(a_dest[0]), inner.copy(), [0], []) expected.if_else(expr.logic_not(b_dest[1]), inner.copy(), inner.copy(), [0], []) expected.while_loop( expr.logic_and(expr.bit_and(b_dest, 2), expr.less(mapped_reg, 7)), inner.copy(), [0], [] ) self.assertEqual(dest, expected) def test_expr_target_is_mapped(self): """Test that an expression in a switch statement's target is mapping correctly to the destination circuit.""" inner1 = QuantumCircuit(1) inner1.x(0) inner2 = QuantumCircuit(1) inner2.z(0) a_src = ClassicalRegister(2, "a_src") b_src = ClassicalRegister(2, "b_src") c_src = ClassicalRegister(name="c_src", bits=list(a_src) + list(b_src)) source = QuantumCircuit(QuantumRegister(1), a_src, b_src, c_src) test_1 = lambda: expr.lift(a_src[0]) test_2 = lambda: expr.logic_not(b_src[1]) test_3 = lambda: expr.lift(b_src) test_4 = lambda: expr.bit_and(c_src, 7) source.switch(test_1(), [(False, inner1.copy()), (True, inner2.copy())], [0], []) source.switch(test_2(), [(False, inner1.copy()), (True, inner2.copy())], [0], []) source.switch(test_3(), [(0, inner1.copy()), (CASE_DEFAULT, inner2.copy())], [0], []) source.switch(test_4(), [(0, inner1.copy()), (CASE_DEFAULT, inner2.copy())], [0], []) a_dest = ClassicalRegister(2, "a_dest") b_dest = ClassicalRegister(2, "b_dest") dest = QuantumCircuit(QuantumRegister(1), a_dest, b_dest).compose(source) # Check that the input expressions weren't mutated. for in_target, instruction in zip((test_1, test_2, test_3, test_4), source.data): self.assertEqual(in_target(), instruction.operation.target) # Should be `a_dest`, `b_dest` and an added one to account for `c_src`. self.assertEqual(len(dest.cregs), 3) mapped_reg = dest.cregs[-1] expected = QuantumCircuit(dest.qregs[0], a_dest, b_dest, mapped_reg) expected.switch( expr.lift(a_dest[0]), [(False, inner1.copy()), (True, inner2.copy())], [0], [] ) expected.switch( expr.logic_not(b_dest[1]), [(False, inner1.copy()), (True, inner2.copy())], [0], [] ) expected.switch( expr.lift(b_dest), [(0, inner1.copy()), (CASE_DEFAULT, inner2.copy())], [0], [] ) expected.switch( expr.bit_and(mapped_reg, 7), [(0, inner1.copy()), (CASE_DEFAULT, inner2.copy())], [0], [], ) self.assertEqual(dest, expected) if __name__ == "__main__": unittest.main()
https://github.com/swe-train/qiskit__qiskit
swe-train
# 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. """Test Qiskit's controlled gate operation.""" import unittest from test import combine import numpy as np from numpy import pi from ddt import ddt, data, unpack from qiskit import QuantumRegister, QuantumCircuit, execute, BasicAer, QiskitError from qiskit.test import QiskitTestCase from qiskit.circuit import ControlledGate, Parameter, Gate from qiskit.circuit.exceptions import CircuitError from qiskit.quantum_info.operators.predicates import matrix_equal, is_unitary_matrix from qiskit.quantum_info.random import random_unitary from qiskit.quantum_info.states import Statevector import qiskit.circuit.add_control as ac from qiskit.transpiler.passes import Unroller from qiskit.converters.circuit_to_dag import circuit_to_dag from qiskit.converters.dag_to_circuit import dag_to_circuit from qiskit.quantum_info import Operator from qiskit.circuit.library import ( CXGate, XGate, YGate, ZGate, U1Gate, CYGate, CZGate, CU1Gate, SwapGate, PhaseGate, CCXGate, HGate, RZGate, RXGate, CPhaseGate, RYGate, CRYGate, CRXGate, CSwapGate, UGate, U3Gate, CHGate, CRZGate, CU3Gate, CUGate, SXGate, CSXGate, MSGate, Barrier, RCCXGate, RC3XGate, MCU1Gate, MCXGate, MCXGrayCode, MCXRecursive, MCXVChain, C3XGate, C3SXGate, C4XGate, MCPhaseGate, GlobalPhaseGate, ) from qiskit.circuit._utils import _compute_control_matrix import qiskit.circuit.library.standard_gates as allGates from qiskit.extensions import UnitaryGate from qiskit.circuit.library.standard_gates.multi_control_rotation_gates import _mcsu2_real_diagonal from .gate_utils import _get_free_params @ddt class TestControlledGate(QiskitTestCase): """Tests for controlled gates and the ControlledGate class.""" def test_controlled_x(self): """Test creation of controlled x gate""" self.assertEqual(XGate().control(), CXGate()) def test_controlled_y(self): """Test creation of controlled y gate""" self.assertEqual(YGate().control(), CYGate()) def test_controlled_z(self): """Test creation of controlled z gate""" self.assertEqual(ZGate().control(), CZGate()) def test_controlled_h(self): """Test the creation of a controlled H gate.""" self.assertEqual(HGate().control(), CHGate()) def test_controlled_phase(self): """Test the creation of a controlled U1 gate.""" theta = 0.5 self.assertEqual(PhaseGate(theta).control(), CPhaseGate(theta)) def test_double_controlled_phase(self): """Test the creation of a controlled phase gate.""" theta = 0.5 self.assertEqual(PhaseGate(theta).control(2), MCPhaseGate(theta, 2)) def test_controlled_u1(self): """Test the creation of a controlled U1 gate.""" theta = 0.5 self.assertEqual(U1Gate(theta).control(), CU1Gate(theta)) circ = QuantumCircuit(1) circ.append(U1Gate(theta), circ.qregs[0]) unroller = Unroller(["cx", "u", "p"]) ctrl_circ_gate = dag_to_circuit(unroller.run(circuit_to_dag(circ))).control() ctrl_circ = QuantumCircuit(2) ctrl_circ.append(ctrl_circ_gate, ctrl_circ.qregs[0]) ctrl_circ = ctrl_circ.decompose().decompose() self.assertEqual(ctrl_circ.size(), 1) def test_controlled_rz(self): """Test the creation of a controlled RZ gate.""" theta = 0.5 self.assertEqual(RZGate(theta).control(), CRZGate(theta)) def test_control_parameters(self): """Test different ctrl_state formats for control function.""" theta = 0.5 self.assertEqual( CRYGate(theta).control(2, ctrl_state="01"), CRYGate(theta).control(2, ctrl_state=1) ) self.assertEqual( CRYGate(theta).control(2, ctrl_state=None), CRYGate(theta).control(2, ctrl_state=3) ) self.assertEqual(CCXGate().control(2, ctrl_state="01"), CCXGate().control(2, ctrl_state=1)) self.assertEqual(CCXGate().control(2, ctrl_state=None), CCXGate().control(2, ctrl_state=3)) def test_controlled_ry(self): """Test the creation of a controlled RY gate.""" theta = 0.5 self.assertEqual(RYGate(theta).control(), CRYGate(theta)) def test_controlled_rx(self): """Test the creation of a controlled RX gate.""" theta = 0.5 self.assertEqual(RXGate(theta).control(), CRXGate(theta)) def test_controlled_u(self): """Test the creation of a controlled U gate.""" theta, phi, lamb = 0.1, 0.2, 0.3 self.assertEqual(UGate(theta, phi, lamb).control(), CUGate(theta, phi, lamb, 0)) def test_controlled_u3(self): """Test the creation of a controlled U3 gate.""" theta, phi, lamb = 0.1, 0.2, 0.3 self.assertEqual(U3Gate(theta, phi, lamb).control(), CU3Gate(theta, phi, lamb)) circ = QuantumCircuit(1) circ.append(U3Gate(theta, phi, lamb), circ.qregs[0]) unroller = Unroller(["cx", "u", "p"]) ctrl_circ_gate = dag_to_circuit(unroller.run(circuit_to_dag(circ))).control() ctrl_circ = QuantumCircuit(2) ctrl_circ.append(ctrl_circ_gate, ctrl_circ.qregs[0]) ctrl_circ = ctrl_circ.decompose().decompose() self.assertEqual(ctrl_circ.size(), 1) def test_controlled_cx(self): """Test creation of controlled cx gate""" self.assertEqual(CXGate().control(), CCXGate()) def test_controlled_swap(self): """Test creation of controlled swap gate""" self.assertEqual(SwapGate().control(), CSwapGate()) def test_special_cases_equivalent_to_controlled_base_gate(self): """Test that ``ControlledGate`` subclasses for more efficient representations give equivalent matrices and definitions to the naive ``base_gate.control(n)``.""" # Angles used here are not important, we just pick slightly strange values to ensure that # there are no coincidental equivalences. tests = [ (CXGate(), 1), (CCXGate(), 2), (C3XGate(), 3), (C4XGate(), 4), (MCXGate(5), 5), (CYGate(), 1), (CZGate(), 1), (CPhaseGate(np.pi / 7), 1), (MCPhaseGate(np.pi / 7, 2), 2), (CSwapGate(), 1), (CSXGate(), 1), (C3SXGate(), 3), (CHGate(), 1), (CU1Gate(np.pi / 7), 1), (MCU1Gate(np.pi / 7, 2), 2), # `CUGate` takes an extra "global" phase parameter compared to `UGate`, and consequently # is only equal to `base_gate.control()` when this extra phase is 0. (CUGate(np.pi / 7, np.pi / 5, np.pi / 3, 0), 1), (CU3Gate(np.pi / 7, np.pi / 5, np.pi / 3), 1), (CRXGate(np.pi / 7), 1), (CRYGate(np.pi / 7), 1), (CRZGate(np.pi / 7), 1), ] for special_case_gate, n_controls in tests: with self.subTest(gate=special_case_gate.name): naive_operator = Operator(special_case_gate.base_gate.control(n_controls)) # Ensure that both the array form (if the gate overrides `__array__`) and the # circuit-definition form are tested. self.assertTrue(Operator(special_case_gate).equiv(naive_operator)) if not isinstance(special_case_gate, CXGate): # CX is treated like a primitive within Terra, and doesn't have a definition. self.assertTrue(Operator(special_case_gate.definition).equiv(naive_operator)) def test_global_phase_control(self): """Test creation of a GlobalPhaseGate.""" base = GlobalPhaseGate(np.pi / 7) expected_1q = PhaseGate(np.pi / 7) self.assertEqual(Operator(base.control()), Operator(expected_1q)) expected_2q = PhaseGate(np.pi / 7).control() self.assertEqual(Operator(base.control(2)), Operator(expected_2q)) expected_open = QuantumCircuit(1) expected_open.x(0) expected_open.p(np.pi / 7, 0) expected_open.x(0) self.assertEqual(Operator(base.control(ctrl_state=0)), Operator(expected_open)) def test_circuit_append(self): """Test appending a controlled gate to a quantum circuit.""" circ = QuantumCircuit(5) inst = CXGate() circ.append(inst.control(), qargs=[0, 2, 1]) circ.append(inst.control(2), qargs=[0, 3, 1, 2]) circ.append(inst.control().control(), qargs=[0, 3, 1, 2]) # should be same as above self.assertEqual(circ[1].operation, circ[2].operation) self.assertEqual(circ.depth(), 3) self.assertEqual(circ[0].operation.num_ctrl_qubits, 2) self.assertEqual(circ[1].operation.num_ctrl_qubits, 3) self.assertEqual(circ[2].operation.num_ctrl_qubits, 3) self.assertEqual(circ[0].operation.num_qubits, 3) self.assertEqual(circ[1].operation.num_qubits, 4) self.assertEqual(circ[2].operation.num_qubits, 4) for instr in circ: self.assertTrue(isinstance(instr.operation, ControlledGate)) def test_swap_definition_specification(self): """Test the instantiation of a controlled swap gate with explicit definition.""" swap = SwapGate() cswap = ControlledGate( "cswap", 3, [], num_ctrl_qubits=1, definition=swap.definition, base_gate=swap ) self.assertEqual(swap.definition, cswap.definition) def test_multi_controlled_composite_gate(self): """Test a multi controlled composite gate.""" num_ctrl = 3 # create composite gate sub_q = QuantumRegister(2) cgate = QuantumCircuit(sub_q, name="cgate") cgate.h(sub_q[0]) cgate.crz(pi / 2, sub_q[0], sub_q[1]) cgate.swap(sub_q[0], sub_q[1]) cgate.u(0.1, 0.2, 0.3, sub_q[1]) cgate.t(sub_q[0]) num_target = cgate.width() gate = cgate.to_gate() cont_gate = gate.control(num_ctrl_qubits=num_ctrl) control = QuantumRegister(num_ctrl) target = QuantumRegister(num_target) qc = QuantumCircuit(control, target) qc.append(cont_gate, control[:] + target[:]) op_mat = Operator(cgate).data cop_mat = _compute_control_matrix(op_mat, num_ctrl) ref_mat = Operator(qc).data self.assertTrue(matrix_equal(cop_mat, ref_mat)) def test_single_controlled_composite_gate(self): """Test a singly controlled composite gate.""" num_ctrl = 1 # create composite gate sub_q = QuantumRegister(2) cgate = QuantumCircuit(sub_q, name="cgate") cgate.h(sub_q[0]) cgate.cx(sub_q[0], sub_q[1]) num_target = cgate.width() gate = cgate.to_gate() cont_gate = gate.control(num_ctrl_qubits=num_ctrl) control = QuantumRegister(num_ctrl, "control") target = QuantumRegister(num_target, "target") qc = QuantumCircuit(control, target) qc.append(cont_gate, control[:] + target[:]) op_mat = Operator(cgate).data cop_mat = _compute_control_matrix(op_mat, num_ctrl) ref_mat = Operator(qc).data self.assertTrue(matrix_equal(cop_mat, ref_mat)) def test_control_open_controlled_gate(self): """Test control(2) vs control.control where inner gate has open controls.""" gate1pre = ZGate().control(1, ctrl_state=0) gate1 = gate1pre.control(1, ctrl_state=1) gate2 = ZGate().control(2, ctrl_state=1) expected = Operator(_compute_control_matrix(ZGate().to_matrix(), 2, ctrl_state=1)) self.assertEqual(expected, Operator(gate1)) self.assertEqual(expected, Operator(gate2)) def test_multi_control_z(self): """Test a multi controlled Z gate.""" qc = QuantumCircuit(1) qc.z(0) ctr_gate = qc.to_gate().control(2) ctr_circ = QuantumCircuit(3) ctr_circ.append(ctr_gate, range(3)) ref_circ = QuantumCircuit(3) ref_circ.h(2) ref_circ.ccx(0, 1, 2) ref_circ.h(2) self.assertEqual(ctr_circ.decompose(), ref_circ) def test_multi_control_u3(self): """Test the matrix representation of the controlled and controlled-controlled U3 gate.""" from qiskit.circuit.library.standard_gates import u3 num_ctrl = 3 # U3 gate params alpha, beta, gamma = 0.2, 0.3, 0.4 u3gate = u3.U3Gate(alpha, beta, gamma) cu3gate = u3.CU3Gate(alpha, beta, gamma) # cnu3 gate cnu3 = u3gate.control(num_ctrl) width = cnu3.num_qubits qr = QuantumRegister(width) qcnu3 = QuantumCircuit(qr) qcnu3.append(cnu3, qr, []) # U3 gate qu3 = QuantumCircuit(1) qu3.append(u3gate, [0]) # CU3 gate qcu3 = QuantumCircuit(2) qcu3.append(cu3gate, [0, 1]) # c-cu3 gate width = 3 qr = QuantumRegister(width) qc_cu3 = QuantumCircuit(qr) c_cu3 = cu3gate.control(1) qc_cu3.append(c_cu3, qr, []) # Circuit unitaries mat_cnu3 = Operator(qcnu3).data mat_u3 = Operator(qu3).data mat_cu3 = Operator(qcu3).data mat_c_cu3 = Operator(qc_cu3).data # Target Controlled-U3 unitary target_cnu3 = _compute_control_matrix(mat_u3, num_ctrl) target_cu3 = np.kron(mat_u3, np.diag([0, 1])) + np.kron(np.eye(2), np.diag([1, 0])) target_c_cu3 = np.kron(mat_cu3, np.diag([0, 1])) + np.kron(np.eye(4), np.diag([1, 0])) tests = [ ("check unitary of u3.control against tensored unitary of u3", target_cu3, mat_cu3), ( "check unitary of cu3.control against tensored unitary of cu3", target_c_cu3, mat_c_cu3, ), ("check unitary of cnu3 against tensored unitary of u3", target_cnu3, mat_cnu3), ] for itest in tests: info, target, decomp = itest[0], itest[1], itest[2] with self.subTest(i=info): self.assertTrue(matrix_equal(target, decomp, atol=1e-8, rtol=1e-5)) def test_multi_control_u1(self): """Test the matrix representation of the controlled and controlled-controlled U1 gate.""" from qiskit.circuit.library.standard_gates import u1 num_ctrl = 3 # U1 gate params theta = 0.2 u1gate = u1.U1Gate(theta) cu1gate = u1.CU1Gate(theta) # cnu1 gate cnu1 = u1gate.control(num_ctrl) width = cnu1.num_qubits qr = QuantumRegister(width) qcnu1 = QuantumCircuit(qr) qcnu1.append(cnu1, qr, []) # U1 gate qu1 = QuantumCircuit(1) qu1.append(u1gate, [0]) # CU1 gate qcu1 = QuantumCircuit(2) qcu1.append(cu1gate, [0, 1]) # c-cu1 gate width = 3 qr = QuantumRegister(width) qc_cu1 = QuantumCircuit(qr) c_cu1 = cu1gate.control(1) qc_cu1.append(c_cu1, qr, []) job = execute( [qcnu1, qu1, qcu1, qc_cu1], BasicAer.get_backend("unitary_simulator"), basis_gates=["u1", "u2", "u3", "id", "cx"], ) result = job.result() # Circuit unitaries mat_cnu1 = result.get_unitary(0) # trace out ancillae mat_u1 = result.get_unitary(1) mat_cu1 = result.get_unitary(2) mat_c_cu1 = result.get_unitary(3) # Target Controlled-U1 unitary target_cnu1 = _compute_control_matrix(mat_u1, num_ctrl) target_cu1 = np.kron(mat_u1, np.diag([0, 1])) + np.kron(np.eye(2), np.diag([1, 0])) target_c_cu1 = np.kron(mat_cu1, np.diag([0, 1])) + np.kron(np.eye(4), np.diag([1, 0])) tests = [ ("check unitary of u1.control against tensored unitary of u1", target_cu1, mat_cu1), ( "check unitary of cu1.control against tensored unitary of cu1", target_c_cu1, mat_c_cu1, ), ("check unitary of cnu1 against tensored unitary of u1", target_cnu1, mat_cnu1), ] for itest in tests: info, target, decomp = itest[0], itest[1], itest[2] with self.subTest(i=info): self.log.info(info) self.assertTrue(matrix_equal(target, decomp)) @data(1, 2, 3, 4) def test_multi_controlled_u1_matrix(self, num_controls): """Test the matrix representation of the multi-controlled CU1 gate. Based on the test moved here from Aqua: https://github.com/Qiskit/qiskit-aqua/blob/769ca8f/test/aqua/test_mcu1.py """ # registers for the circuit q_controls = QuantumRegister(num_controls) q_target = QuantumRegister(1) # iterate over all possible combinations of control qubits for ctrl_state in range(2**num_controls): bitstr = bin(ctrl_state)[2:].zfill(num_controls)[::-1] lam = 0.3165354 * pi qc = QuantumCircuit(q_controls, q_target) for idx, bit in enumerate(bitstr): if bit == "0": qc.x(q_controls[idx]) qc.mcp(lam, q_controls, q_target[0]) # for idx in subset: for idx, bit in enumerate(bitstr): if bit == "0": qc.x(q_controls[idx]) backend = BasicAer.get_backend("unitary_simulator") simulated = execute(qc, backend).result().get_unitary(qc) base = PhaseGate(lam).to_matrix() expected = _compute_control_matrix(base, num_controls, ctrl_state=ctrl_state) with self.subTest(msg=f"control state = {ctrl_state}"): self.assertTrue(matrix_equal(simulated, expected)) @data(1, 2, 3, 4) def test_multi_control_toffoli_matrix_clean_ancillas(self, num_controls): """Test the multi-control Toffoli gate with clean ancillas. Based on the test moved here from Aqua: https://github.com/Qiskit/qiskit-aqua/blob/769ca8f/test/aqua/test_mct.py """ # set up circuit q_controls = QuantumRegister(num_controls) q_target = QuantumRegister(1) qc = QuantumCircuit(q_controls, q_target) if num_controls > 2: num_ancillas = num_controls - 2 q_ancillas = QuantumRegister(num_controls) qc.add_register(q_ancillas) else: num_ancillas = 0 q_ancillas = None # apply hadamard on control qubits and toffoli gate qc.mct(q_controls, q_target[0], q_ancillas, mode="basic") # execute the circuit and obtain statevector result backend = BasicAer.get_backend("unitary_simulator") simulated = execute(qc, backend).result().get_unitary(qc) # compare to expectation if num_ancillas > 0: simulated = simulated[: 2 ** (num_controls + 1), : 2 ** (num_controls + 1)] base = XGate().to_matrix() expected = _compute_control_matrix(base, num_controls) self.assertTrue(matrix_equal(simulated, expected)) @data(1, 2, 3, 4, 5) def test_multi_control_toffoli_matrix_basic_dirty_ancillas(self, num_controls): """Test the multi-control Toffoli gate with dirty ancillas (basic-dirty-ancilla). Based on the test moved here from Aqua: https://github.com/Qiskit/qiskit-aqua/blob/769ca8f/test/aqua/test_mct.py """ q_controls = QuantumRegister(num_controls) q_target = QuantumRegister(1) qc = QuantumCircuit(q_controls, q_target) q_ancillas = None if num_controls <= 2: num_ancillas = 0 else: num_ancillas = num_controls - 2 q_ancillas = QuantumRegister(num_ancillas) qc.add_register(q_ancillas) qc.mct(q_controls, q_target[0], q_ancillas, mode="basic-dirty-ancilla") simulated = execute(qc, BasicAer.get_backend("unitary_simulator")).result().get_unitary(qc) if num_ancillas > 0: simulated = simulated[: 2 ** (num_controls + 1), : 2 ** (num_controls + 1)] base = XGate().to_matrix() expected = _compute_control_matrix(base, num_controls) self.assertTrue(matrix_equal(simulated, expected, atol=1e-8)) @data(1, 2, 3, 4, 5) def test_multi_control_toffoli_matrix_advanced_dirty_ancillas(self, num_controls): """Test the multi-control Toffoli gate with dirty ancillas (advanced). Based on the test moved here from Aqua: https://github.com/Qiskit/qiskit-aqua/blob/769ca8f/test/aqua/test_mct.py """ q_controls = QuantumRegister(num_controls) q_target = QuantumRegister(1) qc = QuantumCircuit(q_controls, q_target) q_ancillas = None if num_controls <= 4: num_ancillas = 0 else: num_ancillas = 1 q_ancillas = QuantumRegister(num_ancillas) qc.add_register(q_ancillas) qc.mct(q_controls, q_target[0], q_ancillas, mode="advanced") simulated = execute(qc, BasicAer.get_backend("unitary_simulator")).result().get_unitary(qc) if num_ancillas > 0: simulated = simulated[: 2 ** (num_controls + 1), : 2 ** (num_controls + 1)] base = XGate().to_matrix() expected = _compute_control_matrix(base, num_controls) self.assertTrue(matrix_equal(simulated, expected, atol=1e-8)) @data(1, 2, 3) def test_multi_control_toffoli_matrix_noancilla_dirty_ancillas(self, num_controls): """Test the multi-control Toffoli gate with dirty ancillas (noancilla). Based on the test moved here from Aqua: https://github.com/Qiskit/qiskit-aqua/blob/769ca8f/test/aqua/test_mct.py """ q_controls = QuantumRegister(num_controls) q_target = QuantumRegister(1) qc = QuantumCircuit(q_controls, q_target) qc.mct(q_controls, q_target[0], None, mode="noancilla") simulated = execute(qc, BasicAer.get_backend("unitary_simulator")).result().get_unitary(qc) base = XGate().to_matrix() expected = _compute_control_matrix(base, num_controls) self.assertTrue(matrix_equal(simulated, expected, atol=1e-8)) def test_mcsu2_real_diagonal(self): """Test mcsu2_real_diagonal""" num_ctrls = 6 theta = 0.3 ry_matrix = RYGate(theta).to_matrix() qc = _mcsu2_real_diagonal(ry_matrix, num_ctrls) mcry_matrix = _compute_control_matrix(ry_matrix, 6) self.assertTrue(np.allclose(mcry_matrix, Operator(qc).to_matrix())) @combine(num_controls=[1, 2, 4], base_gate_name=["x", "y", "z"], use_basis_gates=[True, False]) def test_multi_controlled_rotation_gate_matrices( self, num_controls, base_gate_name, use_basis_gates ): """Test the multi controlled rotation gates without ancillas. Based on the test moved here from Aqua: https://github.com/Qiskit/qiskit-aqua/blob/769ca8f/test/aqua/test_mcr.py """ q_controls = QuantumRegister(num_controls) q_target = QuantumRegister(1) # iterate over all possible combinations of control qubits for ctrl_state in range(2**num_controls): bitstr = bin(ctrl_state)[2:].zfill(num_controls)[::-1] theta = 0.871236 * pi qc = QuantumCircuit(q_controls, q_target) for idx, bit in enumerate(bitstr): if bit == "0": qc.x(q_controls[idx]) # call mcrx/mcry/mcrz if base_gate_name == "y": qc.mcry( theta, q_controls, q_target[0], None, mode="noancilla", use_basis_gates=use_basis_gates, ) else: # case 'x' or 'z' only support the noancilla mode and do not have this keyword getattr(qc, "mcr" + base_gate_name)( theta, q_controls, q_target[0], use_basis_gates=use_basis_gates ) for idx, bit in enumerate(bitstr): if bit == "0": qc.x(q_controls[idx]) if use_basis_gates: with self.subTest(msg="check only basis gates used"): gates_used = set(qc.count_ops().keys()) self.assertTrue(gates_used.issubset({"x", "u", "p", "cx"})) backend = BasicAer.get_backend("unitary_simulator") simulated = execute(qc, backend).result().get_unitary(qc) if base_gate_name == "x": rot_mat = RXGate(theta).to_matrix() elif base_gate_name == "y": rot_mat = RYGate(theta).to_matrix() else: # case 'z' rot_mat = RZGate(theta).to_matrix() expected = _compute_control_matrix(rot_mat, num_controls, ctrl_state=ctrl_state) with self.subTest(msg=f"control state = {ctrl_state}"): self.assertTrue(matrix_equal(simulated, expected)) @combine(num_controls=[1, 2, 4], use_basis_gates=[True, False]) def test_multi_controlled_y_rotation_matrix_basic_mode(self, num_controls, use_basis_gates): """Test the multi controlled Y rotation using the mode 'basic'. Based on the test moved here from Aqua: https://github.com/Qiskit/qiskit-aqua/blob/769ca8f/test/aqua/test_mcr.py """ # get the number of required ancilla qubits if num_controls <= 2: num_ancillas = 0 else: num_ancillas = num_controls - 2 q_controls = QuantumRegister(num_controls) q_target = QuantumRegister(1) for ctrl_state in range(2**num_controls): bitstr = bin(ctrl_state)[2:].zfill(num_controls)[::-1] theta = 0.871236 * pi if num_ancillas > 0: q_ancillas = QuantumRegister(num_ancillas) qc = QuantumCircuit(q_controls, q_target, q_ancillas) else: qc = QuantumCircuit(q_controls, q_target) q_ancillas = None for idx, bit in enumerate(bitstr): if bit == "0": qc.x(q_controls[idx]) qc.mcry( theta, q_controls, q_target[0], q_ancillas, mode="basic", use_basis_gates=use_basis_gates, ) for idx, bit in enumerate(bitstr): if bit == "0": qc.x(q_controls[idx]) rot_mat = RYGate(theta).to_matrix() backend = BasicAer.get_backend("unitary_simulator") simulated = execute(qc, backend).result().get_unitary(qc) if num_ancillas > 0: simulated = simulated[: 2 ** (num_controls + 1), : 2 ** (num_controls + 1)] expected = _compute_control_matrix(rot_mat, num_controls, ctrl_state=ctrl_state) with self.subTest(msg=f"control state = {ctrl_state}"): self.assertTrue(matrix_equal(simulated, expected)) def test_mcry_defaults_to_vchain(self): """Test mcry defaults to the v-chain mode if sufficient work qubits are provided.""" circuit = QuantumCircuit(5) control_qubits = circuit.qubits[:3] target_qubit = circuit.qubits[3] additional_qubits = circuit.qubits[4:] circuit.mcry(0.2, control_qubits, target_qubit, additional_qubits) # If the v-chain mode is selected, all qubits are used. If the noancilla mode would be # selected, the bottom qubit would remain unused. dag = circuit_to_dag(circuit) self.assertEqual(len(list(dag.idle_wires())), 0) @data(1, 2) def test_mcx_gates_yield_explicit_gates(self, num_ctrl_qubits): """Test the creating a MCX gate yields the explicit definition if we know it.""" cls = MCXGate(num_ctrl_qubits).__class__ explicit = {1: CXGate, 2: CCXGate} self.assertEqual(cls, explicit[num_ctrl_qubits]) @data(1, 2, 3, 4) def test_mcxgraycode_gates_yield_explicit_gates(self, num_ctrl_qubits): """Test creating an mcx gate calls MCXGrayCode and yeilds explicit definition.""" qc = QuantumCircuit(num_ctrl_qubits + 1) qc.mcx(list(range(num_ctrl_qubits)), [num_ctrl_qubits]) explicit = {1: CXGate, 2: CCXGate, 3: C3XGate, 4: C4XGate} self.assertEqual(type(qc[0].operation), explicit[num_ctrl_qubits]) @data(3, 4, 5, 8) def test_mcx_gates(self, num_ctrl_qubits): """Test the mcx gates.""" backend = BasicAer.get_backend("statevector_simulator") reference = np.zeros(2 ** (num_ctrl_qubits + 1)) reference[-1] = 1 for gate in [ MCXGrayCode(num_ctrl_qubits), MCXRecursive(num_ctrl_qubits), MCXVChain(num_ctrl_qubits, False), MCXVChain(num_ctrl_qubits, True), ]: with self.subTest(gate=gate): circuit = QuantumCircuit(gate.num_qubits) if num_ctrl_qubits > 0: circuit.x(list(range(num_ctrl_qubits))) circuit.append(gate, list(range(gate.num_qubits)), []) statevector = execute(circuit, backend).result().get_statevector() # account for ancillas if hasattr(gate, "num_ancilla_qubits") and gate.num_ancilla_qubits > 0: corrected = np.zeros(2 ** (num_ctrl_qubits + 1), dtype=complex) for i, statevector_amplitude in enumerate(statevector): i = int(bin(i)[2:].zfill(circuit.num_qubits)[gate.num_ancilla_qubits :], 2) corrected[i] += statevector_amplitude statevector = corrected np.testing.assert_array_almost_equal(statevector.real, reference) @data(1, 2, 3, 4) def test_inverse_x(self, num_ctrl_qubits): """Test inverting the controlled X gate.""" cnx = XGate().control(num_ctrl_qubits) inv_cnx = cnx.inverse() result = Operator(cnx).compose(Operator(inv_cnx)) np.testing.assert_array_almost_equal(result.data, np.identity(result.dim[0])) @data(1, 2, 3) def test_inverse_gate(self, num_ctrl_qubits): """Test inverting a controlled gate based on a circuit definition.""" qc = QuantumCircuit(3) qc.h(0) qc.cx(0, 1) qc.cx(1, 2) qc.rx(np.pi / 4, [0, 1, 2]) gate = qc.to_gate() cgate = gate.control(num_ctrl_qubits) inv_cgate = cgate.inverse() result = Operator(cgate).compose(Operator(inv_cgate)) np.testing.assert_array_almost_equal(result.data, np.identity(result.dim[0])) @data(1, 2, 3) def test_inverse_circuit(self, num_ctrl_qubits): """Test inverting a controlled gate based on a circuit definition.""" qc = QuantumCircuit(3) qc.h(0) qc.cx(0, 1) qc.cx(1, 2) qc.rx(np.pi / 4, [0, 1, 2]) cqc = qc.control(num_ctrl_qubits) cqc_inv = cqc.inverse() result = Operator(cqc).compose(Operator(cqc_inv)) np.testing.assert_array_almost_equal(result.data, np.identity(result.dim[0])) @data(1, 2, 3, 4, 5) def test_controlled_unitary(self, num_ctrl_qubits): """Test the matrix data of an Operator, which is based on a controlled gate.""" num_target = 1 q_target = QuantumRegister(num_target) qc1 = QuantumCircuit(q_target) # for h-rx(pi/2) theta, phi, lamb = 1.57079632679490, 0.0, 4.71238898038469 qc1.u(theta, phi, lamb, q_target[0]) base_gate = qc1.to_gate() # get UnitaryGate version of circuit base_op = Operator(qc1) base_mat = base_op.data cgate = base_gate.control(num_ctrl_qubits) test_op = Operator(cgate) cop_mat = _compute_control_matrix(base_mat, num_ctrl_qubits) self.assertTrue(is_unitary_matrix(base_mat)) self.assertTrue(matrix_equal(cop_mat, test_op.data)) @data(1, 2, 3, 4, 5) def test_controlled_random_unitary(self, num_ctrl_qubits): """Test the matrix data of an Operator based on a random UnitaryGate.""" num_target = 2 base_gate = random_unitary(2**num_target).to_instruction() base_mat = base_gate.to_matrix() cgate = base_gate.control(num_ctrl_qubits) test_op = Operator(cgate) cop_mat = _compute_control_matrix(base_mat, num_ctrl_qubits) self.assertTrue(matrix_equal(cop_mat, test_op.data)) @combine(num_ctrl_qubits=[1, 2, 3], ctrl_state=[0, None]) def test_open_controlled_unitary_z(self, num_ctrl_qubits, ctrl_state): """Test that UnitaryGate with control returns params.""" umat = np.array([[1, 0], [0, -1]]) ugate = UnitaryGate(umat) cugate = ugate.control(num_ctrl_qubits, ctrl_state=ctrl_state) ref_mat = _compute_control_matrix(umat, num_ctrl_qubits, ctrl_state=ctrl_state) self.assertEqual(Operator(cugate), Operator(ref_mat)) def test_controlled_controlled_rz(self): """Test that UnitaryGate with control returns params.""" qc = QuantumCircuit(1) qc.rz(0.2, 0) controlled = QuantumCircuit(2) controlled.compose(qc.control(), inplace=True) self.assertEqual(Operator(controlled), Operator(CRZGate(0.2))) self.assertEqual(Operator(controlled), Operator(RZGate(0.2).control())) def test_controlled_controlled_unitary(self): """Test that global phase in iso decomposition of unitary is handled.""" umat = np.array([[1, 0], [0, -1]]) ugate = UnitaryGate(umat) cugate = ugate.control() ccugate = cugate.control() ccugate2 = ugate.control(2) ref_mat = _compute_control_matrix(umat, 2) self.assertTrue(Operator(ccugate2).equiv(Operator(ref_mat))) self.assertTrue(Operator(ccugate).equiv(Operator(ccugate2))) @data(1, 2, 3) def test_open_controlled_unitary_matrix(self, num_ctrl_qubits): """test open controlled unitary matrix""" # verify truth table num_target_qubits = 2 num_qubits = num_ctrl_qubits + num_target_qubits target_op = Operator(XGate()) for i in range(num_target_qubits - 1): target_op = target_op.tensor(XGate()) for i in range(2**num_qubits): input_bitstring = bin(i)[2:].zfill(num_qubits) input_target = input_bitstring[0:num_target_qubits] input_ctrl = input_bitstring[-num_ctrl_qubits:] phi = Statevector.from_label(input_bitstring) cop = Operator( _compute_control_matrix(target_op.data, num_ctrl_qubits, ctrl_state=input_ctrl) ) for j in range(2**num_qubits): output_bitstring = bin(j)[2:].zfill(num_qubits) output_target = output_bitstring[0:num_target_qubits] output_ctrl = output_bitstring[-num_ctrl_qubits:] psi = Statevector.from_label(output_bitstring) cxout = np.dot(phi.data, psi.evolve(cop).data) if input_ctrl == output_ctrl: # flip the target bits cond_output = "".join([str(int(not int(a))) for a in input_target]) else: cond_output = input_target if cxout == 1: self.assertTrue((output_ctrl == input_ctrl) and (output_target == cond_output)) else: self.assertTrue( ((output_ctrl == input_ctrl) and (output_target != cond_output)) or output_ctrl != input_ctrl ) def test_open_control_cx_unrolling(self): """test unrolling of open control gates when gate is in basis""" qc = QuantumCircuit(2) qc.cx(0, 1, ctrl_state=0) dag = circuit_to_dag(qc) unroller = Unroller(["u3", "cx"]) uqc = dag_to_circuit(unroller.run(dag)) ref_circuit = QuantumCircuit(2) ref_circuit.append(U3Gate(np.pi, 0, np.pi), [0]) ref_circuit.cx(0, 1) ref_circuit.append(U3Gate(np.pi, 0, np.pi), [0]) self.assertEqual(uqc, ref_circuit) def test_open_control_cy_unrolling(self): """test unrolling of open control gates when gate is in basis""" qc = QuantumCircuit(2) qc.cy(0, 1, ctrl_state=0) dag = circuit_to_dag(qc) unroller = Unroller(["u3", "cy"]) uqc = dag_to_circuit(unroller.run(dag)) ref_circuit = QuantumCircuit(2) ref_circuit.append(U3Gate(np.pi, 0, np.pi), [0]) ref_circuit.cy(0, 1) ref_circuit.append(U3Gate(np.pi, 0, np.pi), [0]) self.assertEqual(uqc, ref_circuit) def test_open_control_ccx_unrolling(self): """test unrolling of open control gates when gate is in basis""" qreg = QuantumRegister(3) qc = QuantumCircuit(qreg) ccx = CCXGate(ctrl_state=0) qc.append(ccx, [0, 1, 2]) dag = circuit_to_dag(qc) unroller = Unroller(["x", "ccx"]) unrolled_dag = unroller.run(dag) # ┌───┐ ┌───┐ # q0_0: ┤ X ├──■──┤ X ├ # ├───┤ │ ├───┤ # q0_1: ┤ X ├──■──┤ X ├ # └───┘┌─┴─┐└───┘ # q0_2: ─────┤ X ├───── # └───┘ ref_circuit = QuantumCircuit(qreg) ref_circuit.x(qreg[0]) ref_circuit.x(qreg[1]) ref_circuit.ccx(qreg[0], qreg[1], qreg[2]) ref_circuit.x(qreg[0]) ref_circuit.x(qreg[1]) ref_dag = circuit_to_dag(ref_circuit) self.assertEqual(unrolled_dag, ref_dag) def test_ccx_ctrl_state_consistency(self): """Test the consistency of parameters ctrl_state in CCX See issue: https://github.com/Qiskit/qiskit-terra/issues/6465 """ qreg = QuantumRegister(3) qc = QuantumCircuit(qreg) qc.ccx(qreg[0], qreg[1], qreg[2], ctrl_state=0) ref_circuit = QuantumCircuit(qreg) ccx = CCXGate(ctrl_state=0) ref_circuit.append(ccx, [qreg[0], qreg[1], qreg[2]]) self.assertEqual(qc, ref_circuit) def test_open_control_composite_unrolling(self): """test unrolling of open control gates when gate is in basis""" # create composite gate qreg = QuantumRegister(2) qcomp = QuantumCircuit(qreg, name="bell") qcomp.h(qreg[0]) qcomp.cx(qreg[0], qreg[1]) bell = qcomp.to_gate() # create controlled composite gate cqreg = QuantumRegister(3) qc = QuantumCircuit(cqreg) qc.append(bell.control(ctrl_state=0), qc.qregs[0][:]) dag = circuit_to_dag(qc) unroller = Unroller(["x", "u1", "cbell"]) unrolled_dag = unroller.run(dag) # create reference circuit ref_circuit = QuantumCircuit(cqreg) ref_circuit.x(cqreg[0]) ref_circuit.append(bell.control(), [cqreg[0], cqreg[1], cqreg[2]]) ref_circuit.x(cqreg[0]) ref_dag = circuit_to_dag(ref_circuit) self.assertEqual(unrolled_dag, ref_dag) @data(*ControlledGate.__subclasses__()) def test_standard_base_gate_setting(self, gate_class): """Test all gates in standard extensions which are of type ControlledGate and have a base gate setting. """ num_free_params = len(_get_free_params(gate_class.__init__, ignore=["self"])) free_params = [0.1 * i for i in range(num_free_params)] if gate_class in [MCU1Gate, MCPhaseGate]: free_params[1] = 3 elif gate_class in [MCXGate]: free_params[0] = 3 base_gate = gate_class(*free_params) cgate = base_gate.control() # the base gate of CU is U (3 params), the base gate of CCU is CU (4 params) if gate_class == CUGate: self.assertListEqual(cgate.base_gate.params[:3], base_gate.base_gate.params[:3]) else: self.assertEqual(base_gate.base_gate, cgate.base_gate) @combine( gate=[cls for cls in allGates.__dict__.values() if isinstance(cls, type)], num_ctrl_qubits=[1, 2], ctrl_state=[None, 0, 1], ) def test_all_inverses(self, gate, num_ctrl_qubits, ctrl_state): """Test all gates in standard extensions except those that cannot be controlled or are being deprecated. """ if not (issubclass(gate, ControlledGate) or issubclass(gate, allGates.IGate)): # only verify basic gates right now, as already controlled ones # will generate differing definitions try: numargs = len(_get_free_params(gate)) args = [2] * numargs gate = gate(*args) self.assertEqual( gate.inverse().control(num_ctrl_qubits, ctrl_state=ctrl_state), gate.control(num_ctrl_qubits, ctrl_state=ctrl_state).inverse(), ) except AttributeError: # skip gates that do not have a control attribute (e.g. barrier) pass @data(2, 3) def test_relative_phase_toffoli_gates(self, num_ctrl_qubits): """Test the relative phase Toffoli gates. This test compares the matrix representation of the relative phase gate classes (i.e. RCCXGate().to_matrix()), the matrix obtained from the unitary simulator, and the exact version of the gate as obtained through `_compute_control_matrix`. """ # get target matrix (w/o relative phase) base_mat = XGate().to_matrix() target_mat = _compute_control_matrix(base_mat, num_ctrl_qubits) # build the matrix for the relative phase toffoli using the unitary simulator circuit = QuantumCircuit(num_ctrl_qubits + 1) if num_ctrl_qubits == 2: circuit.rccx(0, 1, 2) else: # num_ctrl_qubits == 3: circuit.rcccx(0, 1, 2, 3) simulator = BasicAer.get_backend("unitary_simulator") simulated_mat = execute(circuit, simulator).result().get_unitary() # get the matrix representation from the class itself if num_ctrl_qubits == 2: repr_mat = RCCXGate().to_matrix() else: # num_ctrl_qubits == 3: repr_mat = RC3XGate().to_matrix() # test up to phase # note, that all entries may have an individual phase! (as opposed to a global phase) self.assertTrue(matrix_equal(np.abs(simulated_mat), target_mat)) # compare simulated matrix with the matrix representation provided by the class self.assertTrue(matrix_equal(simulated_mat, repr_mat)) def test_open_controlled_gate(self): """ Test controlled gates with control on '0' """ base_gate = XGate() base_mat = base_gate.to_matrix() num_ctrl_qubits = 3 ctrl_state = 5 cgate = base_gate.control(num_ctrl_qubits, ctrl_state=ctrl_state) target_mat = _compute_control_matrix(base_mat, num_ctrl_qubits, ctrl_state=ctrl_state) self.assertEqual(Operator(cgate), Operator(target_mat)) ctrl_state = None cgate = base_gate.control(num_ctrl_qubits, ctrl_state=ctrl_state) target_mat = _compute_control_matrix(base_mat, num_ctrl_qubits, ctrl_state=ctrl_state) self.assertEqual(Operator(cgate), Operator(target_mat)) ctrl_state = 0 cgate = base_gate.control(num_ctrl_qubits, ctrl_state=ctrl_state) target_mat = _compute_control_matrix(base_mat, num_ctrl_qubits, ctrl_state=ctrl_state) self.assertEqual(Operator(cgate), Operator(target_mat)) ctrl_state = 7 cgate = base_gate.control(num_ctrl_qubits, ctrl_state=ctrl_state) target_mat = _compute_control_matrix(base_mat, num_ctrl_qubits, ctrl_state=ctrl_state) self.assertEqual(Operator(cgate), Operator(target_mat)) ctrl_state = "110" cgate = base_gate.control(num_ctrl_qubits, ctrl_state=ctrl_state) target_mat = _compute_control_matrix(base_mat, num_ctrl_qubits, ctrl_state=ctrl_state) self.assertEqual(Operator(cgate), Operator(target_mat)) def test_open_controlled_gate_raises(self): """ Test controlled gates with open controls raises if ctrl_state isn't allowed. """ base_gate = XGate() num_ctrl_qubits = 3 with self.assertRaises(CircuitError): base_gate.control(num_ctrl_qubits, ctrl_state=-1) with self.assertRaises(CircuitError): base_gate.control(num_ctrl_qubits, ctrl_state=2**num_ctrl_qubits) with self.assertRaises(CircuitError): base_gate.control(num_ctrl_qubits, ctrl_state="201") def test_base_gate_params_reference(self): """ Test all gates in standard extensions which are of type ControlledGate and have a base gate setting have params which reference the one in their base gate. """ num_ctrl_qubits = 1 for gate_class in ControlledGate.__subclasses__(): with self.subTest(i=repr(gate_class)): num_free_params = len(_get_free_params(gate_class.__init__, ignore=["self"])) free_params = [0.1 * (i + 1) for i in range(num_free_params)] if gate_class in [MCU1Gate, MCPhaseGate]: free_params[1] = 3 elif gate_class in [MCXGate]: free_params[0] = 3 base_gate = gate_class(*free_params) if base_gate.params: cgate = base_gate.control(num_ctrl_qubits) self.assertIs(cgate.base_gate.params, cgate.params) def test_assign_parameters(self): """Test assigning parameters to quantum circuit with controlled gate.""" qc = QuantumCircuit(2, name="assign") ptest = Parameter("p") gate = CRYGate(ptest) qc.append(gate, [0, 1]) subs1, subs2 = {ptest: Parameter("a")}, {ptest: Parameter("b")} bound1 = qc.assign_parameters(subs1, inplace=False) bound2 = qc.assign_parameters(subs2, inplace=False) self.assertEqual(qc.parameters, {ptest}) self.assertEqual(bound1.parameters, {subs1[ptest]}) self.assertEqual(bound2.parameters, {subs2[ptest]}) @data(-1, 0, 1.4, "1", 4, 10) def test_improper_num_ctrl_qubits(self, num_ctrl_qubits): """ Test improperly specified num_ctrl_qubits. """ num_qubits = 4 with self.assertRaises(CircuitError): ControlledGate( name="cgate", num_qubits=num_qubits, params=[], num_ctrl_qubits=num_ctrl_qubits ) def test_improper_num_ctrl_qubits_base_gate(self): """Test that the allowed number of control qubits takes the base gate into account.""" with self.assertRaises(CircuitError): ControlledGate( name="cx?", num_qubits=2, params=[], num_ctrl_qubits=2, base_gate=XGate() ) self.assertIsInstance( ControlledGate( name="cx?", num_qubits=2, params=[], num_ctrl_qubits=1, base_gate=XGate() ), ControlledGate, ) self.assertIsInstance( ControlledGate( name="p", num_qubits=1, params=[np.pi], num_ctrl_qubits=1, base_gate=Gate("gphase", 0, [np.pi]), ), ControlledGate, ) def test_open_controlled_equality(self): """ Test open controlled gates are equal if their base gates and control states are equal. """ self.assertEqual(XGate().control(1), XGate().control(1)) self.assertNotEqual(XGate().control(1), YGate().control(1)) self.assertNotEqual(XGate().control(1), XGate().control(2)) self.assertEqual(XGate().control(1, ctrl_state="0"), XGate().control(1, ctrl_state="0")) self.assertNotEqual(XGate().control(1, ctrl_state="0"), XGate().control(1, ctrl_state="1")) def test_cx_global_phase(self): """ Test controlling CX with global phase """ theta = pi / 2 circ = QuantumCircuit(2, global_phase=theta) circ.cx(0, 1) cx = circ.to_gate() self.assertNotEqual(Operator(CXGate()), Operator(cx)) ccx = cx.control(1) base_mat = Operator(cx).data target = _compute_control_matrix(base_mat, 1) self.assertEqual(Operator(ccx), Operator(target)) expected = QuantumCircuit(*ccx.definition.qregs) expected.ccx(0, 1, 2) expected.p(theta, 0) self.assertEqual(ccx.definition, expected) @data(1, 2) def test_controlled_global_phase(self, num_ctrl_qubits): """ Test controlled global phase on base gate. """ theta = pi / 4 circ = QuantumCircuit(2, global_phase=theta) base_gate = circ.to_gate() base_mat = Operator(base_gate).data target = _compute_control_matrix(base_mat, num_ctrl_qubits) cgate = base_gate.control(num_ctrl_qubits) ccirc = circ.control(num_ctrl_qubits) self.assertEqual(Operator(cgate), Operator(target)) self.assertEqual(Operator(ccirc), Operator(target)) @data(1, 2) def test_rz_composite_global_phase(self, num_ctrl_qubits): """ Test controlling CX with global phase """ theta = pi / 4 circ = QuantumCircuit(2, global_phase=theta) circ.rz(0.1, 0) circ.rz(0.2, 1) ccirc = circ.control(num_ctrl_qubits) base_gate = circ.to_gate() cgate = base_gate.control(num_ctrl_qubits) base_mat = Operator(base_gate).data target = _compute_control_matrix(base_mat, num_ctrl_qubits) self.assertEqual(Operator(cgate), Operator(target)) self.assertEqual(Operator(ccirc), Operator(target)) @data(1, 2) def test_nested_global_phase(self, num_ctrl_qubits): """ Test controlling a gate with nested global phase. """ theta = pi / 4 circ = QuantumCircuit(1, global_phase=theta) circ.z(0) v = circ.to_gate() qc = QuantumCircuit(1) qc.append(v, [0]) ctrl_qc = qc.control(num_ctrl_qubits) base_mat = Operator(qc).data target = _compute_control_matrix(base_mat, num_ctrl_qubits) self.assertEqual(Operator(ctrl_qc), Operator(target)) @data(1, 2) def test_control_zero_operand_gate(self, num_ctrl_qubits): """Test that a zero-operand gate (such as a make-shift global-phase gate) can be controlled.""" gate = QuantumCircuit(global_phase=np.pi).to_gate() controlled = gate.control(num_ctrl_qubits) self.assertIsInstance(controlled, ControlledGate) self.assertEqual(controlled.num_ctrl_qubits, num_ctrl_qubits) self.assertEqual(controlled.num_qubits, num_ctrl_qubits) target = np.eye(2**num_ctrl_qubits, dtype=np.complex128) target.flat[-1] = -1 self.assertEqual(Operator(controlled), Operator(target)) @ddt class TestOpenControlledToMatrix(QiskitTestCase): """Test controlled_gates implementing to_matrix work with ctrl_state""" @combine(gate_class=ControlledGate.__subclasses__(), ctrl_state=[0, None]) def test_open_controlled_to_matrix(self, gate_class, ctrl_state): """Test open controlled to_matrix.""" num_free_params = len(_get_free_params(gate_class.__init__, ignore=["self"])) free_params = [0.1 * i for i in range(1, num_free_params + 1)] if gate_class in [MCU1Gate, MCPhaseGate]: free_params[1] = 3 elif gate_class in [MCXGate]: free_params[0] = 3 cgate = gate_class(*free_params) cgate.ctrl_state = ctrl_state base_mat = Operator(cgate.base_gate).data if gate_class == CUGate: # account for global phase base_mat = np.array(base_mat) * np.exp(1j * cgate.params[3]) target = _compute_control_matrix(base_mat, cgate.num_ctrl_qubits, ctrl_state=ctrl_state) try: actual = cgate.to_matrix() except CircuitError as cerr: self.skipTest(str(cerr)) self.assertTrue(np.allclose(actual, target)) @ddt class TestSingleControlledRotationGates(QiskitTestCase): """Test the controlled rotation gates controlled on one qubit.""" from qiskit.circuit.library.standard_gates import u1, rx, ry, rz num_ctrl = 2 num_target = 1 theta = pi / 2 gu1 = u1.U1Gate(theta) grx = rx.RXGate(theta) gry = ry.RYGate(theta) grz = rz.RZGate(theta) ugu1 = ac._unroll_gate(gu1, ["p", "u", "cx"]) ugrx = ac._unroll_gate(grx, ["p", "u", "cx"]) ugry = ac._unroll_gate(gry, ["p", "u", "cx"]) ugrz = ac._unroll_gate(grz, ["p", "u", "cx"]) ugrz.params = grz.params cgu1 = ugu1.control(num_ctrl) cgrx = ugrx.control(num_ctrl) cgry = ugry.control(num_ctrl) cgrz = ugrz.control(num_ctrl) @data((gu1, cgu1), (grx, cgrx), (gry, cgry), (grz, cgrz)) @unpack def test_single_controlled_rotation_gates(self, gate, cgate): """Test the controlled rotation gates controlled on one qubit.""" if gate.name == "rz": iden = Operator.from_label("I") zgen = Operator.from_label("Z") op_mat = (np.cos(0.5 * self.theta) * iden - 1j * np.sin(0.5 * self.theta) * zgen).data else: op_mat = Operator(gate).data ref_mat = Operator(cgate).data cop_mat = _compute_control_matrix(op_mat, self.num_ctrl) self.assertTrue(matrix_equal(cop_mat, ref_mat)) cqc = QuantumCircuit(self.num_ctrl + self.num_target) cqc.append(cgate, cqc.qregs[0]) dag = circuit_to_dag(cqc) unroller = Unroller(["u", "cx"]) uqc = dag_to_circuit(unroller.run(dag)) self.log.info("%s gate count: %d", cgate.name, uqc.size()) self.log.info("\n%s", str(uqc)) # these limits could be changed if gate.name == "ry": self.assertLessEqual(uqc.size(), 32, f"\n{uqc}") elif gate.name == "rz": self.assertLessEqual(uqc.size(), 43, f"\n{uqc}") else: self.assertLessEqual(uqc.size(), 20, f"\n{uqc}") def test_composite(self): """Test composite gate count.""" qreg = QuantumRegister(self.num_ctrl + self.num_target) qc = QuantumCircuit(qreg, name="composite") qc.append(self.grx.control(self.num_ctrl), qreg) qc.append(self.gry.control(self.num_ctrl), qreg) qc.append(self.gry, qreg[0 : self.gry.num_qubits]) qc.append(self.grz.control(self.num_ctrl), qreg) dag = circuit_to_dag(qc) unroller = Unroller(["u", "cx"]) uqc = dag_to_circuit(unroller.run(dag)) self.log.info("%s gate count: %d", uqc.name, uqc.size()) self.assertLessEqual(uqc.size(), 96, f"\n{uqc}") # this limit could be changed @ddt class TestControlledStandardGates(QiskitTestCase): """Tests for control standard gates.""" @combine( num_ctrl_qubits=[1, 2, 3], gate_class=[cls for cls in allGates.__dict__.values() if isinstance(cls, type)], ) def test_controlled_standard_gates(self, num_ctrl_qubits, gate_class): """Test controlled versions of all standard gates.""" theta = pi / 2 ctrl_state_ones = 2**num_ctrl_qubits - 1 ctrl_state_zeros = 0 ctrl_state_mixed = ctrl_state_ones >> int(num_ctrl_qubits / 2) numargs = len(_get_free_params(gate_class)) args = [theta] * numargs if gate_class in [MSGate, Barrier]: args[0] = 2 elif gate_class in [MCU1Gate, MCPhaseGate]: args[1] = 2 elif issubclass(gate_class, MCXGate): args = [5] gate = gate_class(*args) for ctrl_state in (ctrl_state_ones, ctrl_state_zeros, ctrl_state_mixed): with self.subTest(i=f"{gate_class.__name__}, ctrl_state={ctrl_state}"): if hasattr(gate, "num_ancilla_qubits") and gate.num_ancilla_qubits > 0: # skip matrices that include ancilla qubits continue try: cgate = gate.control(num_ctrl_qubits, ctrl_state=ctrl_state) except (AttributeError, QiskitError): # 'object has no attribute "control"' # skipping Id and Barrier continue base_mat = Operator(gate).data target_mat = _compute_control_matrix( base_mat, num_ctrl_qubits, ctrl_state=ctrl_state ) self.assertEqual(Operator(cgate), Operator(target_mat)) @ddt class TestParameterCtrlState(QiskitTestCase): """Test gate equality with ctrl_state parameter.""" @data( (RXGate(0.5), CRXGate(0.5)), (RYGate(0.5), CRYGate(0.5)), (RZGate(0.5), CRZGate(0.5)), (XGate(), CXGate()), (YGate(), CYGate()), (ZGate(), CZGate()), (U1Gate(0.5), CU1Gate(0.5)), (PhaseGate(0.5), CPhaseGate(0.5)), (SwapGate(), CSwapGate()), (HGate(), CHGate()), (U3Gate(0.1, 0.2, 0.3), CU3Gate(0.1, 0.2, 0.3)), (UGate(0.1, 0.2, 0.3), CUGate(0.1, 0.2, 0.3, 0)), ) @unpack def test_ctrl_state_one(self, gate, controlled_gate): """Test controlled gates with ctrl_state See https://github.com/Qiskit/qiskit-terra/pull/4025 """ self.assertEqual( Operator(gate.control(1, ctrl_state="1")), Operator(controlled_gate.to_matrix()) ) @ddt class TestControlledGateLabel(QiskitTestCase): """Tests for controlled gate labels.""" gates_and_args = [ (XGate, []), (YGate, []), (ZGate, []), (HGate, []), (CXGate, []), (CCXGate, []), (C3XGate, []), (C3SXGate, []), (C4XGate, []), (MCXGate, [5]), (PhaseGate, [0.1]), (U1Gate, [0.1]), (CYGate, []), (CZGate, []), (CPhaseGate, [0.1]), (CU1Gate, [0.1]), (SwapGate, []), (SXGate, []), (CSXGate, []), (CCXGate, []), (RZGate, [0.1]), (RXGate, [0.1]), (RYGate, [0.1]), (CRYGate, [0.1]), (CRXGate, [0.1]), (CSwapGate, []), (UGate, [0.1, 0.2, 0.3]), (U3Gate, [0.1, 0.2, 0.3]), (CHGate, []), (CRZGate, [0.1]), (CUGate, [0.1, 0.2, 0.3, 0.4]), (CU3Gate, [0.1, 0.2, 0.3]), (MSGate, [5, 0.1]), (RCCXGate, []), (RC3XGate, []), (MCU1Gate, [0.1, 1]), (MCXGate, [5]), ] @data(*gates_and_args) @unpack def test_control_label(self, gate, args): """Test gate(label=...).control(label=...)""" cgate = gate(*args, label="a gate").control(label="a controlled gate") self.assertEqual(cgate.label, "a controlled gate") self.assertEqual(cgate.base_gate.label, "a gate") @data(*gates_and_args) @unpack def test_control_label_1(self, gate, args): """Test gate(label=...).control(1, label=...)""" cgate = gate(*args, label="a gate").control(1, label="a controlled gate") self.assertEqual(cgate.label, "a controlled gate") self.assertEqual(cgate.base_gate.label, "a gate") if __name__ == "__main__": unittest.main()
https://github.com/swe-train/qiskit__qiskit
swe-train
# 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. """Diagonal gate tests.""" import unittest import numpy as np from qiskit import QuantumCircuit, QuantumRegister, BasicAer, execute from qiskit import QiskitError from qiskit.test import QiskitTestCase from qiskit.compiler import transpile from qiskit.extensions.quantum_initializer import DiagonalGate from qiskit.quantum_info.operators.predicates import matrix_equal class TestDiagonalGate(QiskitTestCase): """ Diagonal gate tests. """ def test_diag_gate(self): """Test diagonal gates.""" for phases in [ [0, 0], [0, 0.8], [0, 0, 1, 1], [0, 1, 0.5, 1], (2 * np.pi * np.random.rand(2**3)).tolist(), (2 * np.pi * np.random.rand(2**4)).tolist(), (2 * np.pi * np.random.rand(2**5)).tolist(), ]: with self.subTest(phases=phases): diag = [np.exp(1j * ph) for ph in phases] num_qubits = int(np.log2(len(diag))) q = QuantumRegister(num_qubits) qc = QuantumCircuit(q) qc.diagonal(diag, q[0:num_qubits]) # Decompose the gate qc = transpile(qc, basis_gates=["u1", "u3", "u2", "cx", "id"], optimization_level=0) # Simulate the decomposed gate simulator = BasicAer.get_backend("unitary_simulator") result = execute(qc, simulator).result() unitary = result.get_unitary(qc) unitary_desired = _get_diag_gate_matrix(diag) self.assertTrue(matrix_equal(unitary, unitary_desired, ignore_phase=False)) def test_mod1_entries(self): """Test that diagonal raises if entries do not have modules of 1.""" from qiskit.quantum_info.operators.predicates import ATOL_DEFAULT, RTOL_DEFAULT with self.assertRaises(QiskitError): DiagonalGate([1, 1 - 2 * ATOL_DEFAULT - RTOL_DEFAULT]) def _get_diag_gate_matrix(diag): return np.diagflat(diag) if __name__ == "__main__": unittest.main()
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=missing-function-docstring, missing-module-docstring import unittest from inspect import signature from math import pi import numpy as np from scipy.linalg import expm from ddt import data, ddt, unpack from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister, execute from qiskit.exceptions import QiskitError from qiskit.circuit.exceptions import CircuitError from qiskit.test import QiskitTestCase from qiskit.circuit import Gate, ControlledGate from qiskit.circuit.library import ( U1Gate, U2Gate, U3Gate, CU1Gate, CU3Gate, XXMinusYYGate, XXPlusYYGate, RZGate, XGate, YGate, GlobalPhaseGate, ) from qiskit import BasicAer from qiskit.quantum_info import Pauli from qiskit.quantum_info.operators.predicates import matrix_equal, is_unitary_matrix from qiskit.utils.optionals import HAS_TWEEDLEDUM from qiskit.quantum_info import Operator from qiskit import transpile class TestStandard1Q(QiskitTestCase): """Standard Extension Test. Gates with a single Qubit""" def setUp(self): super().setUp() self.qr = QuantumRegister(3, "q") self.qr2 = QuantumRegister(3, "r") self.cr = ClassicalRegister(3, "c") self.circuit = QuantumCircuit(self.qr, self.qr2, self.cr) def test_barrier(self): self.circuit.barrier(self.qr[1]) self.assertEqual(len(self.circuit), 1) self.assertEqual(self.circuit[0].operation.name, "barrier") self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_barrier_wires(self): self.circuit.barrier(1) self.assertEqual(len(self.circuit), 1) self.assertEqual(self.circuit[0].operation.name, "barrier") self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_barrier_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.barrier, self.cr[0]) self.assertRaises(CircuitError, qc.barrier, self.cr) self.assertRaises(CircuitError, qc.barrier, (self.qr, "a")) self.assertRaises(CircuitError, qc.barrier, 0.0) def test_conditional_barrier_invalid(self): qc = self.circuit barrier = qc.barrier(self.qr) self.assertRaises(QiskitError, barrier.c_if, self.cr, 0) def test_barrier_reg(self): self.circuit.barrier(self.qr) self.assertEqual(len(self.circuit), 1) self.assertEqual(self.circuit[0].operation.name, "barrier") self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1], self.qr[2])) def test_barrier_none(self): self.circuit.barrier() self.assertEqual(len(self.circuit), 1) self.assertEqual(self.circuit[0].operation.name, "barrier") self.assertEqual( self.circuit[0].qubits, (self.qr[0], self.qr[1], self.qr[2], self.qr2[0], self.qr2[1], self.qr2[2]), ) def test_ccx(self): self.circuit.ccx(self.qr[0], self.qr[1], self.qr[2]) self.assertEqual(self.circuit[0].operation.name, "ccx") self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1], self.qr[2])) def test_ccx_wires(self): self.circuit.ccx(0, 1, 2) self.assertEqual(self.circuit[0].operation.name, "ccx") self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1], self.qr[2])) def test_ccx_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.ccx, self.cr[0], self.cr[1], self.cr[2]) self.assertRaises(CircuitError, qc.ccx, self.qr[0], self.qr[0], self.qr[2]) self.assertRaises(CircuitError, qc.ccx, 0.0, self.qr[0], self.qr[2]) self.assertRaises(CircuitError, qc.ccx, self.cr, self.qr, self.qr) self.assertRaises(CircuitError, qc.ccx, "a", self.qr[1], self.qr[2]) def test_ch(self): self.circuit.ch(self.qr[0], self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "ch") self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1])) def test_ch_wires(self): self.circuit.ch(0, 1) self.assertEqual(self.circuit[0].operation.name, "ch") self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1])) def test_ch_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.ch, self.cr[0], self.cr[1]) self.assertRaises(CircuitError, qc.ch, self.qr[0], self.qr[0]) self.assertRaises(CircuitError, qc.ch, 0.0, self.qr[0]) self.assertRaises(CircuitError, qc.ch, (self.qr, 3), self.qr[0]) self.assertRaises(CircuitError, qc.ch, self.cr, self.qr) self.assertRaises(CircuitError, qc.ch, "a", self.qr[1]) def test_cif_reg(self): self.circuit.h(self.qr[0]).c_if(self.cr, 7) self.assertEqual(self.circuit[0].operation.name, "h") self.assertEqual(self.circuit[0].qubits, (self.qr[0],)) self.assertEqual(self.circuit[0].operation.condition, (self.cr, 7)) def test_cif_single_bit(self): self.circuit.h(self.qr[0]).c_if(self.cr[0], True) self.assertEqual(self.circuit[0].operation.name, "h") self.assertEqual(self.circuit[0].qubits, (self.qr[0],)) self.assertEqual(self.circuit[0].operation.condition, (self.cr[0], True)) def test_crz(self): self.circuit.crz(1, self.qr[0], self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "crz") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1])) def test_cry(self): self.circuit.cry(1, self.qr[0], self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "cry") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1])) def test_crx(self): self.circuit.crx(1, self.qr[0], self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "crx") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1])) def test_crz_wires(self): self.circuit.crz(1, 0, 1) self.assertEqual(self.circuit[0].operation.name, "crz") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1])) def test_cry_wires(self): self.circuit.cry(1, 0, 1) self.assertEqual(self.circuit[0].operation.name, "cry") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1])) def test_crx_wires(self): self.circuit.crx(1, 0, 1) self.assertEqual(self.circuit[0].operation.name, "crx") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1])) def test_crz_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.crz, 0, self.cr[0], self.cr[1]) self.assertRaises(CircuitError, qc.crz, 0, self.qr[0], self.qr[0]) self.assertRaises(CircuitError, qc.crz, 0, 0.0, self.qr[0]) self.assertRaises(CircuitError, qc.crz, self.qr[2], self.qr[1], self.qr[0]) self.assertRaises(CircuitError, qc.crz, 0, self.qr[1], self.cr[2]) self.assertRaises(CircuitError, qc.crz, 0, (self.qr, 3), self.qr[1]) self.assertRaises(CircuitError, qc.crz, 0, self.cr, self.qr) # TODO self.assertRaises(CircuitError, qc.crz, 'a', self.qr[1], self.qr[2]) def test_cry_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.cry, 0, self.cr[0], self.cr[1]) self.assertRaises(CircuitError, qc.cry, 0, self.qr[0], self.qr[0]) self.assertRaises(CircuitError, qc.cry, 0, 0.0, self.qr[0]) self.assertRaises(CircuitError, qc.cry, self.qr[2], self.qr[1], self.qr[0]) self.assertRaises(CircuitError, qc.cry, 0, self.qr[1], self.cr[2]) self.assertRaises(CircuitError, qc.cry, 0, (self.qr, 3), self.qr[1]) self.assertRaises(CircuitError, qc.cry, 0, self.cr, self.qr) # TODO self.assertRaises(CircuitError, qc.cry, 'a', self.qr[1], self.qr[2]) def test_crx_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.crx, 0, self.cr[0], self.cr[1]) self.assertRaises(CircuitError, qc.crx, 0, self.qr[0], self.qr[0]) self.assertRaises(CircuitError, qc.crx, 0, 0.0, self.qr[0]) self.assertRaises(CircuitError, qc.crx, self.qr[2], self.qr[1], self.qr[0]) self.assertRaises(CircuitError, qc.crx, 0, self.qr[1], self.cr[2]) self.assertRaises(CircuitError, qc.crx, 0, (self.qr, 3), self.qr[1]) self.assertRaises(CircuitError, qc.crx, 0, self.cr, self.qr) # TODO self.assertRaises(CircuitError, qc.crx, 'a', self.qr[1], self.qr[2]) def test_cswap(self): self.circuit.cswap(self.qr[0], self.qr[1], self.qr[2]) self.assertEqual(self.circuit[0].operation.name, "cswap") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1], self.qr[2])) def test_cswap_wires(self): self.circuit.cswap(0, 1, 2) self.assertEqual(self.circuit[0].operation.name, "cswap") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1], self.qr[2])) def test_cswap_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.cswap, self.cr[0], self.cr[1], self.cr[2]) self.assertRaises(CircuitError, qc.cswap, self.qr[1], self.qr[0], self.qr[0]) self.assertRaises(CircuitError, qc.cswap, self.qr[1], 0.0, self.qr[0]) self.assertRaises(CircuitError, qc.cswap, self.cr[0], self.cr[1], self.qr[0]) self.assertRaises(CircuitError, qc.cswap, self.qr[0], self.qr[0], self.qr[1]) self.assertRaises(CircuitError, qc.cswap, 0.0, self.qr[0], self.qr[1]) self.assertRaises(CircuitError, qc.cswap, (self.qr, 3), self.qr[0], self.qr[1]) self.assertRaises(CircuitError, qc.cswap, self.cr, self.qr[0], self.qr[1]) self.assertRaises(CircuitError, qc.cswap, "a", self.qr[1], self.qr[2]) def test_cu1(self): self.circuit.append(CU1Gate(1), [self.qr[1], self.qr[2]]) self.assertEqual(self.circuit[0].operation.name, "cu1") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2])) def test_cu1_wires(self): self.circuit.append(CU1Gate(1), [1, 2]) self.assertEqual(self.circuit[0].operation.name, "cu1") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2])) def test_cu3(self): self.circuit.append(CU3Gate(1, 2, 3), [self.qr[1], self.qr[2]]) self.assertEqual(self.circuit[0].operation.name, "cu3") self.assertEqual(self.circuit[0].operation.params, [1, 2, 3]) self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2])) def test_cu3_wires(self): self.circuit.append(CU3Gate(1, 2, 3), [1, 2]) self.assertEqual(self.circuit[0].operation.name, "cu3") self.assertEqual(self.circuit[0].operation.params, [1, 2, 3]) self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2])) def test_cx(self): self.circuit.cx(self.qr[1], self.qr[2]) self.assertEqual(self.circuit[0].operation.name, "cx") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2])) def test_cx_wires(self): self.circuit.cx(1, 2) self.assertEqual(self.circuit[0].operation.name, "cx") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2])) def test_cx_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.cx, self.cr[1], self.cr[2]) self.assertRaises(CircuitError, qc.cx, self.qr[0], self.qr[0]) self.assertRaises(CircuitError, qc.cx, 0.0, self.qr[0]) self.assertRaises(CircuitError, qc.cx, (self.qr, 3), self.qr[0]) self.assertRaises(CircuitError, qc.cx, self.cr, self.qr) self.assertRaises(CircuitError, qc.cx, "a", self.qr[1]) def test_cy(self): self.circuit.cy(self.qr[1], self.qr[2]) self.assertEqual(self.circuit[0].operation.name, "cy") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2])) def test_cy_wires(self): self.circuit.cy(1, 2) self.assertEqual(self.circuit[0].operation.name, "cy") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2])) def test_cy_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.cy, self.cr[1], self.cr[2]) self.assertRaises(CircuitError, qc.cy, self.qr[0], self.qr[0]) self.assertRaises(CircuitError, qc.cy, 0.0, self.qr[0]) self.assertRaises(CircuitError, qc.cy, (self.qr, 3), self.qr[0]) self.assertRaises(CircuitError, qc.cy, self.cr, self.qr) self.assertRaises(CircuitError, qc.cy, "a", self.qr[1]) def test_cz(self): self.circuit.cz(self.qr[1], self.qr[2]) self.assertEqual(self.circuit[0].operation.name, "cz") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2])) def test_cz_wires(self): self.circuit.cz(1, 2) self.assertEqual(self.circuit[0].operation.name, "cz") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2])) def test_cz_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.cz, self.cr[1], self.cr[2]) self.assertRaises(CircuitError, qc.cz, self.qr[0], self.qr[0]) self.assertRaises(CircuitError, qc.cz, 0.0, self.qr[0]) self.assertRaises(CircuitError, qc.cz, (self.qr, 3), self.qr[0]) self.assertRaises(CircuitError, qc.cz, self.cr, self.qr) self.assertRaises(CircuitError, qc.cz, "a", self.qr[1]) def test_h(self): self.circuit.h(self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "h") self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_h_wires(self): self.circuit.h(1) self.assertEqual(self.circuit[0].operation.name, "h") self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_h_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.h, self.cr[0]) self.assertRaises(CircuitError, qc.h, self.cr) self.assertRaises(CircuitError, qc.h, (self.qr, 3)) self.assertRaises(CircuitError, qc.h, (self.qr, "a")) self.assertRaises(CircuitError, qc.h, 0.0) def test_h_reg(self): instruction_set = self.circuit.h(self.qr) self.assertEqual(len(instruction_set), 3) self.assertEqual(instruction_set[0].operation.name, "h") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) def test_h_reg_inv(self): instruction_set = self.circuit.h(self.qr).inverse() self.assertEqual(len(instruction_set), 3) self.assertEqual(instruction_set[0].operation.name, "h") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) def test_iden(self): self.circuit.i(self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "id") self.assertEqual(self.circuit[0].operation.params, []) def test_iden_wires(self): self.circuit.i(1) self.assertEqual(self.circuit[0].operation.name, "id") self.assertEqual(self.circuit[0].operation.params, []) def test_iden_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.i, self.cr[0]) self.assertRaises(CircuitError, qc.i, self.cr) self.assertRaises(CircuitError, qc.i, (self.qr, 3)) self.assertRaises(CircuitError, qc.i, (self.qr, "a")) self.assertRaises(CircuitError, qc.i, 0.0) def test_iden_reg(self): instruction_set = self.circuit.i(self.qr) self.assertEqual(len(instruction_set), 3) self.assertEqual(instruction_set[0].operation.name, "id") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) def test_iden_reg_inv(self): instruction_set = self.circuit.i(self.qr).inverse() self.assertEqual(len(instruction_set), 3) self.assertEqual(instruction_set[0].operation.name, "id") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) def test_rx(self): self.circuit.rx(1, self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "rx") self.assertEqual(self.circuit[0].operation.params, [1]) def test_rx_wires(self): self.circuit.rx(1, 1) self.assertEqual(self.circuit[0].operation.name, "rx") self.assertEqual(self.circuit[0].operation.params, [1]) def test_rx_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.rx, self.cr[0], self.cr[1]) self.assertRaises(CircuitError, qc.rx, self.qr[1], 0) self.assertRaises(CircuitError, qc.rx, 0, self.cr[0]) self.assertRaises(CircuitError, qc.rx, 0, 0.0) self.assertRaises(CircuitError, qc.rx, self.qr[2], self.qr[1]) self.assertRaises(CircuitError, qc.rx, 0, (self.qr, 3)) self.assertRaises(CircuitError, qc.rx, 0, self.cr) # TODO self.assertRaises(CircuitError, qc.rx, 'a', self.qr[1]) self.assertRaises(CircuitError, qc.rx, 0, "a") def test_rx_reg(self): instruction_set = self.circuit.rx(1, self.qr) self.assertEqual(len(instruction_set), 3) self.assertEqual(instruction_set[0].operation.name, "rx") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, [1]) def test_rx_reg_inv(self): instruction_set = self.circuit.rx(1, self.qr).inverse() self.assertEqual(len(instruction_set), 3) self.assertEqual(instruction_set[0].operation.name, "rx") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, [-1]) def test_rx_pi(self): qc = self.circuit qc.rx(pi / 2, self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "rx") self.assertEqual(self.circuit[0].operation.params, [pi / 2]) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_ry(self): self.circuit.ry(1, self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "ry") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_ry_wires(self): self.circuit.ry(1, 1) self.assertEqual(self.circuit[0].operation.name, "ry") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_ry_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.ry, self.cr[0], self.cr[1]) self.assertRaises(CircuitError, qc.ry, self.qr[1], 0) self.assertRaises(CircuitError, qc.ry, 0, self.cr[0]) self.assertRaises(CircuitError, qc.ry, 0, 0.0) self.assertRaises(CircuitError, qc.ry, self.qr[2], self.qr[1]) self.assertRaises(CircuitError, qc.ry, 0, (self.qr, 3)) self.assertRaises(CircuitError, qc.ry, 0, self.cr) # TODO self.assertRaises(CircuitError, qc.ry, 'a', self.qr[1]) self.assertRaises(CircuitError, qc.ry, 0, "a") def test_ry_reg(self): instruction_set = self.circuit.ry(1, self.qr) self.assertEqual(instruction_set[0].operation.name, "ry") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, [1]) def test_ry_reg_inv(self): instruction_set = self.circuit.ry(1, self.qr).inverse() self.assertEqual(instruction_set[0].operation.name, "ry") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, [-1]) def test_ry_pi(self): qc = self.circuit qc.ry(pi / 2, self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "ry") self.assertEqual(self.circuit[0].operation.params, [pi / 2]) def test_rz(self): self.circuit.rz(1, self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "rz") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_rz_wires(self): self.circuit.rz(1, 1) self.assertEqual(self.circuit[0].operation.name, "rz") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_rz_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.rz, self.cr[0], self.cr[1]) self.assertRaises(CircuitError, qc.rz, self.qr[1], 0) self.assertRaises(CircuitError, qc.rz, 0, self.cr[0]) self.assertRaises(CircuitError, qc.rz, 0, 0.0) self.assertRaises(CircuitError, qc.rz, self.qr[2], self.qr[1]) self.assertRaises(CircuitError, qc.rz, 0, (self.qr, 3)) self.assertRaises(CircuitError, qc.rz, 0, self.cr) # TODO self.assertRaises(CircuitError, qc.rz, 'a', self.qr[1]) self.assertRaises(CircuitError, qc.rz, 0, "a") def test_rz_reg(self): instruction_set = self.circuit.rz(1, self.qr) self.assertEqual(instruction_set[0].operation.name, "rz") self.assertEqual(instruction_set[2].operation.params, [1]) def test_rz_reg_inv(self): instruction_set = self.circuit.rz(1, self.qr).inverse() self.assertEqual(instruction_set[0].operation.name, "rz") self.assertEqual(instruction_set[2].operation.params, [-1]) def test_rz_pi(self): self.circuit.rz(pi / 2, self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "rz") self.assertEqual(self.circuit[0].operation.params, [pi / 2]) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_rzz(self): self.circuit.rzz(1, self.qr[1], self.qr[2]) self.assertEqual(self.circuit[0].operation.name, "rzz") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2])) def test_rzz_wires(self): self.circuit.rzz(1, 1, 2) self.assertEqual(self.circuit[0].operation.name, "rzz") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2])) def test_rzz_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.rzz, 1, self.cr[1], self.cr[2]) self.assertRaises(CircuitError, qc.rzz, 1, self.qr[0], self.qr[0]) self.assertRaises(CircuitError, qc.rzz, 1, 0.0, self.qr[0]) self.assertRaises(CircuitError, qc.rzz, 1, (self.qr, 3), self.qr[0]) self.assertRaises(CircuitError, qc.rzz, 1, self.cr, self.qr) self.assertRaises(CircuitError, qc.rzz, 1, "a", self.qr[1]) self.assertRaises(CircuitError, qc.rzz, 0.1, self.cr[1], self.cr[2]) self.assertRaises(CircuitError, qc.rzz, 0.1, self.qr[0], self.qr[0]) def test_s(self): self.circuit.s(self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "s") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_s_wires(self): self.circuit.s(1) self.assertEqual(self.circuit[0].operation.name, "s") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_s_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.s, self.cr[0]) self.assertRaises(CircuitError, qc.s, self.cr) self.assertRaises(CircuitError, qc.s, (self.qr, 3)) self.assertRaises(CircuitError, qc.s, (self.qr, "a")) self.assertRaises(CircuitError, qc.s, 0.0) def test_s_reg(self): instruction_set = self.circuit.s(self.qr) self.assertEqual(instruction_set[0].operation.name, "s") self.assertEqual(instruction_set[2].operation.params, []) def test_s_reg_inv(self): instruction_set = self.circuit.s(self.qr).inverse() self.assertEqual(instruction_set[0].operation.name, "sdg") self.assertEqual(instruction_set[2].operation.params, []) def test_sdg(self): self.circuit.sdg(self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "sdg") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_sdg_wires(self): self.circuit.sdg(1) self.assertEqual(self.circuit[0].operation.name, "sdg") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_sdg_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.sdg, self.cr[0]) self.assertRaises(CircuitError, qc.sdg, self.cr) self.assertRaises(CircuitError, qc.sdg, (self.qr, 3)) self.assertRaises(CircuitError, qc.sdg, (self.qr, "a")) self.assertRaises(CircuitError, qc.sdg, 0.0) def test_sdg_reg(self): instruction_set = self.circuit.sdg(self.qr) self.assertEqual(instruction_set[0].operation.name, "sdg") self.assertEqual(instruction_set[2].operation.params, []) def test_sdg_reg_inv(self): instruction_set = self.circuit.sdg(self.qr).inverse() self.assertEqual(instruction_set[0].operation.name, "s") self.assertEqual(instruction_set[2].operation.params, []) def test_swap(self): self.circuit.swap(self.qr[1], self.qr[2]) self.assertEqual(self.circuit[0].operation.name, "swap") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2])) def test_swap_wires(self): self.circuit.swap(1, 2) self.assertEqual(self.circuit[0].operation.name, "swap") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2])) def test_swap_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.swap, self.cr[1], self.cr[2]) self.assertRaises(CircuitError, qc.swap, self.qr[0], self.qr[0]) self.assertRaises(CircuitError, qc.swap, 0.0, self.qr[0]) self.assertRaises(CircuitError, qc.swap, (self.qr, 3), self.qr[0]) self.assertRaises(CircuitError, qc.swap, self.cr, self.qr) self.assertRaises(CircuitError, qc.swap, "a", self.qr[1]) self.assertRaises(CircuitError, qc.swap, self.qr, self.qr2[[1, 2]]) self.assertRaises(CircuitError, qc.swap, self.qr[:2], self.qr2) def test_t(self): self.circuit.t(self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "t") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_t_wire(self): self.circuit.t(1) self.assertEqual(self.circuit[0].operation.name, "t") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_t_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.t, self.cr[0]) self.assertRaises(CircuitError, qc.t, self.cr) self.assertRaises(CircuitError, qc.t, (self.qr, 3)) self.assertRaises(CircuitError, qc.t, (self.qr, "a")) self.assertRaises(CircuitError, qc.t, 0.0) def test_t_reg(self): instruction_set = self.circuit.t(self.qr) self.assertEqual(instruction_set[0].operation.name, "t") self.assertEqual(instruction_set[2].operation.params, []) def test_t_reg_inv(self): instruction_set = self.circuit.t(self.qr).inverse() self.assertEqual(instruction_set[0].operation.name, "tdg") self.assertEqual(instruction_set[2].operation.params, []) def test_tdg(self): self.circuit.tdg(self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "tdg") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_tdg_wires(self): self.circuit.tdg(1) self.assertEqual(self.circuit[0].operation.name, "tdg") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_tdg_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.tdg, self.cr[0]) self.assertRaises(CircuitError, qc.tdg, self.cr) self.assertRaises(CircuitError, qc.tdg, (self.qr, 3)) self.assertRaises(CircuitError, qc.tdg, (self.qr, "a")) self.assertRaises(CircuitError, qc.tdg, 0.0) def test_tdg_reg(self): instruction_set = self.circuit.tdg(self.qr) self.assertEqual(instruction_set[0].operation.name, "tdg") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, []) def test_tdg_reg_inv(self): instruction_set = self.circuit.tdg(self.qr).inverse() self.assertEqual(instruction_set[0].operation.name, "t") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, []) def test_u1(self): self.circuit.append(U1Gate(1), [self.qr[1]]) self.assertEqual(self.circuit[0].operation.name, "u1") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_u1_wires(self): self.circuit.append(U1Gate(1), [1]) self.assertEqual(self.circuit[0].operation.name, "u1") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_u1_reg(self): instruction_set = self.circuit.append(U1Gate(1), [self.qr]) self.assertEqual(instruction_set[0].operation.name, "u1") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, [1]) def test_u1_reg_inv(self): instruction_set = self.circuit.append(U1Gate(1), [self.qr]).inverse() self.assertEqual(instruction_set[0].operation.name, "u1") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, [-1]) def test_u1_pi(self): qc = self.circuit qc.append(U1Gate(pi / 2), [self.qr[1]]) self.assertEqual(self.circuit[0].operation.name, "u1") self.assertEqual(self.circuit[0].operation.params, [pi / 2]) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_u2(self): self.circuit.append(U2Gate(1, 2), [self.qr[1]]) self.assertEqual(self.circuit[0].operation.name, "u2") self.assertEqual(self.circuit[0].operation.params, [1, 2]) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_u2_wires(self): self.circuit.append(U2Gate(1, 2), [1]) self.assertEqual(self.circuit[0].operation.name, "u2") self.assertEqual(self.circuit[0].operation.params, [1, 2]) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_u2_reg(self): instruction_set = self.circuit.append(U2Gate(1, 2), [self.qr]) self.assertEqual(instruction_set[0].operation.name, "u2") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, [1, 2]) def test_u2_reg_inv(self): instruction_set = self.circuit.append(U2Gate(1, 2), [self.qr]).inverse() self.assertEqual(instruction_set[0].operation.name, "u2") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, [-pi - 2, -1 + pi]) def test_u2_pi(self): self.circuit.append(U2Gate(pi / 2, 0.3 * pi), [self.qr[1]]) self.assertEqual(self.circuit[0].operation.name, "u2") self.assertEqual(self.circuit[0].operation.params, [pi / 2, 0.3 * pi]) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_u3(self): self.circuit.append(U3Gate(1, 2, 3), [self.qr[1]]) self.assertEqual(self.circuit[0].operation.name, "u3") self.assertEqual(self.circuit[0].operation.params, [1, 2, 3]) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_u3_wires(self): self.circuit.append(U3Gate(1, 2, 3), [1]) self.assertEqual(self.circuit[0].operation.name, "u3") self.assertEqual(self.circuit[0].operation.params, [1, 2, 3]) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_u3_reg(self): instruction_set = self.circuit.append(U3Gate(1, 2, 3), [self.qr]) self.assertEqual(instruction_set[0].operation.name, "u3") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, [1, 2, 3]) def test_u3_reg_inv(self): instruction_set = self.circuit.append(U3Gate(1, 2, 3), [self.qr]).inverse() self.assertEqual(instruction_set[0].operation.name, "u3") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, [-1, -3, -2]) def test_u3_pi(self): self.circuit.append(U3Gate(pi, pi / 2, 0.3 * pi), [self.qr[1]]) self.assertEqual(self.circuit[0].operation.name, "u3") self.assertEqual(self.circuit[0].operation.params, [pi, pi / 2, 0.3 * pi]) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_x(self): self.circuit.x(self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "x") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_x_wires(self): self.circuit.x(1) self.assertEqual(self.circuit[0].operation.name, "x") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_x_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.x, self.cr[0]) self.assertRaises(CircuitError, qc.x, self.cr) self.assertRaises(CircuitError, qc.x, (self.qr, "a")) self.assertRaises(CircuitError, qc.x, 0.0) def test_x_reg(self): instruction_set = self.circuit.x(self.qr) self.assertEqual(instruction_set[0].operation.name, "x") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, []) def test_x_reg_inv(self): instruction_set = self.circuit.x(self.qr).inverse() self.assertEqual(instruction_set[0].operation.name, "x") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, []) def test_y(self): self.circuit.y(self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "y") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_y_wires(self): self.circuit.y(1) self.assertEqual(self.circuit[0].operation.name, "y") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_y_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.y, self.cr[0]) self.assertRaises(CircuitError, qc.y, self.cr) self.assertRaises(CircuitError, qc.y, (self.qr, "a")) self.assertRaises(CircuitError, qc.y, 0.0) def test_y_reg(self): instruction_set = self.circuit.y(self.qr) self.assertEqual(instruction_set[0].operation.name, "y") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, []) def test_y_reg_inv(self): instruction_set = self.circuit.y(self.qr).inverse() self.assertEqual(instruction_set[0].operation.name, "y") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, []) def test_z(self): self.circuit.z(self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "z") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_z_wires(self): self.circuit.z(1) self.assertEqual(self.circuit[0].operation.name, "z") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_z_reg(self): instruction_set = self.circuit.z(self.qr) self.assertEqual(instruction_set[0].operation.name, "z") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, []) def test_z_reg_inv(self): instruction_set = self.circuit.z(self.qr).inverse() self.assertEqual(instruction_set[0].operation.name, "z") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, []) def test_global_phase(self): qc = self.circuit qc.append(GlobalPhaseGate(0.1), []) self.assertEqual(self.circuit[0].operation.name, "global_phase") self.assertEqual(self.circuit[0].operation.params, [0.1]) self.assertEqual(self.circuit[0].qubits, ()) def test_global_phase_inv(self): instruction_set = self.circuit.append(GlobalPhaseGate(0.1), []).inverse() self.assertEqual(len(instruction_set), 1) self.assertEqual(instruction_set[0].operation.params, [-0.1]) def test_global_phase_matrix(self): """Test global_phase matrix.""" theta = 0.1 np.testing.assert_allclose( np.array(GlobalPhaseGate(theta)), np.array([[np.exp(1j * theta)]], dtype=complex), atol=1e-7, ) def test_global_phase_consistency(self): """Tests compatibility of GlobalPhaseGate with QuantumCircuit.global_phase""" theta = 0.1 qc1 = QuantumCircuit(0, global_phase=theta) qc2 = QuantumCircuit(0) qc2.append(GlobalPhaseGate(theta), []) np.testing.assert_allclose( Operator(qc1), Operator(qc2), atol=1e-7, ) def test_transpile_global_phase_consistency(self): """Tests compatibility of transpiled GlobalPhaseGate with QuantumCircuit.global_phase""" qc1 = QuantumCircuit(0, global_phase=0.3) qc2 = QuantumCircuit(0, global_phase=0.2) qc2.append(GlobalPhaseGate(0.1), []) np.testing.assert_allclose( Operator(transpile(qc1, basis_gates=["u"])), Operator(transpile(qc2, basis_gates=["u"])), atol=1e-7, ) @ddt class TestStandard2Q(QiskitTestCase): """Standard Extension Test. Gates with two Qubits""" def setUp(self): super().setUp() self.qr = QuantumRegister(3, "q") self.qr2 = QuantumRegister(3, "r") self.cr = ClassicalRegister(3, "c") self.circuit = QuantumCircuit(self.qr, self.qr2, self.cr) def test_barrier_reg_bit(self): self.circuit.barrier(self.qr, self.qr2[0]) self.assertEqual(len(self.circuit), 1) self.assertEqual(self.circuit[0].operation.name, "barrier") self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1], self.qr[2], self.qr2[0])) def test_ch_reg_reg(self): instruction_set = self.circuit.ch(self.qr, self.qr2) self.assertEqual(instruction_set[0].operation.name, "ch") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_ch_reg_reg_inv(self): instruction_set = self.circuit.ch(self.qr, self.qr2).inverse() self.assertEqual(instruction_set[0].operation.name, "ch") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_ch_reg_bit(self): instruction_set = self.circuit.ch(self.qr, self.qr2[1]) self.assertEqual(instruction_set[0].operation.name, "ch") self.assertEqual( instruction_set[1].qubits, ( self.qr[1], self.qr2[1], ), ) self.assertEqual(instruction_set[2].operation.params, []) def test_ch_reg_bit_inv(self): instruction_set = self.circuit.ch(self.qr, self.qr2[1]).inverse() self.assertEqual(instruction_set[0].operation.name, "ch") self.assertEqual( instruction_set[1].qubits, ( self.qr[1], self.qr2[1], ), ) self.assertEqual(instruction_set[2].operation.params, []) def test_ch_bit_reg(self): instruction_set = self.circuit.ch(self.qr[1], self.qr2) self.assertEqual(instruction_set[0].operation.name, "ch") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_crz_reg_reg(self): instruction_set = self.circuit.crz(1, self.qr, self.qr2) self.assertEqual(instruction_set[0].operation.name, "crz") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [1]) def test_crz_reg_reg_inv(self): instruction_set = self.circuit.crz(1, self.qr, self.qr2).inverse() self.assertEqual(instruction_set[0].operation.name, "crz") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [-1]) def test_crz_reg_bit(self): instruction_set = self.circuit.crz(1, self.qr, self.qr2[1]) self.assertEqual(instruction_set[0].operation.name, "crz") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [1]) def test_crz_reg_bit_inv(self): instruction_set = self.circuit.crz(1, self.qr, self.qr2[1]).inverse() self.assertEqual(instruction_set[0].operation.name, "crz") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [-1]) def test_crz_bit_reg(self): instruction_set = self.circuit.crz(1, self.qr[1], self.qr2) self.assertEqual(instruction_set[0].operation.name, "crz") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [1]) def test_crz_bit_reg_inv(self): instruction_set = self.circuit.crz(1, self.qr[1], self.qr2).inverse() self.assertEqual(instruction_set[0].operation.name, "crz") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [-1]) def test_cry_reg_reg(self): instruction_set = self.circuit.cry(1, self.qr, self.qr2) self.assertEqual(instruction_set[0].operation.name, "cry") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [1]) def test_cry_reg_reg_inv(self): instruction_set = self.circuit.cry(1, self.qr, self.qr2).inverse() self.assertEqual(instruction_set[0].operation.name, "cry") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [-1]) def test_cry_reg_bit(self): instruction_set = self.circuit.cry(1, self.qr, self.qr2[1]) self.assertEqual(instruction_set[0].operation.name, "cry") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [1]) def test_cry_reg_bit_inv(self): instruction_set = self.circuit.cry(1, self.qr, self.qr2[1]).inverse() self.assertEqual(instruction_set[0].operation.name, "cry") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [-1]) def test_cry_bit_reg(self): instruction_set = self.circuit.cry(1, self.qr[1], self.qr2) self.assertEqual(instruction_set[0].operation.name, "cry") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [1]) def test_cry_bit_reg_inv(self): instruction_set = self.circuit.cry(1, self.qr[1], self.qr2).inverse() self.assertEqual(instruction_set[0].operation.name, "cry") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [-1]) def test_crx_reg_reg(self): instruction_set = self.circuit.crx(1, self.qr, self.qr2) self.assertEqual(instruction_set[0].operation.name, "crx") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [1]) def test_crx_reg_reg_inv(self): instruction_set = self.circuit.crx(1, self.qr, self.qr2).inverse() self.assertEqual(instruction_set[0].operation.name, "crx") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [-1]) def test_crx_reg_bit(self): instruction_set = self.circuit.crx(1, self.qr, self.qr2[1]) self.assertEqual(instruction_set[0].operation.name, "crx") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [1]) def test_crx_reg_bit_inv(self): instruction_set = self.circuit.crx(1, self.qr, self.qr2[1]).inverse() self.assertEqual(instruction_set[0].operation.name, "crx") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [-1]) def test_crx_bit_reg(self): instruction_set = self.circuit.crx(1, self.qr[1], self.qr2) self.assertEqual(instruction_set[0].operation.name, "crx") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [1]) def test_crx_bit_reg_inv(self): instruction_set = self.circuit.crx(1, self.qr[1], self.qr2).inverse() self.assertEqual(instruction_set[0].operation.name, "crx") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [-1]) def test_cu1_reg_reg(self): instruction_set = self.circuit.append(CU1Gate(1), [self.qr, self.qr2]) self.assertEqual(instruction_set[0].operation.name, "cu1") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [1]) def test_cu1_reg_reg_inv(self): instruction_set = self.circuit.append(CU1Gate(1), [self.qr, self.qr2]).inverse() self.assertEqual(instruction_set[0].operation.name, "cu1") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [-1]) def test_cu1_reg_bit(self): instruction_set = self.circuit.append(CU1Gate(1), [self.qr, self.qr2[1]]) self.assertEqual(instruction_set[0].operation.name, "cu1") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [1]) def test_cu1_reg_bit_inv(self): instruction_set = self.circuit.append(CU1Gate(1), [self.qr, self.qr2[1]]).inverse() self.assertEqual(instruction_set[0].operation.name, "cu1") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [-1]) def test_cu1_bit_reg(self): instruction_set = self.circuit.append(CU1Gate(1), [self.qr[1], self.qr2]) self.assertEqual(instruction_set[0].operation.name, "cu1") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [1]) def test_cu1_bit_reg_inv(self): instruction_set = self.circuit.append(CU1Gate(1), [self.qr[1], self.qr2]).inverse() self.assertEqual(instruction_set[0].operation.name, "cu1") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [-1]) def test_cu3_reg_reg(self): instruction_set = self.circuit.append(CU3Gate(1, 2, 3), [self.qr, self.qr2]) self.assertEqual(instruction_set[0].operation.name, "cu3") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [1, 2, 3]) def test_cu3_reg_reg_inv(self): instruction_set = self.circuit.append(CU3Gate(1, 2, 3), [self.qr, self.qr2]).inverse() self.assertEqual(instruction_set[0].operation.name, "cu3") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [-1, -3, -2]) def test_cu3_reg_bit(self): instruction_set = self.circuit.append(CU3Gate(1, 2, 3), [self.qr, self.qr2[1]]) self.assertEqual(instruction_set[0].operation.name, "cu3") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [1, 2, 3]) def test_cu3_reg_bit_inv(self): instruction_set = self.circuit.append(CU3Gate(1, 2, 3), [self.qr, self.qr2[1]]).inverse() self.assertEqual(instruction_set[0].operation.name, "cu3") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [-1, -3, -2]) def test_cu3_bit_reg(self): instruction_set = self.circuit.append(CU3Gate(1, 2, 3), [self.qr[1], self.qr2]) self.assertEqual(instruction_set[0].operation.name, "cu3") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [1, 2, 3]) def test_cu3_bit_reg_inv(self): instruction_set = self.circuit.append(CU3Gate(1, 2, 3), [self.qr[1], self.qr2]).inverse() self.assertEqual(instruction_set[0].operation.name, "cu3") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [-1, -3, -2]) def test_cx_reg_reg(self): instruction_set = self.circuit.cx(self.qr, self.qr2) self.assertEqual(instruction_set[0].operation.name, "cx") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cx_reg_reg_inv(self): instruction_set = self.circuit.cx(self.qr, self.qr2).inverse() self.assertEqual(instruction_set[0].operation.name, "cx") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cx_reg_bit(self): instruction_set = self.circuit.cx(self.qr, self.qr2[1]) self.assertEqual(instruction_set[0].operation.name, "cx") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cx_reg_bit_inv(self): instruction_set = self.circuit.cx(self.qr, self.qr2[1]).inverse() self.assertEqual(instruction_set[0].operation.name, "cx") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cx_bit_reg(self): instruction_set = self.circuit.cx(self.qr[1], self.qr2) self.assertEqual(instruction_set[0].operation.name, "cx") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cx_bit_reg_inv(self): instruction_set = self.circuit.cx(self.qr[1], self.qr2).inverse() self.assertEqual(instruction_set[0].operation.name, "cx") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cy_reg_reg(self): instruction_set = self.circuit.cy(self.qr, self.qr2) self.assertEqual(instruction_set[0].operation.name, "cy") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cy_reg_reg_inv(self): instruction_set = self.circuit.cy(self.qr, self.qr2).inverse() self.assertEqual(instruction_set[0].operation.name, "cy") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cy_reg_bit(self): instruction_set = self.circuit.cy(self.qr, self.qr2[1]) self.assertEqual(instruction_set[0].operation.name, "cy") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cy_reg_bit_inv(self): instruction_set = self.circuit.cy(self.qr, self.qr2[1]).inverse() self.assertEqual(instruction_set[0].operation.name, "cy") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cy_bit_reg(self): instruction_set = self.circuit.cy(self.qr[1], self.qr2) self.assertEqual(instruction_set[0].operation.name, "cy") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cy_bit_reg_inv(self): instruction_set = self.circuit.cy(self.qr[1], self.qr2).inverse() self.assertEqual(instruction_set[0].operation.name, "cy") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cz_reg_reg(self): instruction_set = self.circuit.cz(self.qr, self.qr2) self.assertEqual(instruction_set[0].operation.name, "cz") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cz_reg_reg_inv(self): instruction_set = self.circuit.cz(self.qr, self.qr2).inverse() self.assertEqual(instruction_set[0].operation.name, "cz") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cz_reg_bit(self): instruction_set = self.circuit.cz(self.qr, self.qr2[1]) self.assertEqual(instruction_set[0].operation.name, "cz") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cz_reg_bit_inv(self): instruction_set = self.circuit.cz(self.qr, self.qr2[1]).inverse() self.assertEqual(instruction_set[0].operation.name, "cz") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cz_bit_reg(self): instruction_set = self.circuit.cz(self.qr[1], self.qr2) self.assertEqual(instruction_set[0].operation.name, "cz") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cz_bit_reg_inv(self): instruction_set = self.circuit.cz(self.qr[1], self.qr2).inverse() self.assertEqual(instruction_set[0].operation.name, "cz") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_swap_reg_reg(self): instruction_set = self.circuit.swap(self.qr, self.qr2) self.assertEqual(instruction_set[0].operation.name, "swap") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_swap_reg_reg_inv(self): instruction_set = self.circuit.swap(self.qr, self.qr2).inverse() self.assertEqual(instruction_set[0].operation.name, "swap") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) @unpack @data( (0, 0, np.eye(4)), ( np.pi / 2, np.pi / 2, np.array( [ [np.sqrt(2) / 2, 0, 0, -np.sqrt(2) / 2], [0, 1, 0, 0], [0, 0, 1, 0], [np.sqrt(2) / 2, 0, 0, np.sqrt(2) / 2], ] ), ), ( np.pi, np.pi / 2, np.array([[0, 0, 0, -1], [0, 1, 0, 0], [0, 0, 1, 0], [1, 0, 0, 0]]), ), ( 2 * np.pi, np.pi / 2, np.array([[-1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, -1]]), ), ( np.pi / 2, np.pi, np.array( [ [np.sqrt(2) / 2, 0, 0, 1j * np.sqrt(2) / 2], [0, 1, 0, 0], [0, 0, 1, 0], [1j * np.sqrt(2) / 2, 0, 0, np.sqrt(2) / 2], ] ), ), (4 * np.pi, 0, np.eye(4)), ) def test_xx_minus_yy_matrix(self, theta: float, beta: float, expected: np.ndarray): """Test XX-YY matrix.""" gate = XXMinusYYGate(theta, beta) np.testing.assert_allclose(np.array(gate), expected, atol=1e-7) def test_xx_minus_yy_exponential_formula(self): """Test XX-YY exponential formula.""" theta, beta = np.random.uniform(-10, 10, size=2) gate = XXMinusYYGate(theta, beta) x = np.array(XGate()) y = np.array(YGate()) xx = np.kron(x, x) yy = np.kron(y, y) rz1 = np.kron(np.array(RZGate(beta)), np.eye(2)) np.testing.assert_allclose( np.array(gate), rz1 @ expm(-0.25j * theta * (xx - yy)) @ rz1.T.conj(), atol=1e-7, ) def test_xx_plus_yy_exponential_formula(self): """Test XX+YY exponential formula.""" theta, beta = np.random.uniform(-10, 10, size=2) gate = XXPlusYYGate(theta, beta) x = np.array(XGate()) y = np.array(YGate()) xx = np.kron(x, x) yy = np.kron(y, y) rz0 = np.kron(np.eye(2), np.array(RZGate(beta))) np.testing.assert_allclose( np.array(gate), rz0.T.conj() @ expm(-0.25j * theta * (xx + yy)) @ rz0, atol=1e-7, ) class TestStandard3Q(QiskitTestCase): """Standard Extension Test. Gates with three Qubits""" def setUp(self): super().setUp() self.qr = QuantumRegister(3, "q") self.qr2 = QuantumRegister(3, "r") self.qr3 = QuantumRegister(3, "s") self.cr = ClassicalRegister(3, "c") self.circuit = QuantumCircuit(self.qr, self.qr2, self.qr3, self.cr) def test_ccx_reg_reg_reg(self): instruction_set = self.circuit.ccx(self.qr, self.qr2, self.qr3) self.assertEqual(instruction_set[0].operation.name, "ccx") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1], self.qr3[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_ccx_reg_reg_inv(self): instruction_set = self.circuit.ccx(self.qr, self.qr2, self.qr3).inverse() self.assertEqual(instruction_set[0].operation.name, "ccx") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1], self.qr3[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cswap_reg_reg_reg(self): instruction_set = self.circuit.cswap(self.qr, self.qr2, self.qr3) self.assertEqual(instruction_set[0].operation.name, "cswap") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1], self.qr3[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cswap_reg_reg_inv(self): instruction_set = self.circuit.cswap(self.qr, self.qr2, self.qr3).inverse() self.assertEqual(instruction_set[0].operation.name, "cswap") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1], self.qr3[1])) self.assertEqual(instruction_set[2].operation.params, []) class TestStandardMethods(QiskitTestCase): """Standard Extension Test.""" @unittest.skipUnless(HAS_TWEEDLEDUM, "tweedledum required for this test") def test_to_matrix(self): """test gates implementing to_matrix generate matrix which matches definition.""" from qiskit.circuit.library.pauli_evolution import PauliEvolutionGate from qiskit.circuit.library.generalized_gates.pauli import PauliGate from qiskit.circuit.classicalfunction.boolean_expression import BooleanExpression params = [0.1 * (i + 1) for i in range(10)] gate_class_list = Gate.__subclasses__() + ControlledGate.__subclasses__() simulator = BasicAer.get_backend("unitary_simulator") for gate_class in gate_class_list: if hasattr(gate_class, "__abstractmethods__"): # gate_class is abstract continue sig = signature(gate_class) free_params = len(set(sig.parameters) - {"label", "ctrl_state"}) try: if gate_class == PauliGate: # special case due to PauliGate using string parameters gate = gate_class("IXYZ") elif gate_class == BooleanExpression: gate = gate_class("x") elif gate_class == PauliEvolutionGate: gate = gate_class(Pauli("XYZ")) else: gate = gate_class(*params[0:free_params]) except (CircuitError, QiskitError, AttributeError, TypeError): self.log.info("Cannot init gate with params only. Skipping %s", gate_class) continue if gate.name in ["U", "CX"]: continue circ = QuantumCircuit(gate.num_qubits) circ.append(gate, range(gate.num_qubits)) try: gate_matrix = gate.to_matrix() except CircuitError: # gate doesn't implement to_matrix method: skip self.log.info('to_matrix method FAILED for "%s" gate', gate.name) continue definition_unitary = execute([circ], simulator).result().get_unitary() with self.subTest(gate_class): # TODO check for exact equality once BasicAer can handle global phase self.assertTrue(matrix_equal(definition_unitary, gate_matrix, ignore_phase=True)) self.assertTrue(is_unitary_matrix(gate_matrix)) @unittest.skipUnless(HAS_TWEEDLEDUM, "tweedledum required for this test") def test_to_matrix_op(self): """test gates implementing to_matrix generate matrix which matches definition using Operator.""" from qiskit.circuit.library.generalized_gates.gms import MSGate from qiskit.circuit.library.generalized_gates.pauli import PauliGate from qiskit.circuit.library.pauli_evolution import PauliEvolutionGate from qiskit.circuit.classicalfunction.boolean_expression import BooleanExpression params = [0.1 * i for i in range(1, 11)] gate_class_list = Gate.__subclasses__() + ControlledGate.__subclasses__() for gate_class in gate_class_list: if hasattr(gate_class, "__abstractmethods__"): # gate_class is abstract continue sig = signature(gate_class) if gate_class == MSGate: # due to the signature (num_qubits, theta, *, n_qubits=Noe) the signature detects # 3 arguments but really its only 2. This if can be removed once the deprecated # n_qubits argument is no longer supported. free_params = 2 else: free_params = len(set(sig.parameters) - {"label", "ctrl_state"}) try: if gate_class == PauliGate: # special case due to PauliGate using string parameters gate = gate_class("IXYZ") elif gate_class == BooleanExpression: gate = gate_class("x") elif gate_class == PauliEvolutionGate: gate = gate_class(Pauli("XYZ")) else: gate = gate_class(*params[0:free_params]) except (CircuitError, QiskitError, AttributeError, TypeError): self.log.info("Cannot init gate with params only. Skipping %s", gate_class) continue if gate.name in ["U", "CX"]: continue try: gate_matrix = gate.to_matrix() except CircuitError: # gate doesn't implement to_matrix method: skip self.log.info('to_matrix method FAILED for "%s" gate', gate.name) continue if not hasattr(gate, "definition") or not gate.definition: continue definition_unitary = Operator(gate.definition).data self.assertTrue(matrix_equal(definition_unitary, gate_matrix)) self.assertTrue(is_unitary_matrix(gate_matrix)) if __name__ == "__main__": unittest.main(verbosity=2)
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test hardcoded decomposition rules and matrix definitions for standard gates.""" import inspect import numpy as np from ddt import ddt, data, idata, unpack from qiskit import QuantumCircuit, QuantumRegister from qiskit.quantum_info import Operator from qiskit.test import QiskitTestCase from qiskit.circuit import ParameterVector, Gate, ControlledGate from qiskit.circuit.library import standard_gates from qiskit.circuit.library import ( HGate, CHGate, IGate, RGate, RXGate, CRXGate, RYGate, CRYGate, RZGate, CRZGate, SGate, SdgGate, CSwapGate, TGate, TdgGate, U1Gate, CU1Gate, U2Gate, U3Gate, CU3Gate, XGate, CXGate, ECRGate, CCXGate, YGate, CYGate, ZGate, CZGate, RYYGate, PhaseGate, CPhaseGate, UGate, CUGate, SXGate, SXdgGate, CSXGate, RVGate, XXMinusYYGate, ) from qiskit.circuit.library.standard_gates.equivalence_library import ( StandardEquivalenceLibrary as std_eqlib, ) from .gate_utils import _get_free_params class TestGateDefinitions(QiskitTestCase): """Test the decomposition of a gate in terms of other gates yields the equivalent matrix as the hardcoded matrix definition up to a global phase.""" def test_ch_definition(self): # TODO: expand this to all gates """Test ch gate matrix and definition.""" circ = QuantumCircuit(2) circ.ch(0, 1) decomposed_circ = circ.decompose() self.assertTrue(Operator(circ).equiv(Operator(decomposed_circ))) def test_ccx_definition(self): """Test ccx gate matrix and definition.""" circ = QuantumCircuit(3) circ.ccx(0, 1, 2) decomposed_circ = circ.decompose() self.assertTrue(Operator(circ).equiv(Operator(decomposed_circ))) def test_crz_definition(self): """Test crz gate matrix and definition.""" circ = QuantumCircuit(2) circ.crz(1, 0, 1) decomposed_circ = circ.decompose() self.assertTrue(Operator(circ).equiv(Operator(decomposed_circ))) def test_cry_definition(self): """Test cry gate matrix and definition.""" circ = QuantumCircuit(2) circ.cry(1, 0, 1) decomposed_circ = circ.decompose() self.assertTrue(Operator(circ).equiv(Operator(decomposed_circ))) def test_crx_definition(self): """Test crx gate matrix and definition.""" circ = QuantumCircuit(2) circ.crx(1, 0, 1) decomposed_circ = circ.decompose() self.assertTrue(Operator(circ).equiv(Operator(decomposed_circ))) def test_cswap_definition(self): """Test cswap gate matrix and definition.""" circ = QuantumCircuit(3) circ.cswap(0, 1, 2) decomposed_circ = circ.decompose() self.assertTrue(Operator(circ).equiv(Operator(decomposed_circ))) def test_cu1_definition(self): """Test cu1 gate matrix and definition.""" circ = QuantumCircuit(2) circ.append(CU1Gate(1), [0, 1]) decomposed_circ = circ.decompose() self.assertTrue(Operator(circ).equiv(Operator(decomposed_circ))) def test_cu3_definition(self): """Test cu3 gate matrix and definition.""" circ = QuantumCircuit(2) circ.append(CU3Gate(1, 1, 1), [0, 1]) decomposed_circ = circ.decompose() self.assertTrue(Operator(circ).equiv(Operator(decomposed_circ))) def test_cx_definition(self): """Test cx gate matrix and definition.""" circ = QuantumCircuit(2) circ.cx(0, 1) decomposed_circ = circ.decompose() self.assertTrue(Operator(circ).equiv(Operator(decomposed_circ))) def test_ecr_definition(self): """Test ecr gate matrix and definition.""" circ = QuantumCircuit(2) circ.ecr(0, 1) decomposed_circ = circ.decompose() self.assertTrue(Operator(circ).equiv(Operator(decomposed_circ))) def test_rv_definition(self): """Test R(v) gate to_matrix and definition.""" qreg = QuantumRegister(1) circ = QuantumCircuit(qreg) vec = np.array([0.1, 0.2, 0.3], dtype=float) circ.rv(*vec, 0) decomposed_circ = circ.decompose() self.assertTrue(Operator(circ).equiv(Operator(decomposed_circ))) def test_rv_r_equiv(self): """Test R(v) gate is equivalent to R gate.""" theta = np.pi / 5 phi = np.pi / 3 rgate = RGate(theta, phi) axis = np.array([np.cos(phi), np.sin(phi), 0]) # RGate axis rotvec = theta * axis rv = RVGate(*rotvec) rg_matrix = rgate.to_matrix() rv_matrix = rv.to_matrix() np.testing.assert_array_max_ulp(rg_matrix.real, rv_matrix.real, 4) np.testing.assert_array_max_ulp(rg_matrix.imag, rv_matrix.imag, 4) def test_rv_zero(self): """Test R(v) gate with zero vector returns identity""" rv = RVGate(0, 0, 0) self.assertTrue(np.array_equal(rv.to_matrix(), np.array([[1, 0], [0, 1]]))) def test_xx_minus_yy_definition(self): """Test XX-YY gate decomposition.""" theta, beta = np.random.uniform(-10, 10, size=2) gate = XXMinusYYGate(theta, beta) circuit = QuantumCircuit(2) circuit.append(gate, [0, 1]) decomposed_circuit = circuit.decompose() self.assertTrue(len(decomposed_circuit) > len(circuit)) self.assertTrue(Operator(circuit).equiv(Operator(decomposed_circuit), atol=1e-7)) @ddt class TestStandardGates(QiskitTestCase): """Standard Extension Test.""" @unpack @data( *inspect.getmembers( standard_gates, predicate=lambda value: (inspect.isclass(value) and issubclass(value, Gate)), ) ) def test_definition_parameters(self, class_name, gate_class): """Verify definitions from standard library include correct parameters.""" free_params = _get_free_params(gate_class) n_params = len(free_params) param_vector = ParameterVector("th", n_params) if class_name in ("MCPhaseGate", "MCU1Gate"): param_vector = param_vector[:-1] gate = gate_class(*param_vector, num_ctrl_qubits=2) elif class_name in ("MCXGate", "MCXGrayCode", "MCXRecursive", "MCXVChain"): num_ctrl_qubits = 2 param_vector = param_vector[:-1] gate = gate_class(num_ctrl_qubits, *param_vector) elif class_name == "MSGate": num_qubits = 2 param_vector = param_vector[:-1] gate = gate_class(num_qubits, *param_vector) else: gate = gate_class(*param_vector) if gate.definition is not None: self.assertEqual(gate.definition.parameters, set(param_vector)) @unpack @data( *inspect.getmembers( standard_gates, predicate=lambda value: (inspect.isclass(value) and issubclass(value, Gate)), ) ) def test_inverse(self, class_name, gate_class): """Verify self-inverse pair yield identity for all standard gates.""" free_params = _get_free_params(gate_class) n_params = len(free_params) float_vector = [0.1 + 0.1 * i for i in range(n_params)] if class_name in ("MCPhaseGate", "MCU1Gate"): float_vector = float_vector[:-1] gate = gate_class(*float_vector, num_ctrl_qubits=2) elif class_name in ("MCXGate", "MCXGrayCode", "MCXRecursive", "MCXVChain"): num_ctrl_qubits = 3 float_vector = float_vector[:-1] gate = gate_class(num_ctrl_qubits, *float_vector) elif class_name == "PauliGate": pauli_string = "IXYZ" gate = gate_class(pauli_string) else: gate = gate_class(*float_vector) from qiskit.quantum_info.operators.predicates import is_identity_matrix self.assertTrue(is_identity_matrix(Operator(gate).dot(gate.inverse()).data)) if gate.definition is not None: self.assertTrue(is_identity_matrix(Operator(gate).dot(gate.definition.inverse()).data)) self.assertTrue(is_identity_matrix(Operator(gate).dot(gate.inverse().definition).data)) @ddt class TestGateEquivalenceEqual(QiskitTestCase): """Test the decomposition of a gate in terms of other gates yields the same matrix as the hardcoded matrix definition.""" class_list = Gate.__subclasses__() + ControlledGate.__subclasses__() exclude = { "ControlledGate", "DiagonalGate", "UCGate", "MCGupDiag", "MCU1Gate", "UnitaryGate", "HamiltonianGate", "MCPhaseGate", "UCPauliRotGate", "SingleQubitUnitary", "MCXGate", "VariadicZeroParamGate", "ClassicalFunction", "ClassicalElement", "StatePreparation", "LinearFunction", "PermutationGate", "Commuting2qBlock", "PauliEvolutionGate", "_U0Gate", "_DefinedGate", } # Amazingly, Python's scoping rules for class bodies means that this is the closest we can get # to a "natural" comprehension or functional iterable definition: # https://docs.python.org/3/reference/executionmodel.html#resolution-of-names @idata(filter(lambda x, exclude=exclude: x.__name__ not in exclude, class_list)) def test_equivalence_phase(self, gate_class): """Test that the equivalent circuits from the equivalency_library have equal matrix representations""" n_params = len(_get_free_params(gate_class)) params = [0.1 * i for i in range(1, n_params + 1)] if gate_class.__name__ == "RXXGate": params = [np.pi / 2] if gate_class.__name__ in ["MSGate"]: params[0] = 2 if gate_class.__name__ in ["PauliGate"]: params = ["IXYZ"] if gate_class.__name__ in ["BooleanExpression"]: params = ["x | y"] gate = gate_class(*params) equiv_lib_list = std_eqlib.get_entry(gate) for ieq, equivalency in enumerate(equiv_lib_list): with self.subTest(msg=gate.name + "_" + str(ieq)): op1 = Operator(gate) op2 = Operator(equivalency) self.assertEqual(op1, op2) @ddt class TestStandardEquivalenceLibrary(QiskitTestCase): """Standard Extension Test.""" @data( HGate, CHGate, IGate, RGate, RXGate, CRXGate, RYGate, CRYGate, RZGate, CRZGate, SGate, SdgGate, CSwapGate, TGate, TdgGate, U1Gate, CU1Gate, U2Gate, U3Gate, CU3Gate, XGate, CXGate, ECRGate, CCXGate, YGate, CYGate, ZGate, CZGate, RYYGate, PhaseGate, CPhaseGate, UGate, CUGate, SXGate, SXdgGate, CSXGate, ) def test_definition_parameters(self, gate_class): """Verify decompositions from standard equivalence library match definitions.""" n_params = len(_get_free_params(gate_class)) param_vector = ParameterVector("th", n_params) float_vector = [0.1 * i for i in range(n_params)] param_gate = gate_class(*param_vector) float_gate = gate_class(*float_vector) param_entry = std_eqlib.get_entry(param_gate) float_entry = std_eqlib.get_entry(float_gate) if not param_gate.definition or not param_gate.definition.data: return self.assertGreaterEqual(len(param_entry), 1) self.assertGreaterEqual(len(float_entry), 1) param_qc = QuantumCircuit(param_gate.num_qubits) float_qc = QuantumCircuit(float_gate.num_qubits) param_qc.append(param_gate, param_qc.qregs[0]) float_qc.append(float_gate, float_qc.qregs[0]) self.assertTrue(any(equiv == param_qc.decompose() for equiv in param_entry)) self.assertTrue(any(equiv == float_qc.decompose() for equiv in float_entry))
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """HamiltonianGate tests""" import numpy as np from numpy.testing import assert_allclose import qiskit from qiskit.extensions.hamiltonian_gate import HamiltonianGate, UnitaryGate from qiskit.extensions.exceptions import ExtensionError from qiskit.test import QiskitTestCase from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.circuit import Parameter from qiskit.quantum_info import Operator from qiskit.converters import circuit_to_dag, dag_to_circuit class TestHamiltonianGate(QiskitTestCase): """Tests for the HamiltonianGate class.""" def test_set_matrix(self): """Test instantiation""" hamiltonian = HamiltonianGate([[0, 1], [1, 0]], 1) self.assertEqual(hamiltonian.num_qubits, 1) def test_set_matrix_raises(self): """test non-unitary""" with self.assertRaises(ExtensionError): HamiltonianGate([[1, 0], [1, 1]], 1) def test_complex_time_raises(self): """test non-unitary""" with self.assertRaises(ExtensionError): HamiltonianGate([[1, 0], [1, 1]], 1j) def test_conjugate(self): """test conjugate""" ham = HamiltonianGate([[0, 1j], [-1j, 2]], np.pi / 4) np.testing.assert_array_almost_equal(ham.conjugate().to_matrix(), np.conj(ham.to_matrix())) def test_transpose(self): """test transpose""" ham = HamiltonianGate([[15, 1j], [-1j, -2]], np.pi / 7) np.testing.assert_array_almost_equal( ham.transpose().to_matrix(), np.transpose(ham.to_matrix()) ) def test_adjoint(self): """test adjoint operation""" ham = HamiltonianGate([[3, 4j], [-4j, -0.2]], np.pi * 0.143) np.testing.assert_array_almost_equal( ham.adjoint().to_matrix(), np.transpose(np.conj(ham.to_matrix())) ) class TestHamiltonianCircuit(QiskitTestCase): """Hamiltonian gate circuit tests.""" def test_1q_hamiltonian(self): """test 1 qubit hamiltonian""" qr = QuantumRegister(1, "q0") cr = ClassicalRegister(1, "c0") qc = QuantumCircuit(qr, cr) matrix = np.zeros((2, 2)) qc.x(qr[0]) theta = Parameter("theta") qc.append(HamiltonianGate(matrix, theta), [qr[0]]) qc = qc.bind_parameters({theta: 1}) # test of text drawer self.log.info(qc) dag = circuit_to_dag(qc) dag_nodes = dag.named_nodes("hamiltonian") self.assertTrue(len(dag_nodes) == 1) dnode = dag_nodes[0] self.assertIsInstance(dnode.op, HamiltonianGate) self.assertEqual(dnode.qargs, tuple(qc.qubits)) assert_allclose(dnode.op.to_matrix(), np.eye(2)) def test_error_and_deprecation_warning_on_qasm(self): """test that an error is thrown if the method `qasm` is called.""" matrix = np.zeros((2, 2)) hamiltonian_gate = HamiltonianGate(data=matrix, time=1) with self.assertRaises(ExtensionError): with self.assertWarns(DeprecationWarning): hamiltonian_gate.qasm() def test_2q_hamiltonian(self): """test 2 qubit hamiltonian""" qr = QuantumRegister(2) cr = ClassicalRegister(2) qc = QuantumCircuit(qr, cr) matrix = Operator.from_label("XY") qc.x(qr[0]) theta = Parameter("theta") uni2q = HamiltonianGate(matrix, theta) qc.append(uni2q, [qr[0], qr[1]]) qc2 = qc.bind_parameters({theta: -np.pi / 2}) dag = circuit_to_dag(qc2) nodes = dag.two_qubit_ops() self.assertEqual(len(nodes), 1) dnode = nodes[0] self.assertIsInstance(dnode.op, HamiltonianGate) self.assertEqual(dnode.qargs, (qr[0], qr[1])) # Equality based on Pauli exponential identity np.testing.assert_array_almost_equal(dnode.op.to_matrix(), 1j * matrix.data) qc3 = dag_to_circuit(dag) self.assertEqual(qc2, qc3) def test_3q_hamiltonian(self): """test 3 qubit hamiltonian on non-consecutive bits""" qr = QuantumRegister(4) qc = QuantumCircuit(qr) qc.x(qr[0]) matrix = Operator.from_label("XZY") theta = Parameter("theta") uni3q = HamiltonianGate(matrix, theta) qc.append(uni3q, [qr[0], qr[1], qr[3]]) qc.cx(qr[3], qr[2]) # test of text drawer self.log.info(qc) qc = qc.bind_parameters({theta: -np.pi / 2}) dag = circuit_to_dag(qc) nodes = dag.multi_qubit_ops() self.assertEqual(len(nodes), 1) dnode = nodes[0] self.assertIsInstance(dnode.op, HamiltonianGate) self.assertEqual(dnode.qargs, (qr[0], qr[1], qr[3])) np.testing.assert_almost_equal(dnode.op.to_matrix(), 1j * matrix.data) def test_qobj_with_hamiltonian(self): """test qobj output with hamiltonian""" qr = QuantumRegister(4) qc = QuantumCircuit(qr) qc.rx(np.pi / 4, qr[0]) matrix = Operator.from_label("XIZ") theta = Parameter("theta") uni = HamiltonianGate(matrix, theta, label="XIZ") qc.append(uni, [qr[0], qr[1], qr[3]]) qc.cx(qr[3], qr[2]) qc = qc.bind_parameters({theta: np.pi / 2}) qobj = qiskit.compiler.assemble(qc) instr = qobj.experiments[0].instructions[1] self.assertEqual(instr.name, "hamiltonian") # Also test label self.assertEqual(instr.label, "XIZ") np.testing.assert_array_almost_equal( np.array(instr.params[0]).astype(np.complex64), matrix.data ) def test_decomposes_into_correct_unitary(self): """test 2 qubit hamiltonian""" qc = QuantumCircuit(2) matrix = Operator.from_label("XY") theta = Parameter("theta") uni2q = HamiltonianGate(matrix, theta) qc.append(uni2q, [0, 1]) qc = qc.bind_parameters({theta: -np.pi / 2}).decompose() decomposed_ham = qc.data[0].operation self.assertEqual(decomposed_ham, UnitaryGate(Operator.from_label("XY")))
https://github.com/swe-train/qiskit__qiskit
swe-train
# 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. """Non-string identifiers for circuit and record identifiers test""" import unittest from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister from qiskit.circuit.exceptions import CircuitError from qiskit.test import QiskitTestCase class TestAnonymousIds(QiskitTestCase): """Test the anonymous use of registers.""" def test_create_anonymous_classical_register(self): """ClassicalRegister with no name.""" cr = ClassicalRegister(size=3) self.assertIsInstance(cr, ClassicalRegister) def test_create_anonymous_quantum_register(self): """QuantumRegister with no name.""" qr = QuantumRegister(size=3) self.assertIsInstance(qr, QuantumRegister) def test_create_anonymous_classical_registers(self): """Several ClassicalRegister with no name.""" cr1 = ClassicalRegister(size=3) cr2 = ClassicalRegister(size=3) self.assertNotEqual(cr1.name, cr2.name) def test_create_anonymous_quantum_registers(self): """Several QuantumRegister with no name.""" qr1 = QuantumRegister(size=3) qr2 = QuantumRegister(size=3) self.assertNotEqual(qr1.name, qr2.name) def test_create_anonymous_mixed_registers(self): """Several Registers with no name.""" cr0 = ClassicalRegister(size=3) qr0 = QuantumRegister(size=3) # Get the current index count of the registers cr_index = int(cr0.name[1:]) qr_index = int(qr0.name[1:]) cr1 = ClassicalRegister(size=3) _ = QuantumRegister(size=3) qr2 = QuantumRegister(size=3) # Check that the counters for each kind are incremented separately. cr_current = int(cr1.name[1:]) qr_current = int(qr2.name[1:]) self.assertEqual(cr_current, cr_index + 1) self.assertEqual(qr_current, qr_index + 2) def test_create_circuit_noname(self): """Create_circuit with no name.""" qr = QuantumRegister(size=3) cr = ClassicalRegister(size=3) qc = QuantumCircuit(qr, cr) self.assertIsInstance(qc, QuantumCircuit) class TestInvalidIds(QiskitTestCase): """Circuits and records with invalid IDs""" def test_invalid_type_circuit_name(self): """QuantumCircuit() with invalid type name.""" qr = QuantumRegister(size=3) cr = ClassicalRegister(size=3) self.assertRaises(CircuitError, QuantumCircuit, qr, cr, name=1) if __name__ == "__main__": unittest.main(verbosity=2)
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Initialize test. """ import math import unittest import numpy as np from ddt import ddt, data from qiskit import QuantumCircuit from qiskit import QuantumRegister from qiskit import ClassicalRegister from qiskit import transpile from qiskit import execute, assemble, BasicAer from qiskit.quantum_info import state_fidelity, Statevector, Operator from qiskit.exceptions import QiskitError from qiskit.test import QiskitTestCase from qiskit.extensions.quantum_initializer import Initialize @ddt class TestInitialize(QiskitTestCase): """Qiskit Initialize tests.""" _desired_fidelity = 0.99 def test_uniform_superposition(self): """Initialize a uniform superposition on 2 qubits.""" desired_vector = [0.5, 0.5, 0.5, 0.5] qr = QuantumRegister(2, "qr") qc = QuantumCircuit(qr) qc.initialize(desired_vector, [qr[0], qr[1]]) job = execute(qc, BasicAer.get_backend("statevector_simulator")) result = job.result() statevector = result.get_statevector() fidelity = state_fidelity(statevector, desired_vector) self.assertGreater( fidelity, self._desired_fidelity, f"Initializer has low fidelity {fidelity:.2g}.", ) def test_deterministic_state(self): """Initialize a computational-basis state |01> on 2 qubits.""" desired_vector = [0, 1, 0, 0] qr = QuantumRegister(2, "qr") qc = QuantumCircuit(qr) qc.initialize(desired_vector, [qr[0], qr[1]]) job = execute(qc, BasicAer.get_backend("statevector_simulator")) result = job.result() statevector = result.get_statevector() fidelity = state_fidelity(statevector, desired_vector) self.assertGreater( fidelity, self._desired_fidelity, f"Initializer has low fidelity {fidelity:.2g}.", ) def test_statevector(self): """Initialize gates from a statevector.""" # ref: https://github.com/Qiskit/qiskit-terra/issues/5134 (footnote) desired_vector = [0, 0, 0, 1] qc = QuantumCircuit(2) statevector = Statevector.from_label("11") qc.initialize(statevector, [0, 1]) self.assertEqual(qc.data[0].operation.params, desired_vector) def test_bell_state(self): """Initialize a Bell state on 2 qubits.""" desired_vector = [1 / math.sqrt(2), 0, 0, 1 / math.sqrt(2)] qr = QuantumRegister(2, "qr") qc = QuantumCircuit(qr) qc.initialize(desired_vector, [qr[0], qr[1]]) job = execute(qc, BasicAer.get_backend("statevector_simulator")) result = job.result() statevector = result.get_statevector() fidelity = state_fidelity(statevector, desired_vector) self.assertGreater( fidelity, self._desired_fidelity, f"Initializer has low fidelity {fidelity:.2g}.", ) def test_ghz_state(self): """Initialize a GHZ state on 3 qubits.""" desired_vector = [1 / math.sqrt(2), 0, 0, 0, 0, 0, 0, 1 / math.sqrt(2)] qr = QuantumRegister(3, "qr") qc = QuantumCircuit(qr) qc.initialize(desired_vector, [qr[0], qr[1], qr[2]]) job = execute(qc, BasicAer.get_backend("statevector_simulator")) result = job.result() statevector = result.get_statevector() fidelity = state_fidelity(statevector, desired_vector) self.assertGreater( fidelity, self._desired_fidelity, f"Initializer has low fidelity {fidelity:.2g}.", ) def test_initialize_register(self): """Initialize one register out of two.""" desired_vector = [1 / math.sqrt(2), 0, 0, 1 / math.sqrt(2)] qr = QuantumRegister(2, "qr") qr2 = QuantumRegister(2, "qr2") qc = QuantumCircuit(qr, qr2) qc.initialize(desired_vector, qr) job = execute(qc, BasicAer.get_backend("statevector_simulator")) result = job.result() statevector = result.get_statevector() fidelity = state_fidelity(statevector, np.kron([1, 0, 0, 0], desired_vector)) self.assertGreater( fidelity, self._desired_fidelity, f"Initializer has low fidelity {fidelity:.2g}.", ) def test_initialize_one_by_one(self): """Initializing qubits individually into product state same as initializing the pair.""" qubit_0_state = [1, 0] qubit_1_state = [1 / math.sqrt(2), 1 / math.sqrt(2)] qr = QuantumRegister(2, "qr") qc_a = QuantumCircuit(qr) qc_a.initialize(np.kron(qubit_1_state, qubit_0_state), qr) qc_b = QuantumCircuit(qr) qc_b.initialize(qubit_0_state, [qr[0]]) qc_b.initialize(qubit_1_state, [qr[1]]) job = execute([qc_a, qc_b], BasicAer.get_backend("statevector_simulator")) result = job.result() statevector_a = result.get_statevector(0) statevector_b = result.get_statevector(1) fidelity = state_fidelity(statevector_a, statevector_b) self.assertGreater( fidelity, self._desired_fidelity, f"Initializer has low fidelity {fidelity:.2g}.", ) def test_single_qubit(self): """Initialize a single qubit to a weighted superposition state.""" desired_vector = [1 / math.sqrt(3), math.sqrt(2) / math.sqrt(3)] qr = QuantumRegister(1, "qr") qc = QuantumCircuit(qr) qc.initialize(desired_vector, [qr[0]]) job = execute(qc, BasicAer.get_backend("statevector_simulator")) result = job.result() statevector = result.get_statevector() fidelity = state_fidelity(statevector, desired_vector) self.assertGreater( fidelity, self._desired_fidelity, f"Initializer has low fidelity {fidelity:.2g}.", ) def test_random_3qubit(self): """Initialize to a non-trivial 3-qubit state.""" desired_vector = [ 1 / math.sqrt(16) * complex(0, 1), 1 / math.sqrt(8) * complex(1, 0), 1 / math.sqrt(16) * complex(1, 1), 0, 0, 1 / math.sqrt(8) * complex(1, 2), 1 / math.sqrt(16) * complex(1, 0), 0, ] qr = QuantumRegister(3, "qr") qc = QuantumCircuit(qr) qc.initialize(desired_vector, [qr[0], qr[1], qr[2]]) job = execute(qc, BasicAer.get_backend("statevector_simulator")) result = job.result() statevector = result.get_statevector() fidelity = state_fidelity(statevector, desired_vector) self.assertGreater( fidelity, self._desired_fidelity, f"Initializer has low fidelity {fidelity:.2g}.", ) def test_random_4qubit(self): """Initialize to a non-trivial 4-qubit state.""" desired_vector = [ 1 / math.sqrt(4) * complex(0, 1), 1 / math.sqrt(8) * complex(1, 0), 0, 0, 0, 0, 0, 0, 1 / math.sqrt(8) * complex(1, 0), 1 / math.sqrt(8) * complex(0, 1), 0, 0, 0, 0, 1 / math.sqrt(4) * complex(1, 0), 1 / math.sqrt(8) * complex(1, 0), ] qr = QuantumRegister(4, "qr") qc = QuantumCircuit(qr) qc.initialize(desired_vector, [qr[0], qr[1], qr[2], qr[3]]) job = execute(qc, BasicAer.get_backend("statevector_simulator")) result = job.result() statevector = result.get_statevector() fidelity = state_fidelity(statevector, desired_vector) self.assertGreater( fidelity, self._desired_fidelity, f"Initializer has low fidelity {fidelity:.2g}.", ) def test_malformed_amplitudes(self): """Initializing to a vector with 3 amplitudes fails.""" desired_vector = [1 / math.sqrt(3), math.sqrt(2) / math.sqrt(3), 0] qr = QuantumRegister(2, "qr") qc = QuantumCircuit(qr) self.assertRaises(QiskitError, qc.initialize, desired_vector, [qr[0], qr[1]]) def test_non_unit_probability(self): """Initializing to a vector with probabilities not summing to 1 fails.""" desired_vector = [1, 1] qr = QuantumRegister(2, "qr") qc = QuantumCircuit(qr) self.assertRaises(QiskitError, qc.initialize, desired_vector, [qr[0], qr[1]]) def test_normalize(self): """Test initializing with a non-normalized vector is normalized, if specified.""" desired_vector = [1, 1] normalized = np.asarray(desired_vector) / np.linalg.norm(desired_vector) qc = QuantumCircuit(1) qc.initialize(desired_vector, [0], normalize=True) op = qc.data[0].operation self.assertAlmostEqual(np.linalg.norm(op.params), 1) self.assertEqual(Statevector(qc), Statevector(normalized)) def test_wrong_vector_size(self): """Initializing to a vector with a size different to the qubit parameter length. See https://github.com/Qiskit/qiskit-terra/issues/2372""" qr = QuantumRegister(2) random_state = [ 1 / math.sqrt(4) * complex(0, 1), 1 / math.sqrt(8) * complex(1, 0), 0, 1 / math.sqrt(8) * complex(1, 0), 1 / math.sqrt(8) * complex(0, 1), 0, 1 / math.sqrt(4) * complex(1, 0), 1 / math.sqrt(8) * complex(1, 0), ] qc = QuantumCircuit(qr) self.assertRaises(QiskitError, qc.initialize, random_state, qr[0:2]) def test_initialize_middle_circuit(self): """Reset + initialize gives the correct statevector.""" desired_vector = [0.5, 0.5, 0.5, 0.5] qr = QuantumRegister(2, "qr") cr = ClassicalRegister(2, "cr") qc = QuantumCircuit(qr, cr) qc.h(qr[0]) qc.cx(qr[0], qr[1]) qc.reset(qr[0]) qc.reset(qr[1]) qc.initialize(desired_vector, [qr[0], qr[1]]) qc.measure(qr, cr) # statevector simulator does not support reset shots = 2000 threshold = 0.005 * shots job = execute(qc, BasicAer.get_backend("qasm_simulator"), shots=shots, seed_simulator=42) result = job.result() counts = result.get_counts() target = {"00": shots / 4, "01": shots / 4, "10": shots / 4, "11": shots / 4} self.assertDictAlmostEqual(counts, target, threshold) def test_math_amplitudes(self): """Initialize to amplitudes given by math expressions""" desired_vector = [ 0, math.cos(math.pi / 3) * complex(0, 1) / math.sqrt(4), math.sin(math.pi / 3) / math.sqrt(4), 0, 0, 0, 0, 0, 1 / math.sqrt(8) * complex(1, 0), 1 / math.sqrt(8) * complex(0, 1), 0, 0, 0, 0, 1 / math.sqrt(4), 1 / math.sqrt(4) * complex(0, 1), ] qr = QuantumRegister(4, "qr") qc = QuantumCircuit(qr) qc.initialize(desired_vector, [qr[0], qr[1], qr[2], qr[3]]) job = execute(qc, BasicAer.get_backend("statevector_simulator")) result = job.result() statevector = result.get_statevector() fidelity = state_fidelity(statevector, desired_vector) self.assertGreater( fidelity, self._desired_fidelity, f"Initializer has low fidelity {fidelity:.2g}.", ) def test_combiner(self): """Combining two circuits containing initialize.""" desired_vector_1 = [1.0 / math.sqrt(2), 1.0 / math.sqrt(2)] desired_vector_2 = [1.0 / math.sqrt(2), -1.0 / math.sqrt(2)] qr = QuantumRegister(1, "qr") cr = ClassicalRegister(1, "cr") qc1 = QuantumCircuit(qr, cr) qc1.initialize(desired_vector_1, [qr[0]]) qc2 = QuantumCircuit(qr, cr) qc2.initialize(desired_vector_2, [qr[0]]) job = execute(qc1.compose(qc2), BasicAer.get_backend("statevector_simulator")) result = job.result() quantum_state = result.get_statevector() fidelity = state_fidelity(quantum_state, desired_vector_2) self.assertGreater( fidelity, self._desired_fidelity, f"Initializer has low fidelity {fidelity:.2g}.", ) def test_equivalence(self): """Test two similar initialize instructions evaluate to equal.""" desired_vector = [0.5, 0.5, 0.5, 0.5] qr = QuantumRegister(2, "qr") qc1 = QuantumCircuit(qr, name="circuit") qc1.initialize(desired_vector, [qr[0], qr[1]]) qc2 = QuantumCircuit(qr, name="circuit") qc2.initialize(desired_vector, [qr[0], qr[1]]) self.assertEqual(qc1, qc2) def test_max_number_cnots(self): """ Check if the number of cnots <= 2^(n+1) - 2n (arXiv:quant-ph/0406176) """ num_qubits = 4 _optimization_level = 0 vector = np.array( [ 0.1314346 + 0.0j, 0.32078572 - 0.01542775j, 0.13146466 + 0.0945312j, 0.21090852 + 0.07935982j, 0.1700122 - 0.07905648j, 0.15570757 - 0.12309154j, 0.18039667 + 0.04904504j, 0.22227187 - 0.05055569j, 0.23573255 - 0.09894111j, 0.27307292 - 0.10372994j, 0.24162792 + 0.1090791j, 0.3115577 + 0.1211683j, 0.1851788 + 0.08679141j, 0.36226463 - 0.09940202j, 0.13863395 + 0.10558225j, 0.30767986 + 0.02073838j, ] ) vector = vector / np.linalg.norm(vector) qr = QuantumRegister(num_qubits, "qr") circuit = QuantumCircuit(qr) circuit.initialize(vector, qr) b = transpile( circuit, basis_gates=["u1", "u2", "u3", "cx"], optimization_level=_optimization_level, seed_transpiler=42, ) number_cnots = b.count_ops()["cx"] max_cnots = 2 ** (num_qubits + 1) - 2 * num_qubits self.assertLessEqual(number_cnots, max_cnots) def test_from_labels(self): """Initialize from labels.""" desired_sv = Statevector.from_label("01+-lr") qc = QuantumCircuit(6) qc.initialize("01+-lr", range(6)) actual_sv = Statevector.from_instruction(qc) self.assertTrue(desired_sv == actual_sv) def test_from_int(self): """Initialize from int.""" desired_sv = Statevector.from_label("110101") qc = QuantumCircuit(6) qc.initialize(53, range(6)) actual_sv = Statevector.from_instruction(qc) self.assertTrue(desired_sv == actual_sv) def _remove_resets(self, circ): circ.data = [instr for instr in circ.data if instr.operation.name != "reset"] def test_global_phase_random(self): """Test global phase preservation with random state vectors""" from qiskit.quantum_info.random import random_statevector repeats = 5 for n_qubits in [1, 2, 4]: for irep in range(repeats): with self.subTest(i=f"{n_qubits}_{irep}"): dim = 2**n_qubits qr = QuantumRegister(n_qubits) initializer = QuantumCircuit(qr) target = random_statevector(dim) initializer.initialize(target, qr) uninit = initializer.data[0].operation.definition self._remove_resets(uninit) evolve = Statevector(uninit) self.assertEqual(target, evolve) def test_global_phase_1q(self): """Test global phase preservation with some simple 1q statevectors""" target_list = [ Statevector([1j, 0]), Statevector([0, 1j]), Statevector([1j / np.sqrt(2), 1j / np.sqrt(2)]), ] n_qubits = 1 dim = 2**n_qubits qr = QuantumRegister(n_qubits) for target in target_list: with self.subTest(i=target): initializer = QuantumCircuit(qr) initializer.initialize(target, qr) # need to get rid of the resets in order to use the Operator class disentangler = Operator(initializer.data[0].operation.definition.data[1].operation) zero = Statevector.from_int(0, dim) actual = zero & disentangler self.assertEqual(target, actual) @data(2, "11", [1 / math.sqrt(2), 0, 0, 1 / math.sqrt(2)]) def test_decompose_contains_stateprep(self, state): """Test initialize decomposes to a StatePreparation and reset""" qc = QuantumCircuit(2) qc.initialize(state) decom_circ = qc.decompose() self.assertEqual(decom_circ.data[0].operation.name, "reset") self.assertEqual(decom_circ.data[1].operation.name, "reset") self.assertEqual(decom_circ.data[2].operation.name, "state_preparation") def test_mutating_params(self): """Test mutating Initialize params correctly updates StatePreparation params""" init = Initialize("11") init.params = "00" qr = QuantumRegister(2) qc = QuantumCircuit(qr) qc.append(init, qr) decom_circ = qc.decompose() self.assertEqual(decom_circ.data[2].operation.name, "state_preparation") self.assertEqual(decom_circ.data[2].operation.params, ["0", "0"]) class TestInstructionParam(QiskitTestCase): """Test conversion of numpy type parameters.""" def test_diag(self): """Verify diagonal gate converts numpy.complex to complex.""" # ref: https://github.com/Qiskit/qiskit-aer/issues/696 diag = np.array([1 + 0j, 1 + 0j]) qc = QuantumCircuit(1) qc.diagonal(list(diag), [0]) params = qc.data[0].operation.params self.assertTrue( all(isinstance(p, complex) and not isinstance(p, np.number) for p in params) ) qobj = assemble(qc) params = qobj.experiments[0].instructions[0].params self.assertTrue( all(isinstance(p, complex) and not isinstance(p, np.number) for p in params) ) def test_init(self): """Verify initialize gate converts numpy.complex to complex.""" # ref: https://github.com/Qiskit/qiskit-terra/issues/4151 qc = QuantumCircuit(1) vec = np.array([0, 0 + 1j]) qc.initialize(vec, 0) params = qc.data[0].operation.params self.assertTrue( all(isinstance(p, complex) and not isinstance(p, np.number) for p in params) ) qobj = assemble(qc) params = qobj.experiments[0].instructions[0].params self.assertTrue( all(isinstance(p, complex) and not isinstance(p, np.number) for p in params) ) if __name__ == "__main__": unittest.main()
https://github.com/swe-train/qiskit__qiskit
swe-train
# 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. """Test Qiskit's repeat instruction operation.""" import unittest from numpy import pi from qiskit.transpiler import PassManager from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister from qiskit.test import QiskitTestCase from qiskit.extensions import UnitaryGate from qiskit.circuit.library import SGate, U3Gate, CXGate from qiskit.circuit import Instruction, Measure, Gate from qiskit.transpiler.passes import Unroller from qiskit.circuit.exceptions import CircuitError class TestRepeatInt1Q(QiskitTestCase): """Test gate_q1.repeat() with integer""" def test_standard_1Q_two(self): """Test standard gate.repeat(2) method.""" qr = QuantumRegister(1, "qr") expected_circ = QuantumCircuit(qr) expected_circ.append(SGate(), [qr[0]]) expected_circ.append(SGate(), [qr[0]]) expected = expected_circ.to_instruction() result = SGate().repeat(2) self.assertEqual(result.name, "s*2") self.assertEqual(result.definition, expected.definition) self.assertIsInstance(result, Gate) def test_standard_1Q_one(self): """Test standard gate.repeat(1) method.""" qr = QuantumRegister(1, "qr") expected_circ = QuantumCircuit(qr) expected_circ.append(SGate(), [qr[0]]) expected = expected_circ.to_instruction() result = SGate().repeat(1) self.assertEqual(result.name, "s*1") self.assertEqual(result.definition, expected.definition) self.assertIsInstance(result, Gate) class TestRepeatInt2Q(QiskitTestCase): """Test gate_q2.repeat() with integer""" def test_standard_2Q_two(self): """Test standard 2Q gate.repeat(2) method.""" qr = QuantumRegister(2, "qr") expected_circ = QuantumCircuit(qr) expected_circ.append(CXGate(), [qr[0], qr[1]]) expected_circ.append(CXGate(), [qr[0], qr[1]]) expected = expected_circ.to_instruction() result = CXGate().repeat(2) self.assertEqual(result.name, "cx*2") self.assertEqual(result.definition, expected.definition) self.assertIsInstance(result, Gate) def test_standard_2Q_one(self): """Test standard 2Q gate.repeat(1) method.""" qr = QuantumRegister(2, "qr") expected_circ = QuantumCircuit(qr) expected_circ.append(CXGate(), [qr[0], qr[1]]) expected = expected_circ.to_instruction() result = CXGate().repeat(1) self.assertEqual(result.name, "cx*1") self.assertEqual(result.definition, expected.definition) self.assertIsInstance(result, Gate) class TestRepeatIntMeasure(QiskitTestCase): """Test Measure.repeat() with integer""" def test_measure_two(self): """Test Measure.repeat(2) method.""" qr = QuantumRegister(1, "qr") cr = ClassicalRegister(1, "cr") expected_circ = QuantumCircuit(qr, cr) expected_circ.append(Measure(), [qr[0]], [cr[0]]) expected_circ.append(Measure(), [qr[0]], [cr[0]]) expected = expected_circ.to_instruction() result = Measure().repeat(2) self.assertEqual(result.name, "measure*2") self.assertEqual(result.definition, expected.definition) self.assertIsInstance(result, Instruction) self.assertNotIsInstance(result, Gate) def test_measure_one(self): """Test Measure.repeat(1) method.""" qr = QuantumRegister(1, "qr") cr = ClassicalRegister(1, "cr") expected_circ = QuantumCircuit(qr, cr) expected_circ.append(Measure(), [qr[0]], [cr[0]]) expected = expected_circ.to_instruction() result = Measure().repeat(1) self.assertEqual(result.name, "measure*1") self.assertEqual(result.definition, expected.definition) self.assertIsInstance(result, Instruction) self.assertNotIsInstance(result, Gate) class TestRepeatUnroller(QiskitTestCase): """Test unrolling Gate.repeat""" def test_unroller_two(self): """Test unrolling gate.repeat(2).""" qr = QuantumRegister(1, "qr") circuit = QuantumCircuit(qr) circuit.append(SGate().repeat(2), [qr[0]]) result = PassManager(Unroller("u3")).run(circuit) expected = QuantumCircuit(qr) expected.append(U3Gate(0, 0, pi / 2), [qr[0]]) expected.append(U3Gate(0, 0, pi / 2), [qr[0]]) self.assertEqual(result, expected) def test_unroller_one(self): """Test unrolling gate.repeat(1).""" qr = QuantumRegister(1, "qr") circuit = QuantumCircuit(qr) circuit.append(SGate().repeat(1), [qr[0]]) result = PassManager(Unroller("u3")).run(circuit) expected = QuantumCircuit(qr) expected.append(U3Gate(0, 0, pi / 2), [qr[0]]) self.assertEqual(result, expected) class TestRepeatErrors(QiskitTestCase): """Test when Gate.repeat() should raise.""" def test_unitary_no_int(self): """Test UnitaryGate.repeat(2/3) method. Raises, since n is not int.""" with self.assertRaises(CircuitError) as context: _ = UnitaryGate([[0, 1j], [-1j, 0]]).repeat(2 / 3) self.assertIn("strictly positive integer", str(context.exception)) def test_standard_no_int(self): """Test standard Gate.repeat(2/3) method. Raises, since n is not int.""" with self.assertRaises(CircuitError) as context: _ = SGate().repeat(2 / 3) self.assertIn("strictly positive integer", str(context.exception)) def test_measure_zero(self): """Test Measure.repeat(0) method. Raises, since n<1""" with self.assertRaises(CircuitError) as context: _ = Measure().repeat(0) self.assertIn("strictly positive integer", str(context.exception)) def test_standard_1Q_zero(self): """Test standard 2Q gate.repeat(0) method. Raises, since n<1.""" with self.assertRaises(CircuitError) as context: _ = SGate().repeat(0) self.assertIn("strictly positive integer", str(context.exception)) def test_standard_1Q_minus_one(self): """Test standard 2Q gate.repeat(-1) method. Raises, since n<1.""" with self.assertRaises(CircuitError) as context: _ = SGate().repeat(-1) self.assertIn("strictly positive integer", str(context.exception)) def test_standard_2Q_minus_one(self): """Test standard 2Q gate.repeat(-1) method. Raises, since n<1.""" with self.assertRaises(CircuitError) as context: _ = CXGate().repeat(-1) self.assertIn("strictly positive integer", str(context.exception)) def test_measure_minus_one(self): """Test Measure.repeat(-1) method. Raises, since n<1""" with self.assertRaises(CircuitError) as context: _ = Measure().repeat(-1) self.assertIn("strictly positive integer", str(context.exception)) def test_standard_2Q_zero(self): """Test standard 2Q gate.repeat(0) method. Raises, since n<1.""" with self.assertRaises(CircuitError) as context: _ = CXGate().repeat(0) self.assertIn("strictly positive integer", str(context.exception)) if __name__ == "__main__": unittest.main()
https://github.com/swe-train/qiskit__qiskit
swe-train
# 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. """Isometry tests.""" import unittest import numpy as np from ddt import ddt, data from qiskit.quantum_info.random import random_unitary from qiskit import BasicAer from qiskit import QuantumCircuit from qiskit import QuantumRegister from qiskit import execute from qiskit.test import QiskitTestCase from qiskit.compiler import transpile from qiskit.quantum_info import Operator from qiskit.extensions.quantum_initializer.isometry import Isometry @ddt class TestIsometry(QiskitTestCase): """Qiskit isometry tests.""" @data( np.eye(2, 2), random_unitary(2, seed=868540).data, np.eye(4, 4), random_unitary(4, seed=16785).data[:, 0], np.eye(4, 4)[:, 0:2], random_unitary(4, seed=660477).data, np.eye(4, 4)[:, np.random.RandomState(seed=719010).permutation(4)][:, 0:2], np.eye(8, 8)[:, np.random.RandomState(seed=544326).permutation(8)], random_unitary(8, seed=247924).data[:, 0:4], random_unitary(8, seed=765720).data, random_unitary(16, seed=278663).data, random_unitary(16, seed=406498).data[:, 0:8], ) def test_isometry(self, iso): """Tests for the decomposition of isometries from m to n qubits""" if len(iso.shape) == 1: iso = iso.reshape((len(iso), 1)) num_q_output = int(np.log2(iso.shape[0])) num_q_input = int(np.log2(iso.shape[1])) q = QuantumRegister(num_q_output) qc = QuantumCircuit(q) qc.isometry(iso, q[:num_q_input], q[num_q_input:]) # Verify the circuit can be decomposed self.assertIsInstance(qc.decompose(), QuantumCircuit) # Decompose the gate qc = transpile(qc, basis_gates=["u1", "u3", "u2", "cx", "id"]) # Simulate the decomposed gate simulator = BasicAer.get_backend("unitary_simulator") result = execute(qc, simulator).result() unitary = result.get_unitary(qc) iso_from_circuit = unitary[::, 0 : 2**num_q_input] iso_desired = iso self.assertTrue(np.allclose(iso_from_circuit, iso_desired)) @data( np.eye(2, 2), random_unitary(2, seed=99506).data, np.eye(4, 4), random_unitary(4, seed=673459).data[:, 0], np.eye(4, 4)[:, 0:2], random_unitary(4, seed=124090).data, np.eye(4, 4)[:, np.random.RandomState(seed=889848).permutation(4)][:, 0:2], np.eye(8, 8)[:, np.random.RandomState(seed=94795).permutation(8)], random_unitary(8, seed=986292).data[:, 0:4], random_unitary(8, seed=632121).data, random_unitary(16, seed=623107).data, random_unitary(16, seed=889326).data[:, 0:8], ) def test_isometry_tolerance(self, iso): """Tests for the decomposition of isometries from m to n qubits with a custom tolerance""" if len(iso.shape) == 1: iso = iso.reshape((len(iso), 1)) num_q_output = int(np.log2(iso.shape[0])) num_q_input = int(np.log2(iso.shape[1])) q = QuantumRegister(num_q_output) qc = QuantumCircuit(q) # Compute isometry with custom tolerance qc.isometry(iso, q[:num_q_input], q[num_q_input:], epsilon=1e-3) # Verify the circuit can be decomposed self.assertIsInstance(qc.decompose(), QuantumCircuit) # Decompose the gate qc = transpile(qc, basis_gates=["u1", "u3", "u2", "cx", "id"]) # Simulate the decomposed gate simulator = BasicAer.get_backend("unitary_simulator") result = execute(qc, simulator).result() unitary = result.get_unitary(qc) iso_from_circuit = unitary[::, 0 : 2**num_q_input] self.assertTrue(np.allclose(iso_from_circuit, iso)) @data( np.eye(2, 2), random_unitary(2, seed=272225).data, np.eye(4, 4), random_unitary(4, seed=592640).data[:, 0], np.eye(4, 4)[:, 0:2], random_unitary(4, seed=714210).data, np.eye(4, 4)[:, np.random.RandomState(seed=719934).permutation(4)][:, 0:2], np.eye(8, 8)[:, np.random.RandomState(seed=284469).permutation(8)], random_unitary(8, seed=656745).data[:, 0:4], random_unitary(8, seed=583813).data, random_unitary(16, seed=101363).data, random_unitary(16, seed=583429).data[:, 0:8], ) def test_isometry_inverse(self, iso): """Tests for the inverse of isometries from m to n qubits""" if len(iso.shape) == 1: iso = iso.reshape((len(iso), 1)) num_q_output = int(np.log2(iso.shape[0])) q = QuantumRegister(num_q_output) qc = QuantumCircuit(q) qc.append(Isometry(iso, 0, 0), q) qc.append(Isometry(iso, 0, 0).inverse(), q) result = Operator(qc) np.testing.assert_array_almost_equal(result.data, np.identity(result.dim[0])) if __name__ == "__main__": unittest.main()
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test circuits with variable parameters.""" import unittest import cmath import math import copy import pickle from operator import add, mul, sub, truediv from test import combine import numpy from ddt import data, ddt, named_data import qiskit import qiskit.circuit.library as circlib from qiskit.circuit.library.standard_gates.rz import RZGate from qiskit import BasicAer, ClassicalRegister, QuantumCircuit, QuantumRegister from qiskit.circuit import Gate, Instruction, Parameter, ParameterExpression, ParameterVector from qiskit.circuit.parametertable import ParameterReferences, ParameterTable, ParameterView from qiskit.circuit.exceptions import CircuitError from qiskit.compiler import assemble, transpile from qiskit.execute_function import execute from qiskit import pulse from qiskit.quantum_info import Operator from qiskit.test import QiskitTestCase from qiskit.providers.fake_provider import FakeOurense from qiskit.tools import parallel_map def raise_if_parameter_table_invalid(circuit): """Validates the internal consistency of a ParameterTable and its containing QuantumCircuit. Intended for use in testing. Raises: CircuitError: if QuantumCircuit and ParameterTable are inconsistent. """ table = circuit._parameter_table # Assert parameters present in circuit match those in table. circuit_parameters = { parameter for instruction in circuit._data for param in instruction.operation.params for parameter in param.parameters if isinstance(param, ParameterExpression) } table_parameters = set(table._table.keys()) if circuit_parameters != table_parameters: raise CircuitError( "Circuit/ParameterTable Parameter mismatch. " "Circuit parameters: {}. " "Table parameters: {}.".format(circuit_parameters, table_parameters) ) # Assert parameter locations in table are present in circuit. circuit_instructions = [instr.operation for instr in circuit._data] for parameter, instr_list in table.items(): for instr, param_index in instr_list: if instr not in circuit_instructions: raise CircuitError(f"ParameterTable instruction not present in circuit: {instr}.") if not isinstance(instr.params[param_index], ParameterExpression): raise CircuitError( "ParameterTable instruction does not have a " "ParameterExpression at param_index {}: {}." "".format(param_index, instr) ) if parameter not in instr.params[param_index].parameters: raise CircuitError( "ParameterTable instruction parameters does " "not match ParameterTable key. Instruction " "parameters: {} ParameterTable key: {}." "".format(instr.params[param_index].parameters, parameter) ) # Assert circuit has no other parameter locations other than those in table. for instruction in circuit._data: for param_index, param in enumerate(instruction.operation.params): if isinstance(param, ParameterExpression): parameters = param.parameters for parameter in parameters: if (instruction.operation, param_index) not in table[parameter]: raise CircuitError( "Found parameterized instruction not " "present in table. Instruction: {} " "param_index: {}".format(instruction.operation, param_index) ) @ddt class TestParameters(QiskitTestCase): """Test Parameters.""" def test_gate(self): """Test instantiating gate with variable parameters""" theta = Parameter("θ") theta_gate = Gate("test", 1, params=[theta]) self.assertEqual(theta_gate.name, "test") self.assertIsInstance(theta_gate.params[0], Parameter) def test_compile_quantum_circuit(self): """Test instantiating gate with variable parameters""" theta = Parameter("θ") qr = QuantumRegister(1) qc = QuantumCircuit(qr) qc.rx(theta, qr) backend = BasicAer.get_backend("qasm_simulator") qc_aer = transpile(qc, backend) self.assertIn(theta, qc_aer.parameters) def test_duplicate_name_on_append(self): """Test adding a second parameter object with the same name fails.""" param_a = Parameter("a") param_a_again = Parameter("a") qc = QuantumCircuit(1) qc.rx(param_a, 0) self.assertRaises(CircuitError, qc.rx, param_a_again, 0) def test_get_parameters(self): """Test instantiating gate with variable parameters""" from qiskit.circuit.library.standard_gates.rx import RXGate theta = Parameter("θ") qr = QuantumRegister(1) qc = QuantumCircuit(qr) rxg = RXGate(theta) qc.append(rxg, [qr[0]], []) vparams = qc._parameter_table self.assertEqual(len(vparams), 1) self.assertIs(theta, next(iter(vparams))) self.assertEqual(rxg, next(iter(vparams[theta]))[0]) def test_get_parameters_by_index(self): """Test getting parameters by index""" x = Parameter("x") y = Parameter("y") z = Parameter("z") v = ParameterVector("v", 3) qc = QuantumCircuit(1) qc.rx(x, 0) qc.rz(z, 0) qc.ry(y, 0) qc.u(*v, 0) self.assertEqual(x, qc.parameters[3]) self.assertEqual(y, qc.parameters[4]) self.assertEqual(z, qc.parameters[5]) for i, vi in enumerate(v): self.assertEqual(vi, qc.parameters[i]) def test_bind_parameters_anonymously(self): """Test setting parameters by insertion order anonymously""" phase = Parameter("phase") x = Parameter("x") y = Parameter("y") z = Parameter("z") v = ParameterVector("v", 3) qc = QuantumCircuit(1, global_phase=phase) qc.rx(x, 0) qc.rz(z, 0) qc.ry(y, 0) qc.u(*v, 0) params = [0.1 * i for i in range(len(qc.parameters))] order = [phase] + v[:] + [x, y, z] param_dict = dict(zip(order, params)) for assign_fun in ["bind_parameters", "assign_parameters"]: with self.subTest(assign_fun=assign_fun): bqc_anonymous = getattr(qc, assign_fun)(params) bqc_list = getattr(qc, assign_fun)(param_dict) self.assertEqual(bqc_anonymous, bqc_list) def test_bind_parameters_allow_unknown(self): """Test binding parameters allowing unknown parameters.""" a = Parameter("a") b = Parameter("b") c = a.bind({a: 1, b: 1}, allow_unknown_parameters=True) self.assertEqual(c, a.bind({a: 1})) @data(QuantumCircuit.assign_parameters, QuantumCircuit.bind_parameters) def test_bind_parameters_custom_definition_global_phase(self, assigner): """Test that a custom gate with a parametrised `global_phase` is assigned correctly.""" x = Parameter("x") custom = QuantumCircuit(1, global_phase=x).to_gate() base = QuantumCircuit(1) base.append(custom, [0], []) test = Operator(assigner(base, {x: math.pi})) expected = Operator(numpy.array([[-1, 0], [0, -1]])) self.assertEqual(test, expected) def test_bind_half_single_precision(self): """Test binding with 16bit and 32bit floats.""" phase = Parameter("phase") x = Parameter("x") y = Parameter("y") z = Parameter("z") v = ParameterVector("v", 3) for i in (numpy.float16, numpy.float32): with self.subTest(float_type=i): expr = (v[0] * (x + y + z) + phase) - (v[2] * v[1]) params = numpy.array([0.1 * j for j in range(8)], dtype=i) order = [phase] + v[:] + [x, y, z] param_dict = dict(zip(order, params)) bound_value = expr.bind(param_dict) self.assertAlmostEqual(float(bound_value), 0.09, delta=1e-4) def test_parameter_order(self): """Test the parameters are sorted by name but parameter vector order takes precedence. This means that the following set of parameters {a, z, x[0], x[1], x[2], x[3], x[10], x[11]} will be sorted as [a, x[0], x[1], x[2], x[3], x[10], x[11], z] """ a, b, some_name, z = (Parameter(name) for name in ["a", "b", "some_name", "z"]) x = ParameterVector("x", 12) a_vector = ParameterVector("a_vector", 15) qc = QuantumCircuit(2) qc.p(z, 0) for i, x_i in enumerate(reversed(x)): qc.rx(x_i, i % 2) qc.cry(a, 0, 1) qc.crz(some_name, 1, 0) for v_i in a_vector[::2]: qc.p(v_i, 0) for v_i in a_vector[1::2]: qc.p(v_i, 1) qc.p(b, 0) expected_order = [a] + a_vector[:] + [b, some_name] + x[:] + [z] actual_order = qc.parameters self.assertListEqual(expected_order, list(actual_order)) @data(True, False) def test_parameter_order_compose(self, front): """Test the parameter order is correctly maintained upon composing circuits.""" x = Parameter("x") y = Parameter("y") qc1 = QuantumCircuit(1) qc1.p(x, 0) qc2 = QuantumCircuit(1) qc2.rz(y, 0) order = [x, y] composed = qc1.compose(qc2, front=front) self.assertListEqual(list(composed.parameters), order) def test_parameter_order_append(self): """Test the parameter order is correctly maintained upon appending circuits.""" x = Parameter("x") y = Parameter("y") qc1 = QuantumCircuit(1) qc1.p(x, 0) qc2 = QuantumCircuit(1) qc2.rz(y, 0) qc1.append(qc2, [0]) self.assertListEqual(list(qc1.parameters), [x, y]) def test_parameter_order_composing_nested_circuit(self): """Test the parameter order after nesting circuits and instructions.""" x = ParameterVector("x", 5) inner = QuantumCircuit(1) inner.rx(x[0], [0]) mid = QuantumCircuit(2) mid.p(x[1], 1) mid.append(inner, [0]) mid.p(x[2], 0) mid.append(inner, [0]) outer = QuantumCircuit(2) outer.compose(mid, inplace=True) outer.ryy(x[3], 0, 1) outer.compose(inner, inplace=True) outer.rz(x[4], 0) order = [x[0], x[1], x[2], x[3], x[4]] self.assertListEqual(list(outer.parameters), order) def test_is_parameterized(self): """Test checking if a gate is parameterized (bound/unbound)""" from qiskit.circuit.library.standard_gates.h import HGate from qiskit.circuit.library.standard_gates.rx import RXGate theta = Parameter("θ") rxg = RXGate(theta) self.assertTrue(rxg.is_parameterized()) theta_bound = theta.bind({theta: 3.14}) rxg = RXGate(theta_bound) self.assertFalse(rxg.is_parameterized()) h_gate = HGate() self.assertFalse(h_gate.is_parameterized()) def test_fix_variable(self): """Test setting a variable to a constant value""" theta = Parameter("θ") qr = QuantumRegister(1) qc = QuantumCircuit(qr) qc.rx(theta, qr) qc.u(0, theta, 0, qr) # test for both `bind_parameters` and `assign_parameters` for assign_fun in ["bind_parameters", "assign_parameters"]: with self.subTest(assign_fun=assign_fun): bqc = getattr(qc, assign_fun)({theta: 0.5}) self.assertEqual(float(bqc.data[0].operation.params[0]), 0.5) self.assertEqual(float(bqc.data[1].operation.params[1]), 0.5) bqc = getattr(qc, assign_fun)({theta: 0.6}) self.assertEqual(float(bqc.data[0].operation.params[0]), 0.6) self.assertEqual(float(bqc.data[1].operation.params[1]), 0.6) def test_multiple_parameters(self): """Test setting multiple parameters""" theta = Parameter("θ") x = Parameter("x") qr = QuantumRegister(1) qc = QuantumCircuit(qr) qc.rx(theta, qr) qc.u(0, theta, x, qr) self.assertEqual(qc.parameters, {theta, x}) def test_multiple_named_parameters(self): """Test setting multiple named/keyword argument based parameters""" theta = Parameter(name="θ") x = Parameter(name="x") qr = QuantumRegister(1) qc = QuantumCircuit(qr) qc.rx(theta, qr) qc.u(0, theta, x, qr) self.assertEqual(theta.name, "θ") self.assertEqual(qc.parameters, {theta, x}) @named_data( ["int", 2, int], ["float", 2.5, float], ["float16", numpy.float16(2.5), float], ["float32", numpy.float32(2.5), float], ["float64", numpy.float64(2.5), float], ) def test_circuit_assignment_to_numeric(self, value, type_): """Test binding a numeric value to a circuit instruction""" x = Parameter("x") qc = QuantumCircuit(1) qc.append(Instruction("inst", 1, 0, [x]), (0,)) qc.assign_parameters({x: value}, inplace=True) bound = qc.data[0].operation.params[0] self.assertIsInstance(bound, type_) self.assertEqual(bound, value) def test_partial_binding(self): """Test that binding a subset of circuit parameters returns a new parameterized circuit.""" theta = Parameter("θ") x = Parameter("x") qr = QuantumRegister(1) qc = QuantumCircuit(qr) qc.rx(theta, qr) qc.u(0, theta, x, qr) # test for both `bind_parameters` and `assign_parameters` for assign_fun in ["bind_parameters", "assign_parameters"]: with self.subTest(assign_fun=assign_fun): pqc = getattr(qc, assign_fun)({theta: 2}) self.assertEqual(pqc.parameters, {x}) self.assertEqual(float(pqc.data[0].operation.params[0]), 2) self.assertEqual(float(pqc.data[1].operation.params[1]), 2) @data(True, False) def test_mixed_binding(self, inplace): """Test we can bind a mixed dict with Parameter objects and floats.""" theta = Parameter("θ") x, new_x = Parameter("x"), Parameter("new_x") qr = QuantumRegister(1) qc = QuantumCircuit(qr) qc.rx(theta, qr) qc.u(0, theta, x, qr) pqc = qc.assign_parameters({theta: 2, x: new_x}, inplace=inplace) if inplace: self.assertEqual(qc.parameters, {new_x}) else: self.assertEqual(pqc.parameters, {new_x}) def test_expression_partial_binding(self): """Test that binding a subset of expression parameters returns a new parameterized circuit.""" theta = Parameter("θ") phi = Parameter("phi") qr = QuantumRegister(1) qc = QuantumCircuit(qr) qc.rx(theta + phi, qr) # test for both `bind_parameters` and `assign_parameters` for assign_fun in ["bind_parameters", "assign_parameters"]: with self.subTest(assign_fun=assign_fun): pqc = getattr(qc, assign_fun)({theta: 2}) self.assertEqual(pqc.parameters, {phi}) self.assertTrue(isinstance(pqc.data[0].operation.params[0], ParameterExpression)) self.assertEqual(str(pqc.data[0].operation.params[0]), "phi + 2") fbqc = getattr(pqc, assign_fun)({phi: 1.0}) self.assertEqual(fbqc.parameters, set()) self.assertIsInstance(fbqc.data[0].operation.params[0], float) self.assertEqual(float(fbqc.data[0].operation.params[0]), 3) def test_two_parameter_expression_binding(self): """Verify that for a circuit with parameters theta and phi that we can correctly assign theta to -phi. """ theta = Parameter("theta") phi = Parameter("phi") qc = QuantumCircuit(1) qc.rx(theta, 0) qc.ry(phi, 0) self.assertEqual(len(qc._parameter_table[theta]), 1) self.assertEqual(len(qc._parameter_table[phi]), 1) qc.assign_parameters({theta: -phi}, inplace=True) self.assertEqual(len(qc._parameter_table[phi]), 2) def test_expression_partial_binding_zero(self): """Verify that binding remains possible even if a previous partial bind would reduce the expression to zero. """ theta = Parameter("theta") phi = Parameter("phi") qc = QuantumCircuit(1) qc.p(theta * phi, 0) # test for both `bind_parameters` and `assign_parameters` for assign_fun in ["bind_parameters", "assign_parameters"]: with self.subTest(assign_fun=assign_fun): pqc = getattr(qc, assign_fun)({theta: 0}) self.assertEqual(pqc.parameters, {phi}) self.assertTrue(isinstance(pqc.data[0].operation.params[0], ParameterExpression)) self.assertEqual(str(pqc.data[0].operation.params[0]), "0") fbqc = getattr(pqc, assign_fun)({phi: 1}) self.assertEqual(fbqc.parameters, set()) self.assertIsInstance(fbqc.data[0].operation.params[0], int) self.assertEqual(float(fbqc.data[0].operation.params[0]), 0) def test_raise_if_assigning_params_not_in_circuit(self): """Verify binding parameters which are not present in the circuit raises an error.""" x = Parameter("x") y = Parameter("y") z = ParameterVector("z", 3) qr = QuantumRegister(1) qc = QuantumCircuit(qr) # test for both `bind_parameters` and `assign_parameters` for assign_fun in ["bind_parameters", "assign_parameters"]: qc = QuantumCircuit(qr) with self.subTest(assign_fun=assign_fun): qc.p(0.1, qr[0]) self.assertRaises(CircuitError, getattr(qc, assign_fun), {x: 1}) qc.p(x, qr[0]) self.assertRaises(CircuitError, getattr(qc, assign_fun), {x: 1, y: 2}) qc.p(z[1], qr[0]) self.assertRaises(CircuitError, getattr(qc, assign_fun), {z: [3, 4, 5]}) self.assertRaises(CircuitError, getattr(qc, assign_fun), {"a_str": 6}) self.assertRaises(CircuitError, getattr(qc, assign_fun), {None: 7}) def test_gate_multiplicity_binding(self): """Test binding when circuit contains multiple references to same gate""" qc = QuantumCircuit(1) theta = Parameter("theta") gate = RZGate(theta) qc.append(gate, [0], []) qc.append(gate, [0], []) # test for both `bind_parameters` and `assign_parameters` for assign_fun in ["bind_parameters", "assign_parameters"]: with self.subTest(assign_fun=assign_fun): qc2 = getattr(qc, assign_fun)({theta: 1.0}) self.assertEqual(len(qc2._parameter_table), 0) for instruction in qc2.data: self.assertEqual(float(instruction.operation.params[0]), 1.0) def test_calibration_assignment(self): """That that calibration mapping and the schedules they map are assigned together.""" theta = Parameter("theta") circ = QuantumCircuit(3, 3) circ.append(Gate("rxt", 1, [theta]), [0]) circ.measure(0, 0) rxt_q0 = pulse.Schedule( pulse.Play( pulse.library.Gaussian(duration=128, sigma=16, amp=0.2 * theta / 3.14), pulse.DriveChannel(0), ) ) circ.add_calibration("rxt", [0], rxt_q0, [theta]) circ = circ.assign_parameters({theta: 3.14}) instruction = circ.data[0] cal_key = ( tuple(circ.find_bit(q).index for q in instruction.qubits), tuple(instruction.operation.params), ) self.assertEqual(cal_key, ((0,), (3.14,))) # Make sure that key from instruction data matches the calibrations dictionary self.assertIn(cal_key, circ.calibrations["rxt"]) sched = circ.calibrations["rxt"][cal_key] self.assertEqual(sched.instructions[0][1].pulse.amp, 0.2) def test_calibration_assignment_doesnt_mutate(self): """That that assignment doesn't mutate the original circuit.""" theta = Parameter("theta") circ = QuantumCircuit(3, 3) circ.append(Gate("rxt", 1, [theta]), [0]) circ.measure(0, 0) rxt_q0 = pulse.Schedule( pulse.Play( pulse.library.Gaussian(duration=128, sigma=16, amp=0.2 * theta / 3.14), pulse.DriveChannel(0), ) ) circ.add_calibration("rxt", [0], rxt_q0, [theta]) circ_copy = copy.deepcopy(circ) assigned_circ = circ.assign_parameters({theta: 3.14}) self.assertEqual(circ.calibrations, circ_copy.calibrations) self.assertNotEqual(assigned_circ.calibrations, circ.calibrations) def test_calibration_assignment_w_expressions(self): """That calibrations with multiple parameters are assigned correctly""" theta = Parameter("theta") sigma = Parameter("sigma") circ = QuantumCircuit(3, 3) circ.append(Gate("rxt", 1, [theta / 2, sigma]), [0]) circ.measure(0, 0) rxt_q0 = pulse.Schedule( pulse.Play( pulse.library.Gaussian(duration=128, sigma=4 * sigma, amp=0.2 * theta / 3.14), pulse.DriveChannel(0), ) ) circ.add_calibration("rxt", [0], rxt_q0, [theta / 2, sigma]) circ = circ.assign_parameters({theta: 3.14, sigma: 4}) instruction = circ.data[0] cal_key = ( tuple(circ.find_bit(q).index for q in instruction.qubits), tuple(instruction.operation.params), ) self.assertEqual(cal_key, ((0,), (3.14 / 2, 4))) # Make sure that key from instruction data matches the calibrations dictionary self.assertIn(cal_key, circ.calibrations["rxt"]) sched = circ.calibrations["rxt"][cal_key] self.assertEqual(sched.instructions[0][1].pulse.amp, 0.2) self.assertEqual(sched.instructions[0][1].pulse.sigma, 16) def test_substitution(self): """Test Parameter substitution (vs bind).""" alpha = Parameter("⍺") beta = Parameter("beta") schedule = pulse.Schedule(pulse.ShiftPhase(alpha, pulse.DriveChannel(0))) circ = QuantumCircuit(3, 3) circ.append(Gate("my_rz", 1, [alpha]), [0]) circ.add_calibration("my_rz", [0], schedule, [alpha]) circ = circ.assign_parameters({alpha: 2 * beta}) circ = circ.assign_parameters({beta: 1.57}) cal_sched = circ.calibrations["my_rz"][((0,), (3.14,))] self.assertEqual(float(cal_sched.instructions[0][1].phase), 3.14) def test_partial_assignment(self): """Expressions of parameters with partial assignment.""" alpha = Parameter("⍺") beta = Parameter("beta") gamma = Parameter("γ") phi = Parameter("ϕ") with pulse.build() as my_cal: pulse.set_frequency(alpha + beta, pulse.DriveChannel(0)) pulse.shift_frequency(gamma + beta, pulse.DriveChannel(0)) pulse.set_phase(phi, pulse.DriveChannel(1)) circ = QuantumCircuit(2, 2) circ.append(Gate("custom", 2, [alpha, beta, gamma, phi]), [0, 1]) circ.add_calibration("custom", [0, 1], my_cal, [alpha, beta, gamma, phi]) # Partial bind delta = 1e9 freq = 4.5e9 shift = 0.5e9 phase = 3.14 / 4 circ = circ.assign_parameters({alpha: freq - delta}) cal_sched = list(circ.calibrations["custom"].values())[0] self.assertEqual(cal_sched.instructions[0][1].frequency, freq - delta + beta) circ = circ.assign_parameters({beta: delta}) cal_sched = list(circ.calibrations["custom"].values())[0] self.assertEqual(float(cal_sched.instructions[0][1].frequency), freq) self.assertEqual(cal_sched.instructions[1][1].frequency, gamma + delta) circ = circ.assign_parameters({gamma: shift - delta}) cal_sched = list(circ.calibrations["custom"].values())[0] self.assertEqual(float(cal_sched.instructions[1][1].frequency), shift) self.assertEqual(cal_sched.instructions[2][1].phase, phi) circ = circ.assign_parameters({phi: phase}) cal_sched = list(circ.calibrations["custom"].values())[0] self.assertEqual(float(cal_sched.instructions[2][1].phase), phase) def test_circuit_generation(self): """Test creating a series of circuits parametrically""" theta = Parameter("θ") qr = QuantumRegister(1) qc = QuantumCircuit(qr) qc.rx(theta, qr) backend = BasicAer.get_backend("qasm_simulator") qc_aer = transpile(qc, backend) # generate list of circuits for assign_fun in ["bind_parameters", "assign_parameters"]: with self.subTest(assign_fun=assign_fun): circs = [] theta_list = numpy.linspace(0, numpy.pi, 20) for theta_i in theta_list: circs.append(getattr(qc_aer, assign_fun)({theta: theta_i})) qobj = assemble(circs) for index, theta_i in enumerate(theta_list): res = float(qobj.experiments[index].instructions[0].params[0]) self.assertTrue(math.isclose(res, theta_i), f"{res} != {theta_i}") def test_circuit_composition(self): """Test preservation of parameters when combining circuits.""" theta = Parameter("θ") qr = QuantumRegister(1) cr = ClassicalRegister(1) qc1 = QuantumCircuit(qr, cr) qc1.rx(theta, qr) phi = Parameter("phi") qc2 = QuantumCircuit(qr, cr) qc2.ry(phi, qr) qc2.h(qr) qc2.measure(qr, cr) qc3 = qc1.compose(qc2) self.assertEqual(qc3.parameters, {theta, phi}) def test_composite_instruction(self): """Test preservation of parameters via parameterized instructions.""" theta = Parameter("θ") qr1 = QuantumRegister(1, name="qr1") qc1 = QuantumCircuit(qr1) qc1.rx(theta, qr1) qc1.rz(numpy.pi / 2, qr1) qc1.ry(theta, qr1) gate = qc1.to_instruction() self.assertEqual(gate.params, [theta]) phi = Parameter("phi") qr2 = QuantumRegister(3, name="qr2") qc2 = QuantumCircuit(qr2) qc2.ry(phi, qr2[0]) qc2.h(qr2) qc2.append(gate, qargs=[qr2[1]]) self.assertEqual(qc2.parameters, {theta, phi}) def test_parameter_name_conflicts_raises(self): """Verify attempting to add different parameters with matching names raises an error.""" theta1 = Parameter("theta") theta2 = Parameter("theta") qr = QuantumRegister(1) qc = QuantumCircuit(qr) qc.p(theta1, 0) self.assertRaises(CircuitError, qc.p, theta2, 0) def test_bind_ryrz_vector(self): """Test binding a list of floats to a ParameterVector""" qc = QuantumCircuit(4) depth = 4 theta = ParameterVector("θ", length=len(qc.qubits) * depth * 2) theta_iter = iter(theta) for _ in range(depth): for q in qc.qubits: qc.ry(next(theta_iter), q) qc.rz(next(theta_iter), q) for i, q in enumerate(qc.qubits[:-1]): qc.cx(qc.qubits[i], qc.qubits[i + 1]) qc.barrier() theta_vals = numpy.linspace(0, 1, len(theta)) * numpy.pi self.assertEqual(set(qc.parameters), set(theta.params)) for assign_fun in ["bind_parameters", "assign_parameters"]: with self.subTest(assign_fun=assign_fun): bqc = getattr(qc, assign_fun)({theta: theta_vals}) for instruction in bqc.data: if hasattr(instruction.operation, "params") and instruction.operation.params: self.assertIn(float(instruction.operation.params[0]), theta_vals) def test_compile_vector(self): """Test compiling a circuit with an unbound ParameterVector""" qc = QuantumCircuit(4) depth = 4 theta = ParameterVector("θ", length=len(qc.qubits) * depth * 2) theta_iter = iter(theta) for _ in range(depth): for q in qc.qubits: qc.ry(next(theta_iter), q) qc.rz(next(theta_iter), q) for i, q in enumerate(qc.qubits[:-1]): qc.cx(qc.qubits[i], qc.qubits[i + 1]) qc.barrier() backend = BasicAer.get_backend("qasm_simulator") qc_aer = transpile(qc, backend) for param in theta: self.assertIn(param, qc_aer.parameters) def test_instruction_ryrz_vector(self): """Test constructing a circuit from instructions with remapped ParameterVectors""" qubits = 5 depth = 4 ryrz = QuantumCircuit(qubits, name="ryrz") theta = ParameterVector("θ0", length=len(ryrz.qubits) * 2) theta_iter = iter(theta) for q in ryrz.qubits: ryrz.ry(next(theta_iter), q) ryrz.rz(next(theta_iter), q) cxs = QuantumCircuit(qubits - 1, name="cxs") for i, _ in enumerate(cxs.qubits[:-1:2]): cxs.cx(cxs.qubits[2 * i], cxs.qubits[2 * i + 1]) paramvecs = [] qc = QuantumCircuit(qubits) for i in range(depth): theta_l = ParameterVector(f"θ{i + 1}", length=len(ryrz.qubits) * 2) ryrz_inst = ryrz.to_instruction(parameter_map={theta: theta_l}) paramvecs += [theta_l] qc.append(ryrz_inst, qargs=qc.qubits) qc.append(cxs, qargs=qc.qubits[1:]) qc.append(cxs, qargs=qc.qubits[:-1]) qc.barrier() backend = BasicAer.get_backend("qasm_simulator") qc_aer = transpile(qc, backend) for vec in paramvecs: for param in vec: self.assertIn(param, qc_aer.parameters) @data("single", "vector") def test_parameter_equality_through_serialization(self, ptype): """Verify parameters maintain their equality after serialization.""" if ptype == "single": x1 = Parameter("x") x2 = Parameter("x") else: x1 = ParameterVector("x", 2)[0] x2 = ParameterVector("x", 2)[0] x1_p = pickle.loads(pickle.dumps(x1)) x2_p = pickle.loads(pickle.dumps(x2)) self.assertEqual(x1, x1_p) self.assertEqual(x2, x2_p) self.assertNotEqual(x1, x2_p) self.assertNotEqual(x2, x1_p) def test_binding_parameterized_circuits_built_in_multiproc(self): """Verify subcircuits built in a subprocess can still be bound.""" # ref: https://github.com/Qiskit/qiskit-terra/issues/2429 num_processes = 4 qr = QuantumRegister(3) cr = ClassicalRegister(3) circuit = QuantumCircuit(qr, cr) parameters = [Parameter(f"x{i}") for i in range(num_processes)] results = parallel_map( _construct_circuit, parameters, task_args=(qr,), num_processes=num_processes ) for qc in results: circuit.compose(qc, inplace=True) parameter_values = [{x: 1.0 for x in parameters}] qobj = assemble( circuit, backend=BasicAer.get_backend("qasm_simulator"), parameter_binds=parameter_values, ) self.assertEqual(len(qobj.experiments), 1) self.assertEqual(len(qobj.experiments[0].instructions), 4) self.assertTrue( all( len(inst.params) == 1 and isinstance(inst.params[0], float) and float(inst.params[0]) == 1 for inst in qobj.experiments[0].instructions ) ) def test_transpiling_multiple_parameterized_circuits(self): """Verify several parameterized circuits can be transpiled at once.""" # ref: https://github.com/Qiskit/qiskit-terra/issues/2864 qr = QuantumRegister(1) qc1 = QuantumCircuit(qr) qc2 = QuantumCircuit(qr) theta = Parameter("theta") qc1.u(theta, 0, 0, qr[0]) qc2.u(theta, 3.14, 0, qr[0]) circuits = [qc1, qc2] job = execute( circuits, BasicAer.get_backend("unitary_simulator"), shots=512, parameter_binds=[{theta: 1}], ) self.assertTrue(len(job.result().results), 2) @data(0, 1, 2, 3) def test_transpile_across_optimization_levels(self, opt_level): """Verify parameterized circuits can be transpiled with all default pass managers.""" qc = QuantumCircuit(5, 5) theta = Parameter("theta") phi = Parameter("phi") qc.rx(theta, 0) qc.x(0) for i in range(5 - 1): qc.rxx(phi, i, i + 1) qc.measure(range(5 - 1), range(5 - 1)) transpile(qc, FakeOurense(), optimization_level=opt_level) def test_repeated_gates_to_dag_and_back(self): """Verify circuits with repeated parameterized gates can be converted to DAG and back, maintaining consistency of circuit._parameter_table.""" from qiskit.converters import circuit_to_dag, dag_to_circuit qr = QuantumRegister(1) qc = QuantumCircuit(qr) theta = Parameter("theta") qc.p(theta, qr[0]) double_qc = qc.compose(qc) test_qc = dag_to_circuit(circuit_to_dag(double_qc)) for assign_fun in ["bind_parameters", "assign_parameters"]: with self.subTest(assign_fun=assign_fun): bound_test_qc = getattr(test_qc, assign_fun)({theta: 1}) self.assertEqual(len(bound_test_qc.parameters), 0) def test_rebinding_instruction_copy(self): """Test rebinding a copied instruction does not modify the original.""" theta = Parameter("th") qc = QuantumCircuit(1) qc.rx(theta, 0) instr = qc.to_instruction() qc1 = QuantumCircuit(1) qc1.append(instr, [0]) for assign_fun in ["bind_parameters", "assign_parameters"]: with self.subTest(assign_fun=assign_fun): output1 = getattr(qc1, assign_fun)({theta: 0.1}).decompose() output2 = getattr(qc1, assign_fun)({theta: 0.2}).decompose() expected1 = QuantumCircuit(1) expected1.rx(0.1, 0) expected2 = QuantumCircuit(1) expected2.rx(0.2, 0) self.assertEqual(expected1, output1) self.assertEqual(expected2, output2) @combine(target_type=["gate", "instruction"], parameter_type=["numbers", "parameters"]) def test_decompose_propagates_bound_parameters(self, target_type, parameter_type): """Verify bind-before-decompose preserves bound values.""" # ref: https://github.com/Qiskit/qiskit-terra/issues/2482 theta = Parameter("th") qc = QuantumCircuit(1) qc.rx(theta, 0) if target_type == "gate": inst = qc.to_gate() elif target_type == "instruction": inst = qc.to_instruction() qc2 = QuantumCircuit(1) qc2.append(inst, [0]) if parameter_type == "numbers": bound_qc2 = qc2.assign_parameters({theta: 0.5}) expected_parameters = set() expected_qc2 = QuantumCircuit(1) expected_qc2.rx(0.5, 0) else: phi = Parameter("ph") bound_qc2 = qc2.assign_parameters({theta: phi}) expected_parameters = {phi} expected_qc2 = QuantumCircuit(1) expected_qc2.rx(phi, 0) decomposed_qc2 = bound_qc2.decompose() with self.subTest(msg="testing parameters of initial circuit"): self.assertEqual(qc2.parameters, {theta}) with self.subTest(msg="testing parameters of bound circuit"): self.assertEqual(bound_qc2.parameters, expected_parameters) with self.subTest(msg="testing parameters of deep decomposed bound circuit"): self.assertEqual(decomposed_qc2.parameters, expected_parameters) with self.subTest(msg="testing deep decomposed circuit"): self.assertEqual(decomposed_qc2, expected_qc2) @combine(target_type=["gate", "instruction"], parameter_type=["numbers", "parameters"]) def test_decompose_propagates_deeply_bound_parameters(self, target_type, parameter_type): """Verify bind-before-decompose preserves deeply bound values.""" theta = Parameter("th") qc1 = QuantumCircuit(1) qc1.rx(theta, 0) if target_type == "gate": inst = qc1.to_gate() elif target_type == "instruction": inst = qc1.to_instruction() qc2 = QuantumCircuit(1) qc2.append(inst, [0]) if target_type == "gate": inst = qc2.to_gate() elif target_type == "instruction": inst = qc2.to_instruction() qc3 = QuantumCircuit(1) qc3.append(inst, [0]) if parameter_type == "numbers": bound_qc3 = qc3.assign_parameters({theta: 0.5}) expected_parameters = set() expected_qc3 = QuantumCircuit(1) expected_qc3.rx(0.5, 0) else: phi = Parameter("ph") bound_qc3 = qc3.assign_parameters({theta: phi}) expected_parameters = {phi} expected_qc3 = QuantumCircuit(1) expected_qc3.rx(phi, 0) deep_decomposed_qc3 = bound_qc3.decompose().decompose() with self.subTest(msg="testing parameters of initial circuit"): self.assertEqual(qc3.parameters, {theta}) with self.subTest(msg="testing parameters of bound circuit"): self.assertEqual(bound_qc3.parameters, expected_parameters) with self.subTest(msg="testing parameters of deep decomposed bound circuit"): self.assertEqual(deep_decomposed_qc3.parameters, expected_parameters) with self.subTest(msg="testing deep decomposed circuit"): self.assertEqual(deep_decomposed_qc3, expected_qc3) @data("gate", "instruction") def test_executing_parameterized_instruction_bound_early(self, target_type): """Verify bind-before-execute preserves bound values.""" # ref: https://github.com/Qiskit/qiskit-terra/issues/2482 theta = Parameter("theta") sub_qc = QuantumCircuit(2) sub_qc.h(0) sub_qc.cx(0, 1) sub_qc.rz(theta, [0, 1]) sub_qc.cx(0, 1) sub_qc.h(0) if target_type == "gate": sub_inst = sub_qc.to_gate() elif target_type == "instruction": sub_inst = sub_qc.to_instruction() unbound_qc = QuantumCircuit(2, 1) unbound_qc.append(sub_inst, [0, 1], []) unbound_qc.measure(0, 0) for assign_fun in ["bind_parameters", "assign_parameters"]: with self.subTest(assign_fun=assign_fun): bound_qc = getattr(unbound_qc, assign_fun)({theta: numpy.pi / 2}) shots = 1024 job = execute(bound_qc, backend=BasicAer.get_backend("qasm_simulator"), shots=shots) self.assertDictAlmostEqual(job.result().get_counts(), {"1": shots}, 0.05 * shots) def test_num_parameters(self): """Test the num_parameters property.""" with self.subTest(msg="standard case"): theta = Parameter("θ") x = Parameter("x") qc = QuantumCircuit(1) qc.rx(theta, 0) qc.u(0, theta, x, 0) self.assertEqual(qc.num_parameters, 2) with self.subTest(msg="parameter vector"): params = ParameterVector("x", length=3) qc = QuantumCircuit(4) qc.rx(params[0], 2) qc.ry(params[1], 1) qc.rz(params[2], 3) self.assertEqual(qc.num_parameters, 3) with self.subTest(msg="no params"): qc = QuantumCircuit(1) qc.x(0) self.assertEqual(qc.num_parameters, 0) def test_execute_result_names(self): """Test unique names for list of parameter binds.""" theta = Parameter("θ") reps = 5 qc = QuantumCircuit(1, 1) qc.rx(theta, 0) qc.measure(0, 0) plist = [{theta: i} for i in range(reps)] simulator = BasicAer.get_backend("qasm_simulator") result = execute(qc, backend=simulator, parameter_binds=plist).result() result_names = {res.name for res in result.results} self.assertEqual(reps, len(result_names)) def test_to_instruction_after_inverse(self): """Verify converting an inverse generates a valid ParameterTable""" # ref: https://github.com/Qiskit/qiskit-terra/issues/4235 qc = QuantumCircuit(1) theta = Parameter("theta") qc.rz(theta, 0) inv_instr = qc.inverse().to_instruction() self.assertIsInstance(inv_instr, Instruction) def test_repeated_circuit(self): """Test repeating a circuit maintains the parameters.""" qc = QuantumCircuit(1) theta = Parameter("theta") qc.rz(theta, 0) rep = qc.repeat(3) self.assertEqual(rep.parameters, {theta}) def test_copy_after_inverse(self): """Verify circuit.inverse generates a valid ParameterTable.""" qc = QuantumCircuit(1) theta = Parameter("theta") qc.rz(theta, 0) inverse = qc.inverse() self.assertIn(theta, inverse.parameters) raise_if_parameter_table_invalid(inverse) def test_copy_after_reverse(self): """Verify circuit.reverse generates a valid ParameterTable.""" qc = QuantumCircuit(1) theta = Parameter("theta") qc.rz(theta, 0) reverse = qc.reverse_ops() self.assertIn(theta, reverse.parameters) raise_if_parameter_table_invalid(reverse) def test_copy_after_dot_data_setter(self): """Verify setting circuit.data generates a valid ParameterTable.""" qc = QuantumCircuit(1) theta = Parameter("theta") qc.rz(theta, 0) qc.data = [] self.assertEqual(qc.parameters, set()) raise_if_parameter_table_invalid(qc) def test_circuit_with_ufunc(self): """Test construction of circuit and binding of parameters after we apply universal functions.""" from math import pi phi = Parameter(name="phi") theta = Parameter(name="theta") qc = QuantumCircuit(2) qc.p(numpy.abs(-phi), 0) qc.p(numpy.cos(phi), 0) qc.p(numpy.sin(phi), 0) qc.p(numpy.tan(phi), 0) qc.rz(numpy.arccos(theta), 1) qc.rz(numpy.arctan(theta), 1) qc.rz(numpy.arcsin(theta), 1) qc.assign_parameters({phi: pi, theta: 1}, inplace=True) qc_ref = QuantumCircuit(2) qc_ref.p(pi, 0) qc_ref.p(-1, 0) qc_ref.p(0, 0) qc_ref.p(0, 0) qc_ref.rz(0, 1) qc_ref.rz(pi / 4, 1) qc_ref.rz(pi / 2, 1) self.assertEqual(qc, qc_ref) def test_compile_with_ufunc(self): """Test compiling of circuit with unbound parameters after we apply universal functions.""" from math import pi theta = ParameterVector("theta", length=7) qc = QuantumCircuit(7) qc.rx(numpy.abs(theta[0]), 0) qc.rx(numpy.cos(theta[1]), 1) qc.rx(numpy.sin(theta[2]), 2) qc.rx(numpy.tan(theta[3]), 3) qc.rx(numpy.arccos(theta[4]), 4) qc.rx(numpy.arctan(theta[5]), 5) qc.rx(numpy.arcsin(theta[6]), 6) # transpile to different basis transpiled = transpile(qc, basis_gates=["rz", "sx", "x", "cx"], optimization_level=0) for x in theta: self.assertIn(x, transpiled.parameters) bound = transpiled.bind_parameters({theta: [-1, pi, pi, pi, 1, 1, 1]}) expected = QuantumCircuit(7) expected.rx(1.0, 0) expected.rx(-1.0, 1) expected.rx(0.0, 2) expected.rx(0.0, 3) expected.rx(0.0, 4) expected.rx(pi / 4, 5) expected.rx(pi / 2, 6) expected = transpile(expected, basis_gates=["rz", "sx", "x", "cx"], optimization_level=0) self.assertEqual(expected, bound) def test_parametervector_resize(self): """Test the resize method of the parameter vector.""" vec = ParameterVector("x", 2) element = vec[1] # store an entry for instancecheck later on with self.subTest("shorten"): vec.resize(1) self.assertEqual(len(vec), 1) self.assertListEqual([param.name for param in vec], _paramvec_names("x", 1)) with self.subTest("enlargen"): vec.resize(3) self.assertEqual(len(vec), 3) # ensure we still have the same instance not a copy with the same name # this is crucial for adding parameters to circuits since we cannot use the same # name if the instance is not the same self.assertIs(element, vec[1]) self.assertListEqual([param.name for param in vec], _paramvec_names("x", 3)) def test_raise_if_sub_unknown_parameters(self): """Verify we raise if asked to sub a parameter not in self.""" x = Parameter("x") y = Parameter("y") z = Parameter("z") with self.assertRaisesRegex(CircuitError, "not present"): x.subs({y: z}) def test_sub_allow_unknown_parameters(self): """Verify we raise if asked to sub a parameter not in self.""" x = Parameter("x") y = Parameter("y") z = Parameter("z") subbed = x.subs({y: z}, allow_unknown_parameters=True) self.assertEqual(subbed, x) def _construct_circuit(param, qr): qc = QuantumCircuit(qr) qc.ry(param, qr[0]) return qc def _paramvec_names(prefix, length): return [f"{prefix}[{i}]" for i in range(length)] @ddt class TestParameterExpressions(QiskitTestCase): """Test expressions of Parameters.""" supported_operations = [add, sub, mul, truediv] def test_compare_to_value_when_bound(self): """Verify expression can be compared to a fixed value when fully bound.""" x = Parameter("x") bound_expr = x.bind({x: 2.3}) self.assertEqual(bound_expr, 2.3) def test_abs_function_when_bound(self): """Verify expression can be used with abs functions when bound.""" x = Parameter("x") xb_1 = x.bind({x: 2.0}) xb_2 = x.bind({x: 3.0 + 4.0j}) self.assertEqual(abs(xb_1), 2.0) self.assertEqual(abs(-xb_1), 2.0) self.assertEqual(abs(xb_2), 5.0) def test_abs_function_when_not_bound(self): """Verify expression can be used with abs functions when not bound.""" x = Parameter("x") y = Parameter("y") self.assertEqual(abs(x), abs(-x)) self.assertEqual(abs(x) * abs(y), abs(x * y)) self.assertEqual(abs(x) / abs(y), abs(x / y)) def test_cast_to_complex_when_bound(self): """Verify that the cast to complex works for bound objects.""" x = Parameter("x") y = Parameter("y") bound_expr = (x + y).bind({x: 1.0, y: 1j}) self.assertEqual(complex(bound_expr), 1 + 1j) def test_raise_if_cast_to_complex_when_not_fully_bound(self): """Verify raises if casting to complex and not fully bound.""" x = Parameter("x") y = Parameter("y") bound_expr = (x + y).bind({x: 1j}) with self.assertRaisesRegex(TypeError, "unbound parameters"): complex(bound_expr) def test_cast_to_float_when_bound(self): """Verify expression can be cast to a float when fully bound.""" x = Parameter("x") bound_expr = x.bind({x: 2.3}) self.assertEqual(float(bound_expr), 2.3) def test_cast_to_float_when_underlying_expression_bound(self): """Verify expression can be cast to a float when it still contains unbound parameters, but the underlying symbolic expression has a knowable value.""" x = Parameter("x") expr = x - x + 2.3 self.assertEqual(float(expr), 2.3) def test_cast_to_float_intermediate_complex_value(self): """Verify expression can be cast to a float when it is fully bound, but an intermediate part of the expression evaluation involved complex types. Sympy is generally more permissive than symengine here, and sympy's tends to be the expected behaviour for our users.""" x = Parameter("x") bound_expr = (x + 1.0 + 1.0j).bind({x: -1.0j}) self.assertEqual(float(bound_expr), 1.0) def test_cast_to_float_of_complex_fails(self): """Test that an attempt to produce a float from a complex value fails if there is an imaginary part, with a sensible error message.""" x = Parameter("x") bound_expr = (x + 1.0j).bind({x: 1.0}) with self.assertRaisesRegex(TypeError, "could not cast expression to float"): float(bound_expr) def test_raise_if_cast_to_float_when_not_fully_bound(self): """Verify raises if casting to float and not fully bound.""" x = Parameter("x") y = Parameter("y") bound_expr = (x + y).bind({x: 2.3}) with self.assertRaisesRegex(TypeError, "unbound parameters"): float(bound_expr) def test_cast_to_int_when_bound(self): """Verify expression can be cast to an int when fully bound.""" x = Parameter("x") bound_expr = x.bind({x: 2.3}) self.assertEqual(int(bound_expr), 2) def test_cast_to_int_when_bound_truncates_after_evaluation(self): """Verify expression can be cast to an int when fully bound, but truncated only after evaluation.""" x = Parameter("x") y = Parameter("y") bound_expr = (x + y).bind({x: 2.3, y: 0.8}) self.assertEqual(int(bound_expr), 3) def test_cast_to_int_when_underlying_expression_bound(self): """Verify expression can be cast to a int when it still contains unbound parameters, but the underlying symbolic expression has a knowable value.""" x = Parameter("x") expr = x - x + 2.3 self.assertEqual(int(expr), 2) def test_raise_if_cast_to_int_when_not_fully_bound(self): """Verify raises if casting to int and not fully bound.""" x = Parameter("x") y = Parameter("y") bound_expr = (x + y).bind({x: 2.3}) with self.assertRaisesRegex(TypeError, "unbound parameters"): int(bound_expr) def test_raise_if_sub_unknown_parameters(self): """Verify we raise if asked to sub a parameter not in self.""" x = Parameter("x") expr = x + 2 y = Parameter("y") z = Parameter("z") with self.assertRaisesRegex(CircuitError, "not present"): expr.subs({y: z}) def test_sub_allow_unknown_parameters(self): """Verify we raise if asked to sub a parameter not in self.""" x = Parameter("x") expr = x + 2 y = Parameter("y") z = Parameter("z") subbed = expr.subs({y: z}, allow_unknown_parameters=True) self.assertEqual(subbed, expr) def test_raise_if_subbing_in_parameter_name_conflict(self): """Verify we raise if substituting in conflicting parameter names.""" x = Parameter("x") y_first = Parameter("y") expr = x + y_first y_second = Parameter("y") # Replacing an existing name is okay. expr.subs({y_first: y_second}) with self.assertRaisesRegex(CircuitError, "Name conflict"): expr.subs({x: y_second}) def test_expressions_of_parameter_with_constant(self): """Verify operating on a Parameter with a constant.""" good_constants = [2, 1.3, 0, -1, -1.0, numpy.pi, 1j] x = Parameter("x") for op in self.supported_operations: for const in good_constants: expr = op(const, x) bound_expr = expr.bind({x: 2.3}) self.assertEqual(complex(bound_expr), op(const, 2.3)) # Division by zero will raise. Tested elsewhere. if const == 0 and op == truediv: continue # Repeat above, swapping position of Parameter and constant. expr = op(x, const) bound_expr = expr.bind({x: 2.3}) res = complex(bound_expr) expected = op(2.3, const) self.assertTrue(cmath.isclose(res, expected), f"{res} != {expected}") def test_complex_parameter_bound_to_real(self): """Test a complex parameter expression can be real if bound correctly.""" x, y = Parameter("x"), Parameter("y") with self.subTest("simple 1j * x"): qc = QuantumCircuit(1) qc.rx(1j * x, 0) bound = qc.bind_parameters({x: 1j}) ref = QuantumCircuit(1) ref.rx(-1, 0) self.assertEqual(bound, ref) with self.subTest("more complex expression"): qc = QuantumCircuit(1) qc.rx(0.5j * x - y * y + 2 * y, 0) bound = qc.bind_parameters({x: -4, y: 1j}) ref = QuantumCircuit(1) ref.rx(1, 0) self.assertEqual(bound, ref) def test_complex_angle_raises_when_not_supported(self): """Test parameters are validated when fully bound and errors are raised accordingly.""" x = Parameter("x") qc = QuantumCircuit(1) qc.r(x, 1j * x, 0) with self.subTest("binding x to 0 yields real parameters"): bound = qc.bind_parameters({x: 0}) ref = QuantumCircuit(1) ref.r(0, 0, 0) self.assertEqual(bound, ref) with self.subTest("binding x to 1 yields complex parameters"): # RGate does not support complex parameters with self.assertRaises(CircuitError): bound = qc.bind_parameters({x: 1}) def test_operating_on_a_parameter_with_a_non_float_will_raise(self): """Verify operations between a Parameter and a non-float will raise.""" bad_constants = ["1", numpy.Inf, numpy.NaN, None, {}, []] x = Parameter("x") for op in self.supported_operations: for const in bad_constants: with self.subTest(op=op, const=const): with self.assertRaises(TypeError): _ = op(const, x) with self.assertRaises(TypeError): _ = op(x, const) def test_expressions_division_by_zero(self): """Verify dividing a Parameter by 0, or binding 0 as a denominator raises.""" x = Parameter("x") with self.assertRaises(ZeroDivisionError): _ = x / 0 with self.assertRaises(ZeroDivisionError): _ = x / 0.0 expr = 2 / x with self.assertRaises(ZeroDivisionError): _ = expr.bind({x: 0}) with self.assertRaises(ZeroDivisionError): _ = expr.bind({x: 0.0}) def test_expressions_of_parameter_with_parameter(self): """Verify operating on two Parameters.""" x = Parameter("x") y = Parameter("y") for op in self.supported_operations: expr = op(x, y) partially_bound_expr = expr.bind({x: 2.3}) self.assertEqual(partially_bound_expr.parameters, {y}) fully_bound_expr = partially_bound_expr.bind({y: -numpy.pi}) self.assertEqual(fully_bound_expr.parameters, set()) self.assertEqual(float(fully_bound_expr), op(2.3, -numpy.pi)) bound_expr = expr.bind({x: 2.3, y: -numpy.pi}) self.assertEqual(bound_expr.parameters, set()) self.assertEqual(float(bound_expr), op(2.3, -numpy.pi)) def test_expressions_operation_order(self): """Verify ParameterExpressions respect order of operations.""" x = Parameter("x") y = Parameter("y") z = Parameter("z") # Parenthesis before multiplication/division expr = (x + y) * z bound_expr = expr.bind({x: 1, y: 2, z: 3}) self.assertEqual(float(bound_expr), 9) expr = x * (y + z) bound_expr = expr.bind({x: 1, y: 2, z: 3}) self.assertEqual(float(bound_expr), 5) # Multiplication/division before addition/subtraction expr = x + y * z bound_expr = expr.bind({x: 1, y: 2, z: 3}) self.assertEqual(float(bound_expr), 7) expr = x * y + z bound_expr = expr.bind({x: 1, y: 2, z: 3}) self.assertEqual(float(bound_expr), 5) def test_nested_expressions(self): """Verify ParameterExpressions can also be the target of operations.""" x = Parameter("x") y = Parameter("y") z = Parameter("z") expr1 = x * y expr2 = expr1 + z bound_expr2 = expr2.bind({x: 1, y: 2, z: 3}) self.assertEqual(float(bound_expr2), 5) def test_negated_expression(self): """Verify ParameterExpressions can be negated.""" x = Parameter("x") y = Parameter("y") z = Parameter("z") expr1 = -x + y expr2 = -expr1 * (-z) bound_expr2 = expr2.bind({x: 1, y: 2, z: 3}) self.assertEqual(float(bound_expr2), 3) def test_standard_cu3(self): """This tests parameter negation in standard extension gate cu3.""" from qiskit.circuit.library import CU3Gate x = Parameter("x") y = Parameter("y") z = Parameter("z") qc = qiskit.QuantumCircuit(2) qc.append(CU3Gate(x, y, z), [0, 1]) try: qc.decompose() except TypeError: self.fail("failed to decompose cu3 gate with negated parameter expression") def test_name_collision(self): """Verify Expressions of distinct Parameters of shared name raises.""" x = Parameter("p") y = Parameter("p") # Expression of the same Parameter are valid. _ = x + x _ = x - x _ = x * x _ = x / x with self.assertRaises(CircuitError): _ = x + y with self.assertRaises(CircuitError): _ = x - y with self.assertRaises(CircuitError): _ = x * y with self.assertRaises(CircuitError): _ = x / y @combine(target_type=["gate", "instruction"], order=["bind-decompose", "decompose-bind"]) def test_to_instruction_with_expression(self, target_type, order): """Test preservation of expressions via parameterized instructions. ┌───────┐┌──────────┐┌───────────┐ qr1_0: |0>┤ Rx(θ) ├┤ Rz(pi/2) ├┤ Ry(phi*θ) ├ └───────┘└──────────┘└───────────┘ ┌───────────┐ qr2_0: |0>───┤ Ry(delta) ├─── ┌──┴───────────┴──┐ qr2_1: |0>┤ Circuit0(phi,θ) ├ └─────────────────┘ qr2_2: |0>─────────────────── """ theta = Parameter("θ") phi = Parameter("phi") qr1 = QuantumRegister(1, name="qr1") qc1 = QuantumCircuit(qr1) qc1.rx(theta, qr1) qc1.rz(numpy.pi / 2, qr1) qc1.ry(theta * phi, qr1) if target_type == "gate": gate = qc1.to_gate() elif target_type == "instruction": gate = qc1.to_instruction() self.assertEqual(gate.params, [phi, theta]) delta = Parameter("delta") qr2 = QuantumRegister(3, name="qr2") qc2 = QuantumCircuit(qr2) qc2.ry(delta, qr2[0]) qc2.append(gate, qargs=[qr2[1]]) self.assertEqual(qc2.parameters, {delta, theta, phi}) binds = {delta: 1, theta: 2, phi: 3} expected_qc = QuantumCircuit(qr2) expected_qc.rx(2, 1) expected_qc.rz(numpy.pi / 2, 1) expected_qc.ry(3 * 2, 1) expected_qc.r(1, numpy.pi / 2, 0) if order == "bind-decompose": decomp_bound_qc = qc2.assign_parameters(binds).decompose() elif order == "decompose-bind": decomp_bound_qc = qc2.decompose().assign_parameters(binds) self.assertEqual(decomp_bound_qc.parameters, set()) self.assertEqual(decomp_bound_qc, expected_qc) @combine(target_type=["gate", "instruction"], order=["bind-decompose", "decompose-bind"]) def test_to_instruction_expression_parameter_map(self, target_type, order): """Test preservation of expressions via instruction parameter_map.""" theta = Parameter("θ") phi = Parameter("phi") qr1 = QuantumRegister(1, name="qr1") qc1 = QuantumCircuit(qr1) qc1.rx(theta, qr1) qc1.rz(numpy.pi / 2, qr1) qc1.ry(theta * phi, qr1) theta_p = Parameter("theta") phi_p = Parameter("phi") if target_type == "gate": gate = qc1.to_gate(parameter_map={theta: theta_p, phi: phi_p}) elif target_type == "instruction": gate = qc1.to_instruction(parameter_map={theta: theta_p, phi: phi_p}) self.assertListEqual(gate.params, [theta_p, phi_p]) delta = Parameter("delta") qr2 = QuantumRegister(3, name="qr2") qc2 = QuantumCircuit(qr2) qc2.ry(delta, qr2[0]) qc2.append(gate, qargs=[qr2[1]]) self.assertListEqual(list(qc2.parameters), [delta, phi_p, theta_p]) binds = {delta: 1, theta_p: 2, phi_p: 3} expected_qc = QuantumCircuit(qr2) expected_qc.rx(2, 1) expected_qc.rz(numpy.pi / 2, 1) expected_qc.ry(3 * 2, 1) expected_qc.r(1, numpy.pi / 2, 0) if order == "bind-decompose": decomp_bound_qc = qc2.assign_parameters(binds).decompose() elif order == "decompose-bind": decomp_bound_qc = qc2.decompose().assign_parameters(binds) self.assertEqual(decomp_bound_qc.parameters, set()) self.assertEqual(decomp_bound_qc, expected_qc) def test_binding_across_broadcast_instruction(self): """Bind a parameter which was included via a broadcast instruction.""" # ref: https://github.com/Qiskit/qiskit-terra/issues/3008 theta = Parameter("θ") n = 5 qc = QuantumCircuit(n, 1) qc.h(0) for i in range(n - 1): qc.cx(i, i + 1) qc.barrier() qc.rz(theta, range(n)) qc.barrier() for i in reversed(range(n - 1)): qc.cx(i, i + 1) qc.h(0) qc.measure(0, 0) theta_range = numpy.linspace(0, 2 * numpy.pi, 128) circuits = [qc.assign_parameters({theta: theta_val}) for theta_val in theta_range] self.assertEqual(len(circuits), len(theta_range)) for theta_val, bound_circ in zip(theta_range, circuits): rz_gates = [ inst.operation for inst in bound_circ.data if isinstance(inst.operation, RZGate) ] self.assertEqual(len(rz_gates), n) self.assertTrue(all(float(gate.params[0]) == theta_val for gate in rz_gates)) def test_substituting_parameter_with_simple_expression(self): """Substitute a simple parameter expression for a parameter.""" x = Parameter("x") y = Parameter("y") sub_ = y / 2 updated_expr = x.subs({x: sub_}) expected = y / 2 self.assertEqual(updated_expr, expected) def test_substituting_parameter_with_compound_expression(self): """Substitute a simple parameter expression for a parameter.""" x = Parameter("x") y = Parameter("y") z = Parameter("z") sub_ = y * z updated_expr = x.subs({x: sub_}) expected = y * z self.assertEqual(updated_expr, expected) def test_substituting_simple_with_simple_expression(self): """Substitute a simple parameter expression in a parameter expression.""" x = Parameter("x") expr = x * x y = Parameter("y") sub_ = y / 2 updated_expr = expr.subs({x: sub_}) expected = y * y / 4 self.assertEqual(updated_expr, expected) def test_substituting_compound_expression(self): """Substitute a compound parameter expression in a parameter expression.""" x = Parameter("x") expr = x * x y = Parameter("y") z = Parameter("z") sub_ = y + z updated_expr = expr.subs({x: sub_}) expected = (y + z) * (y + z) self.assertEqual(updated_expr, expected) def test_conjugate(self): """Test calling conjugate on a ParameterExpression.""" x = Parameter("x") self.assertEqual((x.conjugate() + 1j), (x - 1j).conjugate()) @data( circlib.RGate, circlib.RXGate, circlib.RYGate, circlib.RZGate, circlib.RXXGate, circlib.RYYGate, circlib.RZXGate, circlib.RZZGate, circlib.CRXGate, circlib.CRYGate, circlib.CRZGate, circlib.XXPlusYYGate, ) def test_bound_gate_to_matrix(self, gate_class): """Test to_matrix works if previously free parameters are bound. The conversion might fail, if trigonometric functions such as cos are called on the parameters and the parameters are still of type ParameterExpression. """ num_parameters = 2 if gate_class == circlib.RGate else 1 params = list(range(1, 1 + num_parameters)) free_params = ParameterVector("th", num_parameters) gate = gate_class(*params) num_qubits = gate.num_qubits circuit = QuantumCircuit(num_qubits) circuit.append(gate_class(*free_params), list(range(num_qubits))) bound_circuit = circuit.assign_parameters({free_params: params}) numpy.testing.assert_array_almost_equal(Operator(bound_circuit).data, gate.to_matrix()) def test_parameter_expression_grad(self): """Verify correctness of ParameterExpression gradients.""" x = Parameter("x") y = Parameter("y") z = Parameter("z") with self.subTest(msg="first order gradient"): expr = (x + y) * z self.assertEqual(expr.gradient(x), z) self.assertEqual(expr.gradient(z), (x + y)) with self.subTest(msg="second order gradient"): expr = x * x self.assertEqual(expr.gradient(x), 2 * x) self.assertEqual(expr.gradient(x).gradient(x), 2) def test_bound_expression_is_real(self): """Test is_real on bound parameters.""" x = Parameter("x") self.assertEqual(x.is_real(), None) self.assertEqual((1j * x).is_real(), None) expr = 1j * x bound = expr.bind({x: 2}) self.assertEqual(bound.is_real(), False) bound = x.bind({x: 0 + 0j}) self.assertEqual(bound.is_real(), True) bound = x.bind({x: 0 + 1j}) self.assertEqual(bound.is_real(), False) bound = x.bind({x: 1 + 0j}) self.assertEqual(bound.is_real(), True) bound = x.bind({x: 1 + 1j}) self.assertEqual(bound.is_real(), False) class TestParameterEquality(QiskitTestCase): """Test equality of Parameters and ParameterExpressions.""" def test_parameter_equal_self(self): """Verify a parameter is equal to it self.""" theta = Parameter("theta") self.assertEqual(theta, theta) def test_parameter_not_equal_param_of_same_name(self): """Verify a parameter is not equal to a Parameter of the same name.""" theta1 = Parameter("theta") theta2 = Parameter("theta") self.assertNotEqual(theta1, theta2) def test_parameter_expression_equal_to_self(self): """Verify an expression is equal to itself.""" theta = Parameter("theta") expr = 2 * theta self.assertEqual(expr, expr) def test_parameter_expression_equal_to_identical(self): """Verify an expression is equal an identical expression.""" theta = Parameter("theta") expr1 = 2 * theta expr2 = 2 * theta self.assertEqual(expr1, expr2) def test_parameter_expression_equal_floats_to_ints(self): """Verify an expression with float and int is identical.""" theta = Parameter("theta") expr1 = 2.0 * theta expr2 = 2 * theta self.assertEqual(expr1, expr2) def test_parameter_expression_not_equal_if_params_differ(self): """Verify expressions not equal if parameters are different.""" theta1 = Parameter("theta") theta2 = Parameter("theta") expr1 = 2 * theta1 expr2 = 2 * theta2 self.assertNotEqual(expr1, expr2) def test_parameter_equal_to_identical_expression(self): """Verify parameters and ParameterExpressions can be equal if identical.""" theta = Parameter("theta") phi = Parameter("phi") expr = (theta + phi).bind({phi: 0}) self.assertEqual(expr, theta) self.assertEqual(theta, expr) def test_parameter_symbol_equal_after_ufunc(self): """Verfiy ParameterExpression phi and ParameterExpression cos(phi) have the same symbol map""" phi = Parameter("phi") cos_phi = numpy.cos(phi) self.assertEqual(phi._parameter_symbols, cos_phi._parameter_symbols) class TestParameterReferences(QiskitTestCase): """Test the ParameterReferences class.""" def test_equal_inst_diff_instance(self): """Different value equal instructions are treated as distinct.""" theta = Parameter("theta") gate1 = RZGate(theta) gate2 = RZGate(theta) self.assertIsNot(gate1, gate2) self.assertEqual(gate1, gate2) refs = ParameterReferences(((gate1, 0), (gate2, 0))) # test __contains__ self.assertIn((gate1, 0), refs) self.assertIn((gate2, 0), refs) gate_ids = {id(gate1), id(gate2)} self.assertEqual(gate_ids, {id(gate) for gate, _ in refs}) self.assertTrue(all(idx == 0 for _, idx in refs)) def test_pickle_unpickle(self): """Membership testing after pickle/unpickle.""" theta = Parameter("theta") gate1 = RZGate(theta) gate2 = RZGate(theta) self.assertIsNot(gate1, gate2) self.assertEqual(gate1, gate2) refs = ParameterReferences(((gate1, 0), (gate2, 0))) to_pickle = (gate1, refs) pickled = pickle.dumps(to_pickle) (gate1_new, refs_new) = pickle.loads(pickled) self.assertEqual(len(refs_new), len(refs)) self.assertNotIn((gate1, 0), refs_new) self.assertIn((gate1_new, 0), refs_new) def test_equal_inst_same_instance(self): """Referentially equal instructions are treated as same.""" theta = Parameter("theta") gate = RZGate(theta) refs = ParameterReferences(((gate, 0), (gate, 0))) self.assertIn((gate, 0), refs) self.assertEqual(len(refs), 1) self.assertIs(next(iter(refs))[0], gate) self.assertEqual(next(iter(refs))[1], 0) def test_extend_refs(self): """Extending references handles duplicates.""" theta = Parameter("theta") ref0 = (RZGate(theta), 0) ref1 = (RZGate(theta), 0) ref2 = (RZGate(theta), 0) refs = ParameterReferences((ref0,)) refs |= ParameterReferences((ref0, ref1, ref2, ref1, ref0)) self.assertEqual(refs, ParameterReferences((ref0, ref1, ref2))) def test_copy_param_refs(self): """Copy of parameter references is a shallow copy.""" theta = Parameter("theta") ref0 = (RZGate(theta), 0) ref1 = (RZGate(theta), 0) ref2 = (RZGate(theta), 0) ref3 = (RZGate(theta), 0) refs = ParameterReferences((ref0, ref1)) refs_copy = refs.copy() # Check same gate instances in copy gate_ids = {id(ref0[0]), id(ref1[0])} self.assertEqual({id(gate) for gate, _ in refs_copy}, gate_ids) # add new ref to original and check copy not modified refs.add(ref2) self.assertNotIn(ref2, refs_copy) self.assertEqual(refs_copy, ParameterReferences((ref0, ref1))) # add new ref to copy and check original not modified refs_copy.add(ref3) self.assertNotIn(ref3, refs) self.assertEqual(refs, ParameterReferences((ref0, ref1, ref2))) class TestParameterTable(QiskitTestCase): """Test the ParameterTable class.""" def test_init_param_table(self): """Parameter table init from mapping.""" p1 = Parameter("theta") p2 = Parameter("theta") ref0 = (RZGate(p1), 0) ref1 = (RZGate(p1), 0) ref2 = (RZGate(p2), 0) mapping = {p1: ParameterReferences((ref0, ref1)), p2: ParameterReferences((ref2,))} table = ParameterTable(mapping) # make sure editing mapping doesn't change `table` del mapping[p1] self.assertEqual(table[p1], ParameterReferences((ref0, ref1))) self.assertEqual(table[p2], ParameterReferences((ref2,))) def test_set_references(self): """References replacement by parameter key.""" p1 = Parameter("theta") ref0 = (RZGate(p1), 0) ref1 = (RZGate(p1), 0) table = ParameterTable() table[p1] = ParameterReferences((ref0, ref1)) self.assertEqual(table[p1], ParameterReferences((ref0, ref1))) table[p1] = ParameterReferences((ref1,)) self.assertEqual(table[p1], ParameterReferences((ref1,))) def test_set_references_from_iterable(self): """Parameter table init from iterable.""" p1 = Parameter("theta") ref0 = (RZGate(p1), 0) ref1 = (RZGate(p1), 0) ref2 = (RZGate(p1), 0) table = ParameterTable({p1: ParameterReferences((ref0, ref1))}) table[p1] = (ref2, ref1, ref0) self.assertEqual(table[p1], ParameterReferences((ref2, ref1, ref0))) class TestParameterView(QiskitTestCase): """Test the ParameterView object.""" def setUp(self): super().setUp() x, y, z = Parameter("x"), Parameter("y"), Parameter("z") self.params = [x, y, z] self.view1 = ParameterView([x, y]) self.view2 = ParameterView([y, z]) self.view3 = ParameterView([x]) def test_and(self): """Test __and__.""" self.assertEqual(self.view1 & self.view2, {self.params[1]}) def test_or(self): """Test __or__.""" self.assertEqual(self.view1 | self.view2, set(self.params)) def test_xor(self): """Test __xor__.""" self.assertEqual(self.view1 ^ self.view2, {self.params[0], self.params[2]}) def test_len(self): """Test __len__.""" self.assertEqual(len(self.view1), 2) def test_le(self): """Test __le__.""" self.assertTrue(self.view1 <= self.view1) self.assertFalse(self.view1 <= self.view3) def test_lt(self): """Test __lt__.""" self.assertTrue(self.view3 < self.view1) def test_ge(self): """Test __ge__.""" self.assertTrue(self.view1 >= self.view1) self.assertFalse(self.view3 >= self.view1) def test_gt(self): """Test __lt__.""" self.assertTrue(self.view1 > self.view3) def test_eq(self): """Test __eq__.""" self.assertTrue(self.view1 == self.view1) self.assertFalse(self.view3 == self.view1) def test_ne(self): """Test __eq__.""" self.assertTrue(self.view1 != self.view2) self.assertFalse(self.view3 != self.view3) if __name__ == "__main__": unittest.main()
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test registerless QuantumCircuit and Gates on wires""" import numpy from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.circuit import Qubit, Clbit, AncillaQubit from qiskit.circuit.exceptions import CircuitError from qiskit.test import QiskitTestCase class TestRegisterlessCircuit(QiskitTestCase): """Test registerless QuantumCircuit.""" def test_circuit_constructor_qwires(self): """Create a QuantumCircuit directly with quantum wires""" circuit = QuantumCircuit(2) expected = QuantumCircuit(QuantumRegister(2, "q")) self.assertEqual(circuit, expected) def test_circuit_constructor_wires_wrong(self): """Create a registerless QuantumCircuit wrongly""" self.assertRaises(CircuitError, QuantumCircuit, 1, 2, 3) # QuantumCircuit(1, 2, 3) def test_circuit_constructor_wires_wrong_mix(self): """Create an almost-registerless QuantumCircuit""" # QuantumCircuit(1, ClassicalRegister(2)) self.assertRaises(CircuitError, QuantumCircuit, 1, ClassicalRegister(2)) class TestAddingBitsWithoutRegisters(QiskitTestCase): """Test adding Bit instances outside of Registers.""" def test_circuit_constructor_on_bits(self): """Verify we can add bits directly to a circuit.""" qubits = [Qubit(), Qubit()] clbits = [Clbit()] ancillas = [AncillaQubit(), AncillaQubit()] qc = QuantumCircuit(qubits, clbits, ancillas) self.assertEqual(qc.qubits, qubits + ancillas) self.assertEqual(qc.clbits, clbits) self.assertEqual(qc.ancillas, ancillas) self.assertEqual(qc.qregs, []) self.assertEqual(qc.cregs, []) def test_circuit_constructor_on_invalid_bits(self): """Verify we raise if passed not a Bit.""" with self.assertRaisesRegex(CircuitError, "Expected an instance of"): _ = QuantumCircuit([3.14]) def test_raise_if_bits_already_present(self): """Verify we raise when attempting to add a Bit already in the circuit.""" qubits = [Qubit()] with self.assertRaisesRegex(CircuitError, "bits found already"): _ = QuantumCircuit(qubits, qubits) qc = QuantumCircuit(qubits) with self.assertRaisesRegex(CircuitError, "bits found already"): qc.add_bits(qubits) qr = QuantumRegister(1, "qr") qc = QuantumCircuit(qr) with self.assertRaisesRegex(CircuitError, "bits found already"): qc.add_bits(qr[:]) def test_addding_individual_bit(self): """Verify we can add a single bit to a circuit.""" qr = QuantumRegister(3, "qr") qc = QuantumCircuit(qr) new_bit = Qubit() qc.add_bits([new_bit]) self.assertEqual(qc.qubits, list(qr) + [new_bit]) self.assertEqual(qc.qregs, [qr]) def test_inserted_ancilla_bits_are_added_to_qubits(self): """Verify AncillaQubits added via .add_bits are added to .qubits.""" anc = AncillaQubit() qb = Qubit() qc = QuantumCircuit() qc.add_bits([anc, qb]) self.assertEqual(qc.qubits, [anc, qb]) class TestGatesOnWires(QiskitTestCase): """Test gates on wires.""" def test_circuit_single_wire_h(self): """Test circuit on wire (H gate).""" qreg = QuantumRegister(2) circuit = QuantumCircuit(qreg) circuit.h(1) expected = QuantumCircuit(qreg) expected.h(qreg[1]) self.assertEqual(circuit, expected) def test_circuit_two_wire_cx(self): """Test circuit two wires (CX gate).""" qreg = QuantumRegister(2) expected = QuantumCircuit(qreg) expected.cx(qreg[0], qreg[1]) circuit = QuantumCircuit(qreg) circuit.cx(0, 1) self.assertEqual(circuit, expected) def test_circuit_single_wire_measure(self): """Test circuit on wire (measure gate).""" qreg = QuantumRegister(2) creg = ClassicalRegister(2) circuit = QuantumCircuit(qreg, creg) circuit.measure(1, 1) expected = QuantumCircuit(qreg, creg) expected.measure(qreg[1], creg[1]) self.assertEqual(circuit, expected) def test_circuit_multi_qregs_h(self): """Test circuit multi qregs and wires (H gate).""" qreg0 = QuantumRegister(2) qreg1 = QuantumRegister(2) circuit = QuantumCircuit(qreg0, qreg1) circuit.h(0) circuit.h(2) expected = QuantumCircuit(qreg0, qreg1) expected.h(qreg0[0]) expected.h(qreg1[0]) self.assertEqual(circuit, expected) def test_circuit_multi_qreg_cregs_measure(self): """Test circuit multi qregs/cregs and wires (measure).""" qreg0 = QuantumRegister(2) creg0 = ClassicalRegister(2) qreg1 = QuantumRegister(2) creg1 = ClassicalRegister(2) circuit = QuantumCircuit(qreg0, qreg1, creg0, creg1) circuit.measure(0, 2) circuit.measure(2, 1) expected = QuantumCircuit(qreg0, qreg1, creg0, creg1) expected.measure(qreg0[0], creg1[0]) expected.measure(qreg1[0], creg0[1]) self.assertEqual(circuit, expected) def test_circuit_barrier(self): """Test barrier on wires.""" qreg01 = QuantumRegister(2) qreg23 = QuantumRegister(2) circuit = QuantumCircuit(qreg01, qreg23) circuit.barrier(0) circuit.barrier(2) expected = QuantumCircuit(qreg01, qreg23) expected.barrier(qreg01[0]) expected.barrier(qreg23[0]) self.assertEqual(circuit, expected) def test_circuit_conditional(self): """Test conditional on wires.""" qreg = QuantumRegister(2) creg = ClassicalRegister(4) circuit = QuantumCircuit(qreg, creg) circuit.h(0).c_if(creg, 3) expected = QuantumCircuit(qreg, creg) expected.h(qreg[0]).c_if(creg, 3) self.assertEqual(circuit, expected) def test_circuit_qwire_out_of_range(self): """Fail if quantum wire is out of range.""" qreg = QuantumRegister(2) circuit = QuantumCircuit(qreg) self.assertRaises(CircuitError, circuit.h, 99) # circuit.h(99) def test_circuit_cwire_out_of_range(self): """Fail if classical wire is out of range.""" qreg = QuantumRegister(2) creg = ClassicalRegister(2) circuit = QuantumCircuit(qreg, creg) self.assertRaises(CircuitError, circuit.measure, 1, 99) # circuit.measure(1, 99) def test_circuit_initialize(self): """Test initialize on wires.""" init_vector = [0.5, 0.5, 0.5, 0.5] qreg01 = QuantumRegister(2) qreg23 = QuantumRegister(2) circuit = QuantumCircuit(qreg01, qreg23) circuit.initialize(init_vector, [0, 2]) expected = QuantumCircuit(qreg01, qreg23) expected.initialize(init_vector, [qreg01[0], qreg23[0]]) self.assertEqual(circuit, expected) def test_circuit_initialize_single_qubit(self): """Test initialize on single qubit.""" init_vector = [numpy.sqrt(0.5), numpy.sqrt(0.5)] qreg = QuantumRegister(2) circuit = QuantumCircuit(qreg) circuit.initialize(init_vector, qreg[0]) expected = QuantumCircuit(qreg) expected.initialize(init_vector, [qreg[0]]) self.assertEqual(circuit, expected) def test_mixed_register_and_registerless_indexing(self): """Test indexing if circuit contains bits in and out of registers.""" bits = [Qubit(), Qubit()] qreg = QuantumRegister(3, "q") circuit = QuantumCircuit(bits, qreg) for i in range(len(circuit.qubits)): circuit.rz(i, i) expected_qubit_order = bits + qreg[:] expected_circuit = QuantumCircuit(bits, qreg) for i in range(len(expected_circuit.qubits)): expected_circuit.rz(i, expected_qubit_order[i]) self.assertEqual(circuit.data, expected_circuit.data) class TestGatesOnWireRange(QiskitTestCase): """Test gates on wire range.""" def test_wire_range(self): """Test gate wire range""" qreg = QuantumRegister(4) circuit = QuantumCircuit(qreg) circuit.h(range(0, 2)) expected = QuantumCircuit(qreg) expected.h(qreg[0:2]) self.assertEqual(circuit, expected) def test_circuit_multi_qregs_h(self): """Test circuit multi qregs in range of wires (H gate).""" qreg0 = QuantumRegister(2) qreg1 = QuantumRegister(2) circuit = QuantumCircuit(qreg0, qreg1) circuit.h(range(0, 3)) expected = QuantumCircuit(qreg0, qreg1) expected.h(qreg0[0]) expected.h(qreg0[1]) expected.h(qreg1[0]) self.assertEqual(circuit, expected) def test_circuit_multi_qreg_cregs_measure(self): """Test circuit multi qregs in range of wires (measure).""" qreg0 = QuantumRegister(2) creg0 = ClassicalRegister(2) qreg1 = QuantumRegister(2) creg1 = ClassicalRegister(2) circuit = QuantumCircuit(qreg0, qreg1, creg0, creg1) circuit.measure(range(1, 3), range(0, 4, 2)) expected = QuantumCircuit(qreg0, qreg1, creg0, creg1) expected.measure(qreg0[1], creg0[0]) expected.measure(qreg1[0], creg1[0]) self.assertEqual(circuit, expected) def test_circuit_barrier(self): """Test barrier on range of wires with multi regs.""" qreg01 = QuantumRegister(2) qreg23 = QuantumRegister(2) circuit = QuantumCircuit(qreg01, qreg23) circuit.barrier(range(0, 3)) expected = QuantumCircuit(qreg01, qreg23) expected.barrier(qreg01[0], qreg01[1], qreg23[0]) self.assertEqual(circuit, expected) def test_circuit_initialize(self): """Test initialize on wires.""" init_vector = [0.5, 0.5, 0.5, 0.5] qreg01 = QuantumRegister(2) qreg23 = QuantumRegister(2) circuit = QuantumCircuit(qreg01, qreg23) circuit.initialize(init_vector, range(1, 3)) expected = QuantumCircuit(qreg01, qreg23) expected.initialize(init_vector, [qreg01[1], qreg23[0]]) self.assertEqual(circuit, expected) def test_circuit_conditional(self): """Test conditional on wires.""" qreg0 = QuantumRegister(2) qreg1 = QuantumRegister(2) creg = ClassicalRegister(2) circuit = QuantumCircuit(qreg0, qreg1, creg) circuit.h(range(1, 3)).c_if(creg, 3) expected = QuantumCircuit(qreg0, qreg1, creg) expected.h(qreg0[1]).c_if(creg, 3) expected.h(qreg1[0]).c_if(creg, 3) self.assertEqual(circuit, expected) def test_circuit_qwire_out_of_range(self): """Fail if quantum wire is out of range.""" qreg = QuantumRegister(2) circuit = QuantumCircuit(qreg) self.assertRaises(CircuitError, circuit.h, range(9, 99)) # circuit.h(range(9,99)) def test_circuit_cwire_out_of_range(self): """Fail if classical wire is out of range.""" qreg = QuantumRegister(2) creg = ClassicalRegister(2) circuit = QuantumCircuit(qreg, creg) # circuit.measure(1, range(9,99)) self.assertRaises(CircuitError, circuit.measure, 1, range(9, 99)) class TestGatesOnWireSlice(QiskitTestCase): """Test gates on wire slice.""" def test_wire_slice(self): """Test gate wire slice""" qreg = QuantumRegister(4) circuit = QuantumCircuit(qreg) circuit.h(slice(0, 2)) expected = QuantumCircuit(qreg) expected.h(qreg[0:2]) self.assertEqual(circuit, expected) def test_wire_list(self): """Test gate wire list of integers""" qreg = QuantumRegister(4) circuit = QuantumCircuit(qreg) circuit.h([0, 1]) expected = QuantumCircuit(qreg) expected.h(qreg[0:2]) self.assertEqual(circuit, expected) def test_wire_np_int(self): """Test gate wire with numpy int""" numpy_int = numpy.dtype("int").type(2) qreg = QuantumRegister(4) circuit = QuantumCircuit(qreg) circuit.h(numpy_int) expected = QuantumCircuit(qreg) expected.h(qreg[2]) self.assertEqual(circuit, expected) def test_wire_np_1d_array(self): """Test gate wire with numpy array (one-dimensional)""" numpy_arr = numpy.array([0, 1]) qreg = QuantumRegister(4) circuit = QuantumCircuit(qreg) circuit.h(numpy_arr) expected = QuantumCircuit(qreg) expected.h(qreg[0]) expected.h(qreg[1]) self.assertEqual(circuit, expected) def test_circuit_multi_qregs_h(self): """Test circuit multi qregs in slices of wires (H gate).""" qreg0 = QuantumRegister(2) qreg1 = QuantumRegister(2) circuit = QuantumCircuit(qreg0, qreg1) circuit.h(slice(0, 3)) expected = QuantumCircuit(qreg0, qreg1) expected.h(qreg0[0]) expected.h(qreg0[1]) expected.h(qreg1[0]) self.assertEqual(circuit, expected) def test_circuit_multi_qreg_cregs_measure(self): """Test circuit multi qregs in slices of wires (measure).""" qreg0 = QuantumRegister(2) creg0 = ClassicalRegister(2) qreg1 = QuantumRegister(2) creg1 = ClassicalRegister(2) circuit = QuantumCircuit(qreg0, qreg1, creg0, creg1) circuit.measure(slice(1, 3), slice(0, 4, 2)) expected = QuantumCircuit(qreg0, qreg1, creg0, creg1) expected.measure(qreg0[1], creg0[0]) expected.measure(qreg1[0], creg1[0]) self.assertEqual(circuit, expected) def test_circuit_barrier(self): """Test barrier on slice of wires with multi regs.""" qreg01 = QuantumRegister(2) qreg23 = QuantumRegister(2) circuit = QuantumCircuit(qreg01, qreg23) circuit.barrier(slice(0, 3)) expected = QuantumCircuit(qreg01, qreg23) expected.barrier([qreg01[0], qreg01[1], qreg23[0]]) self.assertEqual(circuit, expected) def test_circuit_initialize(self): """Test initialize on wires.""" init_vector = [0.5, 0.5, 0.5, 0.5] qreg01 = QuantumRegister(2) qreg23 = QuantumRegister(2) circuit = QuantumCircuit(qreg01, qreg23) circuit.initialize(init_vector, slice(1, 3)) expected = QuantumCircuit(qreg01, qreg23) expected.initialize(init_vector, [qreg01[1], qreg23[0]]) self.assertEqual(circuit, expected) def test_circuit_conditional(self): """Test conditional on wires.""" qreg0 = QuantumRegister(2) qreg1 = QuantumRegister(2) creg = ClassicalRegister(2) circuit = QuantumCircuit(qreg0, qreg1, creg) circuit.h(slice(1, 3)).c_if(creg, 3) expected = QuantumCircuit(qreg0, qreg1, creg) expected.h(qreg0[1]).c_if(creg, 3) expected.h(qreg1[0]).c_if(creg, 3) self.assertEqual(circuit, expected) def test_circuit_qwire_out_of_range(self): """Fail if quantum wire is out of range.""" qreg = QuantumRegister(2) circuit = QuantumCircuit(qreg) self.assertRaises(CircuitError, circuit.h, slice(9, 99)) # circuit.h(slice(9,99)) def test_circuit_cwire_out_of_range(self): """Fail if classical wire is out of range.""" qreg = QuantumRegister(2) creg = ClassicalRegister(2) circuit = QuantumCircuit(qreg, creg) # circuit.measure(1, slice(9,99)) self.assertRaises(CircuitError, circuit.measure, 1, slice(9, 99)) def test_wire_np_2d_array(self): """Test gate wire with numpy array (two-dimensional). Raises.""" numpy_arr = numpy.array([[0, 1], [2, 3]]) qreg = QuantumRegister(4) circuit = QuantumCircuit(qreg) self.assertRaises(CircuitError, circuit.h, numpy_arr) # circuit.h(numpy_arr) class TestBitConditional(QiskitTestCase): """Test gates with single bit conditionals.""" def test_bit_conditional_single_gate(self): """Test circuit with a single gate conditioned on a bit.""" qreg = QuantumRegister(1) creg = ClassicalRegister(2) circuit = QuantumCircuit(qreg, creg) circuit.h(0).c_if(0, True) expected = QuantumCircuit(qreg, creg) expected.h(qreg[0]).c_if(creg[0], True) self.assertEqual(circuit, expected) def test_bit_conditional_multiple_gates(self): """Test circuit with multiple gates conditioned on individual bits.""" qreg = QuantumRegister(2) creg = ClassicalRegister(2) creg1 = ClassicalRegister(1) circuit = QuantumCircuit(qreg, creg, creg1) circuit.h(0).c_if(0, True) circuit.h(1).c_if(1, False) circuit.cx(1, 0).c_if(2, True) expected = QuantumCircuit(qreg, creg, creg1) expected.h(qreg[0]).c_if(creg[0], True) expected.h(qreg[1]).c_if(creg[1], False) expected.cx(qreg[1], qreg[0]).c_if(creg1[0], True) self.assertEqual(circuit, expected)
https://github.com/swe-train/qiskit__qiskit
swe-train
# 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=missing-function-docstring """Test scheduled circuit (quantum circuit with duration).""" from ddt import ddt, data from qiskit import QuantumCircuit, QiskitError from qiskit import transpile, assemble, BasicAer from qiskit.circuit import Parameter from qiskit.providers.fake_provider import FakeParis from qiskit.transpiler.exceptions import TranspilerError from qiskit.transpiler.instruction_durations import InstructionDurations from qiskit.test.base import QiskitTestCase @ddt class TestScheduledCircuit(QiskitTestCase): """Test scheduled circuit (quantum circuit with duration).""" def setUp(self): super().setUp() self.backend_with_dt = FakeParis() self.backend_without_dt = FakeParis() delattr(self.backend_without_dt.configuration(), "dt") self.dt = 2.2222222222222221e-10 self.simulator_backend = BasicAer.get_backend("qasm_simulator") def test_schedule_circuit_when_backend_tells_dt(self): """dt is known to transpiler by backend""" qc = QuantumCircuit(2) qc.delay(0.1, 0, unit="ms") # 450000[dt] qc.delay(100, 0, unit="ns") # 450[dt] qc.h(0) # 160[dt] qc.h(1) # 160[dt] sc = transpile(qc, self.backend_with_dt, scheduling_method="alap", layout_method="trivial") self.assertEqual(sc.duration, 450610) self.assertEqual(sc.unit, "dt") self.assertEqual(sc.data[0].operation.name, "delay") self.assertEqual(sc.data[0].operation.duration, 450450) self.assertEqual(sc.data[0].operation.unit, "dt") self.assertEqual(sc.data[1].operation.name, "rz") self.assertEqual(sc.data[1].operation.duration, 0) self.assertEqual(sc.data[1].operation.unit, "dt") self.assertEqual(sc.data[4].operation.name, "delay") self.assertEqual(sc.data[4].operation.duration, 450450) self.assertEqual(sc.data[4].operation.unit, "dt") qobj = assemble(sc, self.backend_with_dt) self.assertEqual(qobj.experiments[0].instructions[0].name, "delay") self.assertEqual(qobj.experiments[0].instructions[0].params[0], 450450) self.assertEqual(qobj.experiments[0].instructions[4].name, "delay") self.assertEqual(qobj.experiments[0].instructions[4].params[0], 450450) def test_schedule_circuit_when_transpile_option_tells_dt(self): """dt is known to transpiler by transpile option""" qc = QuantumCircuit(2) qc.delay(0.1, 0, unit="ms") # 450000[dt] qc.delay(100, 0, unit="ns") # 450[dt] qc.h(0) qc.h(1) sc = transpile( qc, self.backend_without_dt, scheduling_method="alap", dt=self.dt, layout_method="trivial", ) self.assertEqual(sc.duration, 450610) self.assertEqual(sc.unit, "dt") self.assertEqual(sc.data[0].operation.name, "delay") self.assertEqual(sc.data[0].operation.duration, 450450) self.assertEqual(sc.data[0].operation.unit, "dt") self.assertEqual(sc.data[1].operation.name, "rz") self.assertEqual(sc.data[1].operation.duration, 0) self.assertEqual(sc.data[1].operation.unit, "dt") self.assertEqual(sc.data[4].operation.name, "delay") self.assertEqual(sc.data[4].operation.duration, 450450) self.assertEqual(sc.data[4].operation.unit, "dt") def test_schedule_circuit_in_sec_when_no_one_tells_dt(self): """dt is unknown and all delays and gate times are in SI""" qc = QuantumCircuit(2) qc.delay(0.1, 0, unit="ms") qc.delay(100, 0, unit="ns") qc.h(0) qc.h(1) sc = transpile( qc, self.backend_without_dt, scheduling_method="alap", layout_method="trivial" ) self.assertAlmostEqual(sc.duration, 450610 * self.dt) self.assertEqual(sc.unit, "s") self.assertEqual(sc.data[0].operation.name, "delay") self.assertAlmostEqual(sc.data[0].operation.duration, 1.0e-4 + 1.0e-7) self.assertEqual(sc.data[0].operation.unit, "s") self.assertEqual(sc.data[1].operation.name, "rz") self.assertAlmostEqual(sc.data[1].operation.duration, 160 * self.dt) self.assertEqual(sc.data[1].operation.unit, "s") self.assertEqual(sc.data[4].operation.name, "delay") self.assertAlmostEqual(sc.data[4].operation.duration, 1.0e-4 + 1.0e-7) self.assertEqual(sc.data[4].operation.unit, "s") with self.assertRaises(QiskitError): assemble(sc, self.backend_without_dt) def test_cannot_schedule_circuit_with_mixed_SI_and_dt_when_no_one_tells_dt(self): """dt is unknown but delays and gate times have a mix of SI and dt""" qc = QuantumCircuit(2) qc.delay(100, 0, unit="ns") qc.delay(30, 0, unit="dt") qc.h(0) qc.h(1) with self.assertRaises(QiskitError): transpile(qc, self.backend_without_dt, scheduling_method="alap") def test_transpile_single_delay_circuit(self): qc = QuantumCircuit(1) qc.delay(1234, 0) sc = transpile(qc, backend=self.backend_with_dt, scheduling_method="alap") self.assertEqual(sc.duration, 1234) self.assertEqual(sc.data[0].operation.name, "delay") self.assertEqual(sc.data[0].operation.duration, 1234) self.assertEqual(sc.data[0].operation.unit, "dt") def test_transpile_t1_circuit(self): qc = QuantumCircuit(1) qc.x(0) # 320 [dt] qc.delay(1000, 0, unit="ns") # 4500 [dt] qc.measure_all() # 19584 [dt] scheduled = transpile(qc, backend=self.backend_with_dt, scheduling_method="alap") self.assertEqual(scheduled.duration, 23060) def test_transpile_delay_circuit_with_backend(self): qc = QuantumCircuit(2) qc.h(0) qc.delay(100, 1, unit="ns") # 450 [dt] qc.cx(0, 1) # 1760 [dt] scheduled = transpile( qc, backend=self.backend_with_dt, scheduling_method="alap", layout_method="trivial" ) self.assertEqual(scheduled.duration, 2082) def test_transpile_delay_circuit_without_backend(self): qc = QuantumCircuit(2) qc.h(0) qc.delay(500, 1) qc.cx(0, 1) scheduled = transpile( qc, scheduling_method="alap", basis_gates=["h", "cx"], instruction_durations=[("h", 0, 200), ("cx", [0, 1], 700)], ) self.assertEqual(scheduled.duration, 1200) def test_transpile_circuit_with_custom_instruction(self): """See: https://github.com/Qiskit/qiskit-terra/issues/5154""" bell = QuantumCircuit(2, name="bell") bell.h(0) bell.cx(0, 1) qc = QuantumCircuit(2) qc.delay(500, 1) qc.append(bell.to_instruction(), [0, 1]) scheduled = transpile( qc, scheduling_method="alap", instruction_durations=[("bell", [0, 1], 1000)] ) self.assertEqual(scheduled.duration, 1500) def test_transpile_delay_circuit_with_dt_but_without_scheduling_method(self): qc = QuantumCircuit(1) qc.delay(100, 0, unit="ns") transpiled = transpile(qc, backend=self.backend_with_dt) self.assertEqual(transpiled.duration, None) # not scheduled self.assertEqual(transpiled.data[0].operation.duration, 450) # unit is converted ns -> dt def test_transpile_delay_circuit_without_scheduling_method_or_durs(self): qc = QuantumCircuit(2) qc.h(0) qc.delay(500, 1) qc.cx(0, 1) not_scheduled = transpile(qc) self.assertEqual(not_scheduled.duration, None) def test_raise_error_if_transpile_with_scheduling_method_but_without_durations(self): qc = QuantumCircuit(2) qc.h(0) qc.delay(500, 1) qc.cx(0, 1) with self.assertRaises(TranspilerError): transpile(qc, scheduling_method="alap") def test_invalidate_schedule_circuit_if_new_instruction_is_appended(self): qc = QuantumCircuit(2) qc.h(0) qc.delay(500 * self.dt, 1, "s") qc.cx(0, 1) scheduled = transpile(qc, backend=self.backend_with_dt, scheduling_method="alap") # append a gate to a scheduled circuit scheduled.h(0) self.assertEqual(scheduled.duration, None) def test_default_units_for_my_own_duration_users(self): qc = QuantumCircuit(2) qc.h(0) qc.delay(500, 1) qc.cx(0, 1) # accept None for qubits scheduled = transpile( qc, basis_gates=["h", "cx", "delay"], scheduling_method="alap", instruction_durations=[("h", 0, 200), ("cx", None, 900)], ) self.assertEqual(scheduled.duration, 1400) # prioritize specified qubits over None scheduled = transpile( qc, basis_gates=["h", "cx", "delay"], scheduling_method="alap", instruction_durations=[("h", 0, 200), ("cx", None, 900), ("cx", [0, 1], 800)], ) self.assertEqual(scheduled.duration, 1300) def test_unit_seconds_when_using_backend_durations(self): qc = QuantumCircuit(2) qc.h(0) qc.delay(500 * self.dt, 1, "s") qc.cx(0, 1) # usual case scheduled = transpile( qc, backend=self.backend_with_dt, scheduling_method="alap", layout_method="trivial" ) self.assertEqual(scheduled.duration, 2132) # update durations durations = InstructionDurations.from_backend(self.backend_with_dt) durations.update([("cx", [0, 1], 1000 * self.dt, "s")]) scheduled = transpile( qc, backend=self.backend_with_dt, scheduling_method="alap", instruction_durations=durations, layout_method="trivial", ) self.assertEqual(scheduled.duration, 1500) def test_per_qubit_durations(self): """See: https://github.com/Qiskit/qiskit-terra/issues/5109""" qc = QuantumCircuit(3) qc.h(0) qc.delay(500, 1) qc.cx(0, 1) qc.h(1) sc = transpile( qc, scheduling_method="alap", basis_gates=["h", "cx"], instruction_durations=[("h", None, 200), ("cx", [0, 1], 700)], ) self.assertEqual(sc.qubit_start_time(0), 300) self.assertEqual(sc.qubit_stop_time(0), 1200) self.assertEqual(sc.qubit_start_time(1), 500) self.assertEqual(sc.qubit_stop_time(1), 1400) self.assertEqual(sc.qubit_start_time(2), 0) self.assertEqual(sc.qubit_stop_time(2), 0) self.assertEqual(sc.qubit_start_time(0, 1), 300) self.assertEqual(sc.qubit_stop_time(0, 1), 1400) qc.measure_all() sc = transpile( qc, scheduling_method="alap", basis_gates=["h", "cx", "measure"], instruction_durations=[("h", None, 200), ("cx", [0, 1], 700), ("measure", None, 1000)], ) q = sc.qubits self.assertEqual(sc.qubit_start_time(q[0]), 300) self.assertEqual(sc.qubit_stop_time(q[0]), 2400) self.assertEqual(sc.qubit_start_time(q[1]), 500) self.assertEqual(sc.qubit_stop_time(q[1]), 2400) self.assertEqual(sc.qubit_start_time(q[2]), 1400) self.assertEqual(sc.qubit_stop_time(q[2]), 2400) self.assertEqual(sc.qubit_start_time(*q), 300) self.assertEqual(sc.qubit_stop_time(*q), 2400) def test_change_dt_in_transpile(self): qc = QuantumCircuit(1, 1) qc.x(0) qc.measure(0, 0) # default case scheduled = transpile(qc, backend=self.backend_with_dt, scheduling_method="asap") org_duration = scheduled.duration # halve dt in sec = double duration in dt scheduled = transpile( qc, backend=self.backend_with_dt, scheduling_method="asap", dt=self.dt / 2 ) self.assertEqual(scheduled.duration, org_duration * 2) @data("asap", "alap") def test_duration_on_same_instruction_instance(self, scheduling_method): """See: https://github.com/Qiskit/qiskit-terra/issues/5771""" assert self.backend_with_dt.properties().gate_length( "cx", (0, 1) ) != self.backend_with_dt.properties().gate_length("cx", (1, 2)) qc = QuantumCircuit(3) qc.cz(0, 1) qc.cz(1, 2) sc = transpile(qc, backend=self.backend_with_dt, scheduling_method=scheduling_method) cxs = [inst.operation for inst in sc.data if inst.operation.name == "cx"] self.assertNotEqual(cxs[0].duration, cxs[1].duration) def test_transpile_and_assemble_delay_circuit_for_simulator(self): """See: https://github.com/Qiskit/qiskit-terra/issues/5962""" qc = QuantumCircuit(1) qc.delay(100, 0, "ns") circ = transpile(qc, self.simulator_backend) self.assertEqual(circ.duration, None) # not scheduled qobj = assemble(circ, self.simulator_backend) self.assertEqual(qobj.experiments[0].instructions[0].name, "delay") self.assertEqual(qobj.experiments[0].instructions[0].params[0], 1e-7) def test_transpile_and_assemble_t1_circuit_for_simulator(self): """Check if no scheduling is done in transpiling for simulator backends""" qc = QuantumCircuit(1, 1) qc.x(0) qc.delay(0.1, 0, "us") qc.measure(0, 0) circ = transpile(qc, self.simulator_backend) self.assertEqual(circ.duration, None) # not scheduled qobj = assemble(circ, self.simulator_backend) self.assertEqual(qobj.experiments[0].instructions[1].name, "delay") self.assertAlmostEqual(qobj.experiments[0].instructions[1].params[0], 1e-7) # Tests for circuits with parameterized delays def test_can_transpile_circuits_after_assigning_parameters(self): """Check if not scheduled but duration is converted in dt""" idle_dur = Parameter("t") qc = QuantumCircuit(1, 1) qc.x(0) qc.delay(idle_dur, 0, "us") qc.measure(0, 0) qc = qc.assign_parameters({idle_dur: 0.1}) circ = transpile(qc, self.backend_with_dt) self.assertEqual(circ.duration, None) # not scheduled self.assertEqual(circ.data[1].operation.duration, 450) # converted in dt def test_can_transpile_and_assemble_circuits_with_assigning_parameters_inbetween(self): idle_dur = Parameter("t") qc = QuantumCircuit(1, 1) qc.x(0) qc.delay(idle_dur, 0, "us") qc.measure(0, 0) circ = transpile(qc, self.backend_with_dt) circ = circ.assign_parameters({idle_dur: 0.1}) qobj = assemble(circ, self.backend_with_dt) self.assertEqual(qobj.experiments[0].instructions[1].name, "delay") self.assertEqual(qobj.experiments[0].instructions[1].params[0], 450) def test_can_transpile_circuits_with_unbounded_parameters(self): idle_dur = Parameter("t") qc = QuantumCircuit(1, 1) qc.x(0) qc.delay(idle_dur, 0, "us") qc.measure(0, 0) # not assign parameter circ = transpile(qc, self.backend_with_dt) self.assertEqual(circ.duration, None) # not scheduled self.assertEqual(circ.data[1].operation.unit, "dt") # converted in dt self.assertEqual( circ.data[1].operation.duration, idle_dur * 1e-6 / self.dt ) # still parameterized def test_fail_to_assemble_circuits_with_unbounded_parameters(self): idle_dur = Parameter("t") qc = QuantumCircuit(1, 1) qc.x(0) qc.delay(idle_dur, 0, "us") qc.measure(0, 0) qc = transpile(qc, self.backend_with_dt) with self.assertRaises(QiskitError): assemble(qc, self.backend_with_dt) @data("asap", "alap") def test_can_schedule_circuits_with_bounded_parameters(self, scheduling_method): idle_dur = Parameter("t") qc = QuantumCircuit(1, 1) qc.x(0) qc.delay(idle_dur, 0, "us") qc.measure(0, 0) qc = qc.assign_parameters({idle_dur: 0.1}) circ = transpile(qc, self.backend_with_dt, scheduling_method=scheduling_method) self.assertIsNotNone(circ.duration) # scheduled @data("asap", "alap") def test_fail_to_schedule_circuits_with_unbounded_parameters(self, scheduling_method): idle_dur = Parameter("t") qc = QuantumCircuit(1, 1) qc.x(0) qc.delay(idle_dur, 0, "us") qc.measure(0, 0) # not assign parameter with self.assertRaises(TranspilerError): transpile(qc, self.backend_with_dt, scheduling_method=scheduling_method)
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for circuit templates.""" import unittest from test import combine from inspect import getmembers, isfunction from ddt import ddt import numpy as np from qiskit import QuantumCircuit from qiskit.test import QiskitTestCase from qiskit.quantum_info.operators import Operator import qiskit.circuit.library.templates as templib @ddt class TestTemplates(QiskitTestCase): """Tests for the circuit templates.""" circuits = [o[1]() for o in getmembers(templib) if isfunction(o[1])] for circuit in circuits: if isinstance(circuit, QuantumCircuit): circuit.assign_parameters({param: 0.2 for param in circuit.parameters}, inplace=True) @combine(template_circuit=circuits) def test_template(self, template_circuit): """test to verify that all templates are equivalent to the identity""" target = Operator(template_circuit) value = Operator(np.eye(2**template_circuit.num_qubits)) self.assertTrue(target.equiv(value)) if __name__ == "__main__": unittest.main()
https://github.com/swe-train/qiskit__qiskit
swe-train
# 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. """ Tests for uniformly controlled single-qubit unitaries. """ import unittest from ddt import ddt from test import combine # pylint: disable=wrong-import-order import numpy as np from scipy.linalg import block_diag from qiskit.extensions.quantum_initializer.uc import UCGate from qiskit import QuantumCircuit, QuantumRegister, BasicAer, execute from qiskit.test import QiskitTestCase from qiskit.quantum_info.random import random_unitary from qiskit.compiler import transpile from qiskit.quantum_info.operators.predicates import matrix_equal from qiskit.quantum_info import Operator _id = np.eye(2, 2) _not = np.matrix([[0, 1], [1, 0]]) @ddt class TestUCGate(QiskitTestCase): """Qiskit UCGate tests.""" @combine( squs=[ [_not], [_id], [_id, _id], [_id, 1j * _id], [_id, _not, _id, _not], [random_unitary(2, seed=541234).data for _ in range(2**2)], [random_unitary(2, seed=975163).data for _ in range(2**3)], [random_unitary(2, seed=629462).data for _ in range(2**4)], ], up_to_diagonal=[True, False], ) def test_ucg(self, squs, up_to_diagonal): """Test uniformly controlled gates.""" num_con = int(np.log2(len(squs))) q = QuantumRegister(num_con + 1) qc = QuantumCircuit(q) qc.uc(squs, q[1:], q[0], up_to_diagonal=up_to_diagonal) # Decompose the gate qc = transpile(qc, basis_gates=["u1", "u3", "u2", "cx", "id"]) # Simulate the decomposed gate simulator = BasicAer.get_backend("unitary_simulator") result = execute(qc, simulator).result() unitary = result.get_unitary(qc) if up_to_diagonal: ucg = UCGate(squs, up_to_diagonal=up_to_diagonal) unitary = np.dot(np.diagflat(ucg._get_diagonal()), unitary) unitary_desired = _get_ucg_matrix(squs) self.assertTrue(matrix_equal(unitary_desired, unitary, ignore_phase=True)) def test_global_phase_ucg(self): """Test global phase of uniformly controlled gates""" gates = [random_unitary(2).data for _ in range(2**2)] num_con = int(np.log2(len(gates))) q = QuantumRegister(num_con + 1) qc = QuantumCircuit(q) qc.uc(gates, q[1:], q[0], up_to_diagonal=False) simulator = BasicAer.get_backend("unitary_simulator") result = execute(qc, simulator).result() unitary = result.get_unitary(qc) unitary_desired = _get_ucg_matrix(gates) self.assertTrue(np.allclose(unitary_desired, unitary)) def test_inverse_ucg(self): """Test inverse function of uniformly controlled gates""" gates = [random_unitary(2, seed=42 + s).data for s in range(2**2)] num_con = int(np.log2(len(gates))) q = QuantumRegister(num_con + 1) qc = QuantumCircuit(q) qc.uc(gates, q[1:], q[0], up_to_diagonal=False) qc.append(qc.inverse(), qc.qubits) unitary = Operator(qc).data unitary_desired = np.identity(2**qc.num_qubits) self.assertTrue(np.allclose(unitary_desired, unitary)) def _get_ucg_matrix(squs): return block_diag(*squs) if __name__ == "__main__": unittest.main()
https://github.com/swe-train/qiskit__qiskit
swe-train
# 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. """Tests for uniformly controlled Rx,Ry and Rz gates""" import itertools import unittest import numpy as np from scipy.linalg import block_diag from qiskit import BasicAer, QuantumCircuit, QuantumRegister, execute from qiskit.test import QiskitTestCase from qiskit.quantum_info.operators.predicates import matrix_equal from qiskit.compiler import transpile angles_list = [ [0], [0.4], [0, 0], [0, 0.8], [0, 0, 1, 1], [0, 1, 0.5, 1], (2 * np.pi * np.random.rand(2**3)).tolist(), (2 * np.pi * np.random.rand(2**4)).tolist(), (2 * np.pi * np.random.rand(2**5)).tolist(), ] rot_axis_list = ["X", "Y", "Z"] class TestUCRXYZ(QiskitTestCase): """Qiskit tests for UCRXGate, UCRYGate and UCRZGate rotations gates.""" def test_ucy(self): """Test the decomposition of uniformly controlled rotations.""" for angles, rot_axis in itertools.product(angles_list, rot_axis_list): with self.subTest(angles=angles, rot_axis=rot_axis): num_contr = int(np.log2(len(angles))) q = QuantumRegister(num_contr + 1) qc = QuantumCircuit(q) if rot_axis == "X": qc.ucrx(angles, q[1 : num_contr + 1], q[0]) elif rot_axis == "Y": qc.ucry(angles, q[1 : num_contr + 1], q[0]) else: qc.ucrz(angles, q[1 : num_contr + 1], q[0]) # Decompose the gate qc = transpile(qc, basis_gates=["u1", "u3", "u2", "cx", "id"]) # Simulate the decomposed gate simulator = BasicAer.get_backend("unitary_simulator") result = execute(qc, simulator).result() unitary = result.get_unitary(qc) unitary_desired = _get_ucr_matrix(angles, rot_axis) self.assertTrue(matrix_equal(unitary_desired, unitary, ignore_phase=True)) def _get_ucr_matrix(angles, rot_axis): if rot_axis == "X": gates = [ np.array( [ [np.cos(angle / 2), -1j * np.sin(angle / 2)], [-1j * np.sin(angle / 2), np.cos(angle / 2)], ] ) for angle in angles ] elif rot_axis == "Y": gates = [ np.array( [[np.cos(angle / 2), -np.sin(angle / 2)], [np.sin(angle / 2), np.cos(angle / 2)]] ) for angle in angles ] else: gates = [ np.array([[np.exp(-1.0j * angle / 2), 0], [0, np.exp(1.0j * angle / 2)]]) for angle in angles ] return block_diag(*gates) if __name__ == "__main__": unittest.main()
https://github.com/swe-train/qiskit__qiskit
swe-train
# 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. """UnitaryGate tests""" import json import numpy from numpy.testing import assert_allclose import qiskit from qiskit.extensions.unitary import UnitaryGate from qiskit.test import QiskitTestCase from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.transpiler import PassManager from qiskit.converters import circuit_to_dag, dag_to_circuit from qiskit.quantum_info.random import random_unitary from qiskit.quantum_info.operators import Operator from qiskit.transpiler.passes import CXCancellation class TestUnitaryGate(QiskitTestCase): """Tests for the Unitary class.""" def test_set_matrix(self): """Test instantiation""" try: UnitaryGate([[0, 1], [1, 0]]) # pylint: disable=broad-except except Exception as err: self.fail(f"unexpected exception in init of Unitary: {err}") def test_set_matrix_raises(self): """test non-unitary""" try: UnitaryGate([[1, 1], [1, 0]]) # pylint: disable=broad-except except Exception: pass else: self.fail("setting Unitary with non-unitary did not raise") def test_set_init_with_unitary(self): """test instantiation of new unitary with another one (copy)""" uni1 = UnitaryGate([[0, 1], [1, 0]]) uni2 = UnitaryGate(uni1) self.assertEqual(uni1, uni2) self.assertFalse(uni1 is uni2) def test_conjugate(self): """test conjugate""" ymat = numpy.array([[0, -1j], [1j, 0]]) uni = UnitaryGate([[0, 1j], [-1j, 0]]) self.assertTrue(numpy.array_equal(uni.conjugate().to_matrix(), ymat)) def test_adjoint(self): """test adjoint operation""" uni = UnitaryGate([[0, 1j], [-1j, 0]]) self.assertTrue(numpy.array_equal(uni.adjoint().to_matrix(), uni.to_matrix())) class TestUnitaryCircuit(QiskitTestCase): """Matrix gate circuit tests.""" def test_1q_unitary(self): """test 1 qubit unitary matrix""" qr = QuantumRegister(1) cr = ClassicalRegister(1) qc = QuantumCircuit(qr, cr) matrix = numpy.array([[1, 0], [0, 1]]) qc.x(qr[0]) qc.append(UnitaryGate(matrix), [qr[0]]) # test of qasm output self.log.info(qc.qasm()) # test of text drawer self.log.info(qc) dag = circuit_to_dag(qc) dag_nodes = dag.named_nodes("unitary") self.assertTrue(len(dag_nodes) == 1) dnode = dag_nodes[0] self.assertIsInstance(dnode.op, UnitaryGate) self.assertEqual(dnode.qargs, (qr[0],)) assert_allclose(dnode.op.to_matrix(), matrix) def test_2q_unitary(self): """test 2 qubit unitary matrix""" qr = QuantumRegister(2) cr = ClassicalRegister(2) qc = QuantumCircuit(qr, cr) sigmax = numpy.array([[0, 1], [1, 0]]) sigmay = numpy.array([[0, -1j], [1j, 0]]) matrix = numpy.kron(sigmax, sigmay) qc.x(qr[0]) uni2q = UnitaryGate(matrix) qc.append(uni2q, [qr[0], qr[1]]) passman = PassManager() passman.append(CXCancellation()) qc2 = passman.run(qc) # test of qasm output self.log.info(qc2.qasm()) # test of text drawer self.log.info(qc2) dag = circuit_to_dag(qc) nodes = dag.two_qubit_ops() self.assertEqual(len(nodes), 1) dnode = nodes[0] self.assertIsInstance(dnode.op, UnitaryGate) self.assertEqual(dnode.qargs, (qr[0], qr[1])) assert_allclose(dnode.op.to_matrix(), matrix) qc3 = dag_to_circuit(dag) self.assertEqual(qc2, qc3) def test_3q_unitary(self): """test 3 qubit unitary matrix on non-consecutive bits""" qr = QuantumRegister(4) qc = QuantumCircuit(qr) sigmax = numpy.array([[0, 1], [1, 0]]) sigmay = numpy.array([[0, -1j], [1j, 0]]) matrix = numpy.kron(sigmay, numpy.kron(sigmax, sigmay)) qc.x(qr[0]) uni3q = UnitaryGate(matrix) qc.append(uni3q, [qr[0], qr[1], qr[3]]) qc.cx(qr[3], qr[2]) # test of text drawer self.log.info(qc) dag = circuit_to_dag(qc) nodes = dag.multi_qubit_ops() self.assertEqual(len(nodes), 1) dnode = nodes[0] self.assertIsInstance(dnode.op, UnitaryGate) self.assertEqual(dnode.qargs, (qr[0], qr[1], qr[3])) assert_allclose(dnode.op.to_matrix(), matrix) def test_1q_unitary_int_qargs(self): """test single qubit unitary matrix with 'int' and 'list of ints' qubits argument""" sigmax = numpy.array([[0, 1], [1, 0]]) sigmaz = numpy.array([[1, 0], [0, -1]]) # new syntax qr = QuantumRegister(2) qc = QuantumCircuit(qr) qc.unitary(sigmax, 0) qc.unitary(sigmax, qr[1]) qc.unitary(sigmaz, [0, 1]) # expected circuit qc_target = QuantumCircuit(qr) qc_target.append(UnitaryGate(sigmax), [0]) qc_target.append(UnitaryGate(sigmax), [qr[1]]) qc_target.append(UnitaryGate(sigmaz), [[0, 1]]) self.assertEqual(qc, qc_target) def test_qobj_with_unitary_matrix(self): """test qobj output with unitary matrix""" qr = QuantumRegister(4) qc = QuantumCircuit(qr) sigmax = numpy.array([[0, 1], [1, 0]]) sigmay = numpy.array([[0, -1j], [1j, 0]]) matrix = numpy.kron(sigmay, numpy.kron(sigmax, sigmay)) qc.rx(numpy.pi / 4, qr[0]) uni = UnitaryGate(matrix) qc.append(uni, [qr[0], qr[1], qr[3]]) qc.cx(qr[3], qr[2]) qobj = qiskit.compiler.assemble(qc) instr = qobj.experiments[0].instructions[1] self.assertEqual(instr.name, "unitary") assert_allclose(numpy.array(instr.params[0]).astype(numpy.complex64), matrix) # check conversion to dict qobj_dict = qobj.to_dict() class NumpyEncoder(json.JSONEncoder): """Class for encoding json str with complex and numpy arrays.""" def default(self, obj): if isinstance(obj, numpy.ndarray): return obj.tolist() if isinstance(obj, complex): return (obj.real, obj.imag) return json.JSONEncoder.default(self, obj) # check json serialization self.assertTrue(isinstance(json.dumps(qobj_dict, cls=NumpyEncoder), str)) def test_labeled_unitary(self): """test qobj output with unitary matrix""" qr = QuantumRegister(4) qc = QuantumCircuit(qr) sigmax = numpy.array([[0, 1], [1, 0]]) sigmay = numpy.array([[0, -1j], [1j, 0]]) matrix = numpy.kron(sigmax, sigmay) uni = UnitaryGate(matrix, label="xy") qc.append(uni, [qr[0], qr[1]]) qobj = qiskit.compiler.assemble(qc) instr = qobj.experiments[0].instructions[0] self.assertEqual(instr.name, "unitary") self.assertEqual(instr.label, "xy") def test_qasm_unitary_only_one_def(self): """test that a custom unitary can be converted to qasm and the definition is only written once""" qr = QuantumRegister(2, "q0") cr = ClassicalRegister(1, "c0") qc = QuantumCircuit(qr, cr) matrix = numpy.array([[1, 0], [0, 1]]) unitary_gate = UnitaryGate(matrix) qc.x(qr[0]) qc.append(unitary_gate, [qr[0]]) qc.append(unitary_gate, [qr[1]]) expected_qasm = ( "OPENQASM 2.0;\n" 'include "qelib1.inc";\n' "gate unitary q0 { u(0,0,0) q0; }\n" "qreg q0[2];\ncreg c0[1];\n" "x q0[0];\n" "unitary q0[0];\n" "unitary q0[1];\n" ) self.assertEqual(expected_qasm, qc.qasm()) def test_qasm_unitary_twice(self): """test that a custom unitary can be converted to qasm and that if the qasm is called twice it is the same every time""" qr = QuantumRegister(2, "q0") cr = ClassicalRegister(1, "c0") qc = QuantumCircuit(qr, cr) matrix = numpy.array([[1, 0], [0, 1]]) unitary_gate = UnitaryGate(matrix) qc.x(qr[0]) qc.append(unitary_gate, [qr[0]]) qc.append(unitary_gate, [qr[1]]) expected_qasm = ( "OPENQASM 2.0;\n" 'include "qelib1.inc";\n' "gate unitary q0 { u(0,0,0) q0; }\n" "qreg q0[2];\ncreg c0[1];\n" "x q0[0];\n" "unitary q0[0];\n" "unitary q0[1];\n" ) self.assertEqual(expected_qasm, qc.qasm()) self.assertEqual(expected_qasm, qc.qasm()) def test_qasm_2q_unitary(self): """test that a 2 qubit custom unitary can be converted to qasm""" qr = QuantumRegister(2, "q0") cr = ClassicalRegister(1, "c0") qc = QuantumCircuit(qr, cr) matrix = numpy.asarray([[0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0], [1, 0, 0, 0]]) unitary_gate = UnitaryGate(matrix) qc.x(qr[0]) qc.append(unitary_gate, [qr[0], qr[1]]) qc.append(unitary_gate, [qr[1], qr[0]]) expected_qasm = ( "OPENQASM 2.0;\n" 'include "qelib1.inc";\n' "gate unitary q0,q1 { u(pi,-pi/2,pi/2) q0; u(pi,pi/2,-pi/2) q1; }\n" "qreg q0[2];\n" "creg c0[1];\n" "x q0[0];\n" "unitary q0[0],q0[1];\n" "unitary q0[1],q0[0];\n" ) self.assertEqual(expected_qasm, qc.qasm()) def test_qasm_unitary_noop(self): """Test that an identity unitary can be converted to OpenQASM 2""" qc = QuantumCircuit(QuantumRegister(3, "q0")) qc.unitary(numpy.eye(8), qc.qubits) expected_qasm = ( "OPENQASM 2.0;\n" 'include "qelib1.inc";\n' "gate unitary q0,q1,q2 { }\n" "qreg q0[3];\n" "unitary q0[0],q0[1],q0[2];\n" ) self.assertEqual(expected_qasm, qc.qasm()) def test_unitary_decomposition(self): """Test decomposition for unitary gates over 2 qubits.""" qc = QuantumCircuit(3) qc.unitary(random_unitary(8, seed=42), [0, 1, 2]) self.assertTrue(Operator(qc).equiv(Operator(qc.decompose()))) def test_unitary_decomposition_via_definition(self): """Test decomposition for 1Q unitary via definition.""" mat = numpy.array([[0, 1], [1, 0]]) self.assertTrue(numpy.allclose(Operator(UnitaryGate(mat).definition).data, mat)) def test_unitary_decomposition_via_definition_2q(self): """Test decomposition for 2Q unitary via definition.""" mat = numpy.array([[0, 0, 1, 0], [0, 0, 0, -1], [1, 0, 0, 0], [0, -1, 0, 0]]) self.assertTrue(numpy.allclose(Operator(UnitaryGate(mat).definition).data, mat)) def test_unitary_control(self): """Test parameters of controlled - unitary.""" mat = numpy.array([[0, 1], [1, 0]]) gate = UnitaryGate(mat).control() self.assertTrue(numpy.allclose(gate.params, mat)) self.assertTrue(numpy.allclose(gate.base_gate.params, mat))
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test library of n-local circuits.""" import unittest from test import combine import numpy as np from ddt import ddt, data, unpack from qiskit.test.base import QiskitTestCase from qiskit import transpile from qiskit.circuit import QuantumCircuit, Parameter, ParameterVector, ParameterExpression from qiskit.circuit.library import ( NLocal, TwoLocal, RealAmplitudes, ExcitationPreserving, XGate, CRXGate, CCXGate, SwapGate, RXGate, RYGate, EfficientSU2, RZGate, RXXGate, RYYGate, CXGate, ) from qiskit.circuit.random.utils import random_circuit from qiskit.converters.circuit_to_dag import circuit_to_dag from qiskit.quantum_info import Operator @ddt class TestNLocal(QiskitTestCase): """Test the n-local circuit class.""" def test_if_reps_is_negative(self): """Test to check if error is raised for negative value of reps""" with self.assertRaises(ValueError): _ = NLocal(reps=-1) def test_if_reps_is_str(self): """Test to check if proper error is raised for str value of reps""" with self.assertRaises(TypeError): _ = NLocal(reps="3") def test_if_reps_is_float(self): """Test to check if proper error is raised for float value of reps""" with self.assertRaises(TypeError): _ = NLocal(reps=5.6) def test_if_reps_is_npint32(self): """Equality test for reps with int value and np.int32 value""" self.assertEqual(NLocal(reps=3), NLocal(reps=np.int32(3))) def test_if_reps_is_npint64(self): """Equality test for reps with int value and np.int64 value""" self.assertEqual(NLocal(reps=3), NLocal(reps=np.int64(3))) def test_reps_setter_when_negative(self): """Test to check if setter raises error for reps < 0""" nlocal = NLocal(reps=1) with self.assertRaises(ValueError): nlocal.reps = -1 def assertCircuitEqual(self, qc1, qc2, visual=False, transpiled=True): """An equality test specialized to circuits.""" if transpiled: basis_gates = ["id", "u1", "u3", "cx"] qc1_transpiled = transpile(qc1, basis_gates=basis_gates, optimization_level=0) qc2_transpiled = transpile(qc2, basis_gates=basis_gates, optimization_level=0) qc1, qc2 = qc1_transpiled, qc2_transpiled if visual: self.assertEqual(qc1.draw(), qc2.draw()) else: self.assertEqual(qc1, qc2) def test_empty_nlocal(self): """Test the creation of an empty NLocal.""" nlocal = NLocal() self.assertEqual(nlocal.num_qubits, 0) self.assertEqual(nlocal.num_parameters_settable, 0) self.assertEqual(nlocal.reps, 1) self.assertEqual(nlocal, QuantumCircuit()) for attribute in [nlocal.rotation_blocks, nlocal.entanglement_blocks]: self.assertEqual(len(attribute), 0) @data( (XGate(), [[0], [2], [1]]), (XGate(), [[0]]), (CRXGate(-0.2), [[2, 0], [1, 3]]), ) @unpack def test_add_layer_to_empty_nlocal(self, block, entangler_map): """Test appending gates to an empty nlocal.""" nlocal = NLocal() nlocal.add_layer(block, entangler_map) max_num_qubits = max(max(indices) for indices in entangler_map) reference = QuantumCircuit(max_num_qubits + 1) for indices in entangler_map: reference.append(block, indices) self.assertCircuitEqual(nlocal, reference) @data([5, 3], [1, 5], [1, 1], [1, 2, 3, 10]) def test_append_circuit(self, num_qubits): """Test appending circuits to an nlocal works normally.""" # fixed depth of 3 gates per circuit depth = 3 # keep track of a reference circuit reference = QuantumCircuit(max(num_qubits)) # construct the NLocal from the first circuit first_circuit = random_circuit(num_qubits[0], depth, seed=4200) # TODO Terra bug: if this is to_gate it fails, since the QC adds an instruction not gate nlocal = NLocal(max(num_qubits), entanglement_blocks=first_circuit.to_instruction(), reps=1) reference.append(first_circuit, list(range(num_qubits[0]))) # append the rest for num in num_qubits[1:]: circuit = random_circuit(num, depth, seed=4200) nlocal.append(circuit, list(range(num))) reference.append(circuit, list(range(num))) self.assertCircuitEqual(nlocal, reference) @data([5, 3], [1, 5], [1, 1], [1, 2, 3, 10]) def test_add_nlocal(self, num_qubits): """Test adding an nlocal to an nlocal (using add_layer).""" # fixed depth of 3 gates per circuit depth = 3 # keep track of a reference circuit reference = QuantumCircuit(max(num_qubits)) # construct the NLocal from the first circuit first_circuit = random_circuit(num_qubits[0], depth, seed=4220) # TODO Terra bug: if this is to_gate it fails, since the QC adds an instruction not gate nlocal = NLocal(max(num_qubits), entanglement_blocks=first_circuit.to_instruction(), reps=1) nlocal2 = nlocal.copy() _ = nlocal2.data reference.append(first_circuit, list(range(num_qubits[0]))) # append the rest for num in num_qubits[1:]: circuit = random_circuit(num, depth, seed=4220) layer = NLocal(num, entanglement_blocks=circuit, reps=1) nlocal.add_layer(layer) nlocal2.add_layer(layer) reference.append(circuit, list(range(num))) self.assertCircuitEqual(nlocal, reference) self.assertCircuitEqual(nlocal2, reference) @unittest.skip("Feature missing") def test_iadd_overload(self): """Test the overloaded + operator.""" num_qubits, depth = 2, 2 # construct two circuits for adding first_circuit = random_circuit(num_qubits, depth, seed=4242) circuit = random_circuit(num_qubits, depth, seed=4242) # get a reference reference = first_circuit + circuit # convert the object to be appended to different types others = [circuit, circuit.to_instruction(), circuit.to_gate(), NLocal(circuit)] # try adding each type for other in others: nlocal = NLocal(num_qubits, entanglement_blocks=first_circuit, reps=1) nlocal += other with self.subTest(msg=f"type: {type(other)}"): self.assertCircuitEqual(nlocal, reference) def test_parameter_getter_from_automatic_repetition(self): """Test getting and setting of the nlocal parameters.""" circuit = QuantumCircuit(2) circuit.ry(Parameter("a"), 0) circuit.crx(Parameter("b"), 0, 1) # repeat circuit and check that parameters are duplicated reps = 3 nlocal = NLocal(2, entanglement_blocks=circuit, reps=reps) self.assertTrue(nlocal.num_parameters, 6) self.assertTrue(len(nlocal.parameters), 6) @data(list(range(6)), ParameterVector("θ", length=6), [0, 1, Parameter("theta"), 3, 4, 5]) def test_parameter_setter_from_automatic_repetition(self, params): """Test getting and setting of the nlocal parameters.""" circuit = QuantumCircuit(2) circuit.ry(Parameter("a"), 0) circuit.crx(Parameter("b"), 0, 1) # repeat circuit and check that parameters are duplicated reps = 3 nlocal = NLocal(2, entanglement_blocks=circuit, reps=reps) nlocal.assign_parameters(params, inplace=True) param_set = {p for p in params if isinstance(p, ParameterExpression)} with self.subTest(msg="Test the parameters of the non-transpiled circuit"): # check the parameters of the final circuit self.assertEqual(nlocal.parameters, param_set) with self.subTest(msg="Test the parameters of the transpiled circuit"): basis_gates = ["id", "u1", "u2", "u3", "cx"] transpiled_circuit = transpile(nlocal, basis_gates=basis_gates) self.assertEqual(transpiled_circuit.parameters, param_set) @data(list(range(6)), ParameterVector("θ", length=6), [0, 1, Parameter("theta"), 3, 4, 5]) def test_parameters_setter(self, params): """Test setting the parameters via list.""" # construct circuit with some parameters initial_params = ParameterVector("p", length=6) circuit = QuantumCircuit(1) for i, initial_param in enumerate(initial_params): circuit.ry(i * initial_param, 0) # create an NLocal from the circuit and set the new parameters nlocal = NLocal(1, entanglement_blocks=circuit, reps=1) nlocal.assign_parameters(params, inplace=True) param_set = {p for p in params if isinstance(p, ParameterExpression)} with self.subTest(msg="Test the parameters of the non-transpiled circuit"): # check the parameters of the final circuit self.assertEqual(nlocal.parameters, param_set) with self.subTest(msg="Test the parameters of the transpiled circuit"): basis_gates = ["id", "u1", "u2", "u3", "cx"] transpiled_circuit = transpile(nlocal, basis_gates=basis_gates) self.assertEqual(transpiled_circuit.parameters, param_set) def test_repetetive_parameter_setting(self): """Test alternate setting of parameters and circuit construction.""" x = Parameter("x") circuit = QuantumCircuit(1) circuit.rx(x, 0) nlocal = NLocal(1, entanglement_blocks=circuit, reps=3, insert_barriers=True) with self.subTest(msg="immediately after initialization"): self.assertEqual(len(nlocal.parameters), 3) with self.subTest(msg="after circuit construction"): self.assertEqual(len(nlocal.parameters), 3) q = Parameter("q") nlocal.assign_parameters([x, q, q], inplace=True) with self.subTest(msg="setting parameter to Parameter objects"): self.assertEqual(nlocal.parameters, set({x, q})) nlocal.assign_parameters([0, -1], inplace=True) with self.subTest(msg="setting parameter to numbers"): self.assertEqual(nlocal.parameters, set()) def test_skip_unentangled_qubits(self): """Test skipping the unentangled qubits.""" num_qubits = 6 entanglement_1 = [[0, 1, 3], [1, 3, 5], [0, 1, 5]] skipped_1 = [2, 4] entanglement_2 = [entanglement_1, [[0, 1, 2], [2, 3, 5]]] skipped_2 = [4] for entanglement, skipped in zip([entanglement_1, entanglement_2], [skipped_1, skipped_2]): with self.subTest(entanglement=entanglement, skipped=skipped): nlocal = NLocal( num_qubits, rotation_blocks=XGate(), entanglement_blocks=CCXGate(), entanglement=entanglement, reps=3, skip_unentangled_qubits=True, ) decomposed = nlocal.decompose() skipped_set = {decomposed.qubits[i] for i in skipped} dag = circuit_to_dag(decomposed) idle = set(dag.idle_wires()) self.assertEqual(skipped_set, idle) @data( "linear", "full", "circular", "sca", "reverse_linear", ["linear", "full"], ["reverse_linear", "full"], ["circular", "linear", "sca"], ) def test_entanglement_by_str(self, entanglement): """Test setting the entanglement of the layers by str.""" reps = 3 nlocal = NLocal( 5, rotation_blocks=XGate(), entanglement_blocks=CCXGate(), entanglement=entanglement, reps=reps, ) def get_expected_entangler_map(rep_num, mode): if mode == "linear": return [(0, 1, 2), (1, 2, 3), (2, 3, 4)] elif mode == "reverse_linear": return [(2, 3, 4), (1, 2, 3), (0, 1, 2)] elif mode == "full": return [ (0, 1, 2), (0, 1, 3), (0, 1, 4), (0, 2, 3), (0, 2, 4), (0, 3, 4), (1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4), ] else: circular = [(3, 4, 0), (0, 1, 2), (1, 2, 3), (2, 3, 4)] if mode == "circular": return circular sca = circular[-rep_num:] + circular[:-rep_num] if rep_num % 2 == 1: sca = [tuple(reversed(indices)) for indices in sca] return sca for rep_num in range(reps): entangler_map = nlocal.get_entangler_map(rep_num, 0, 3) if isinstance(entanglement, list): mode = entanglement[rep_num % len(entanglement)] else: mode = entanglement expected = get_expected_entangler_map(rep_num, mode) with self.subTest(rep_num=rep_num): # using a set here since the order does not matter self.assertEqual(entangler_map, expected) def test_pairwise_entanglement(self): """Test pairwise entanglement.""" nlocal = NLocal( 5, rotation_blocks=XGate(), entanglement_blocks=CXGate(), entanglement="pairwise", reps=1, ) entangler_map = nlocal.get_entangler_map(0, 0, 2) pairwise = [(0, 1), (2, 3), (1, 2), (3, 4)] self.assertEqual(pairwise, entangler_map) def test_pairwise_entanglement_raises(self): """Test choosing pairwise entanglement raises an error for too large blocks.""" nlocal = NLocal(3, XGate(), CCXGate(), entanglement="pairwise", reps=1) # pairwise entanglement is only defined if the entangling gate has 2 qubits with self.assertRaises(ValueError): print(nlocal.draw()) def test_entanglement_by_list(self): """Test setting the entanglement by list. This is the circuit we test (times 2, with final X layer) ┌───┐ ┌───┐┌───┐ ┌───┐ q_0: |0>┤ X ├──■────■───X────┤ X ├┤ X ├──■───X─────── .. ┤ X ├ ├───┤ │ │ │ ├───┤└─┬─┘ │ │ ├───┤ q_1: |0>┤ X ├──■────┼───┼──X─┤ X ├──■────┼───X──X──── .. ┤ X ├ ├───┤┌─┴─┐ │ │ │ ├───┤ │ │ │ x2 ├───┤ q_2: |0>┤ X ├┤ X ├──■───┼──X─┤ X ├──■────■──────X──X─ .. ┤ X ├ ├───┤└───┘┌─┴─┐ │ ├───┤ ┌─┴─┐ │ ├───┤ q_3: |0>┤ X ├─────┤ X ├─X────┤ X ├─────┤ X ├───────X─ .. ┤ X ├ └───┘ └───┘ └───┘ └───┘ └───┘ """ circuit = QuantumCircuit(4) for _ in range(2): circuit.x([0, 1, 2, 3]) circuit.barrier() circuit.ccx(0, 1, 2) circuit.ccx(0, 2, 3) circuit.swap(0, 3) circuit.swap(1, 2) circuit.barrier() circuit.x([0, 1, 2, 3]) circuit.barrier() circuit.ccx(2, 1, 0) circuit.ccx(0, 2, 3) circuit.swap(0, 1) circuit.swap(1, 2) circuit.swap(2, 3) circuit.barrier() circuit.x([0, 1, 2, 3]) layer_1_ccx = [(0, 1, 2), (0, 2, 3)] layer_1_swap = [(0, 3), (1, 2)] layer_1 = [layer_1_ccx, layer_1_swap] layer_2_ccx = [(2, 1, 0), (0, 2, 3)] layer_2_swap = [(0, 1), (1, 2), (2, 3)] layer_2 = [layer_2_ccx, layer_2_swap] entanglement = [layer_1, layer_2] nlocal = NLocal( 4, rotation_blocks=XGate(), entanglement_blocks=[CCXGate(), SwapGate()], reps=4, entanglement=entanglement, insert_barriers=True, ) self.assertCircuitEqual(nlocal, circuit) def test_initial_state_as_circuit_object(self): """Test setting `initial_state` to `QuantumCircuit` object""" # ┌───┐ ┌───┐ # q_0: ──■──┤ X ├───────■──┤ X ├ # ┌─┴─┐├───┤┌───┐┌─┴─┐├───┤ # q_1: ┤ X ├┤ H ├┤ X ├┤ X ├┤ X ├ # └───┘└───┘└───┘└───┘└───┘ ref = QuantumCircuit(2) ref.cx(0, 1) ref.x(0) ref.h(1) ref.x(1) ref.cx(0, 1) ref.x(0) ref.x(1) qc = QuantumCircuit(2) qc.cx(0, 1) qc.h(1) expected = NLocal( num_qubits=2, rotation_blocks=XGate(), entanglement_blocks=CXGate(), initial_state=qc, reps=1, ) self.assertCircuitEqual(ref, expected) @ddt class TestTwoLocal(QiskitTestCase): """Tests for the TwoLocal circuit.""" def assertCircuitEqual(self, qc1, qc2, visual=False, transpiled=True): """An equality test specialized to circuits.""" if transpiled: basis_gates = ["id", "u1", "u3", "cx"] qc1_transpiled = transpile(qc1, basis_gates=basis_gates, optimization_level=0) qc2_transpiled = transpile(qc2, basis_gates=basis_gates, optimization_level=0) qc1, qc2 = qc1_transpiled, qc2_transpiled if visual: self.assertEqual(qc1.draw(), qc2.draw()) else: self.assertEqual(qc1, qc2) def test_skip_final_rotation_layer(self): """Test skipping the final rotation layer works.""" two = TwoLocal(3, ["ry", "h"], ["cz", "cx"], reps=2, skip_final_rotation_layer=True) self.assertEqual(two.num_parameters, 6) # would be 9 with a final rotation layer @data( (5, "rx", "cx", "full", 2, 15), (3, "x", "z", "linear", 1, 0), (3, "rx", "cz", "linear", 0, 3), (3, ["rx", "ry"], ["cry", "cx"], "circular", 2, 24), ) @unpack def test_num_parameters(self, num_qubits, rot, ent, ent_mode, reps, expected): """Test the number of parameters.""" two = TwoLocal( num_qubits, rotation_blocks=rot, entanglement_blocks=ent, entanglement=ent_mode, reps=reps, ) with self.subTest(msg="num_parameters_settable"): self.assertEqual(two.num_parameters_settable, expected) with self.subTest(msg="num_parameters"): self.assertEqual(two.num_parameters, expected) def test_empty_two_local(self): """Test the setup of an empty two-local circuit.""" two = TwoLocal() with self.subTest(msg="0 qubits"): self.assertEqual(two.num_qubits, 0) with self.subTest(msg="no blocks are set"): self.assertListEqual(two.rotation_blocks, []) self.assertListEqual(two.entanglement_blocks, []) with self.subTest(msg="equal to empty circuit"): self.assertEqual(two, QuantumCircuit()) @data("rx", RXGate(Parameter("p")), RXGate, "circuit") def test_various_block_types(self, rot): """Test setting the rotation blocks to various type and assert the output type is RX.""" if rot == "circuit": rot = QuantumCircuit(1) rot.rx(Parameter("angle"), 0) two = TwoLocal(3, rot, reps=0) self.assertEqual(len(two.rotation_blocks), 1) rotation = two.rotation_blocks[0] # decompose self.assertIsInstance(rotation.data[0].operation, RXGate) def test_parameter_setters(self): """Test different possibilities to set parameters.""" two = TwoLocal(3, rotation_blocks="rx", entanglement="cz", reps=2) params = [0, 1, 2, Parameter("x"), Parameter("y"), Parameter("z"), 6, 7, 0] params_set = {param for param in params if isinstance(param, Parameter)} with self.subTest(msg="dict assign and copy"): ordered = two.ordered_parameters bound = two.assign_parameters(dict(zip(ordered, params)), inplace=False) self.assertEqual(bound.parameters, params_set) self.assertEqual(two.num_parameters, 9) with self.subTest(msg="list assign and copy"): ordered = two.ordered_parameters bound = two.assign_parameters(params, inplace=False) self.assertEqual(bound.parameters, params_set) self.assertEqual(two.num_parameters, 9) with self.subTest(msg="list assign inplace"): ordered = two.ordered_parameters two.assign_parameters(params, inplace=True) self.assertEqual(two.parameters, params_set) self.assertEqual(two.num_parameters, 3) self.assertEqual(two.num_parameters_settable, 9) def test_parameters_settable_is_constant(self): """Test the attribute num_parameters_settable does not change on parameter change.""" two = TwoLocal(3, rotation_blocks="rx", entanglement="cz", reps=2) ordered_params = two.ordered_parameters x = Parameter("x") two.assign_parameters(dict(zip(ordered_params, [x] * two.num_parameters)), inplace=True) with self.subTest(msg="num_parameters collapsed to 1"): self.assertEqual(two.num_parameters, 1) with self.subTest(msg="num_parameters_settable remained constant"): self.assertEqual(two.num_parameters_settable, len(ordered_params)) def test_compose_inplace_to_circuit(self): """Test adding a two-local to an existing circuit.""" two = TwoLocal(3, ["ry", "rz"], "cz", "full", reps=1, insert_barriers=True) circuit = QuantumCircuit(3) circuit.compose(two, inplace=True) # ┌──────────┐┌──────────┐ ░ ░ ┌──────────┐ ┌──────────┐ # q_0: ┤ Ry(θ[0]) ├┤ Rz(θ[3]) ├─░──■──■─────░─┤ Ry(θ[6]) ├─┤ Rz(θ[9]) ├ # ├──────────┤├──────────┤ ░ │ │ ░ ├──────────┤┌┴──────────┤ # q_1: ┤ Ry(θ[1]) ├┤ Rz(θ[4]) ├─░──■──┼──■──░─┤ Ry(θ[7]) ├┤ Rz(θ[10]) ├ # ├──────────┤├──────────┤ ░ │ │ ░ ├──────────┤├───────────┤ # q_2: ┤ Ry(θ[2]) ├┤ Rz(θ[5]) ├─░─────■──■──░─┤ Ry(θ[8]) ├┤ Rz(θ[11]) ├ # └──────────┘└──────────┘ ░ ░ └──────────┘└───────────┘ reference = QuantumCircuit(3) param_iter = iter(two.ordered_parameters) for i in range(3): reference.ry(next(param_iter), i) for i in range(3): reference.rz(next(param_iter), i) reference.barrier() reference.cz(0, 1) reference.cz(0, 2) reference.cz(1, 2) reference.barrier() for i in range(3): reference.ry(next(param_iter), i) for i in range(3): reference.rz(next(param_iter), i) self.assertCircuitEqual(circuit.decompose(), reference) def test_composing_two(self): """Test adding two two-local circuits.""" entangler_map = [[0, 3], [0, 2]] two = TwoLocal(4, [], "cry", entangler_map, reps=1) circuit = two.compose(two) reference = QuantumCircuit(4) params = two.ordered_parameters for _ in range(2): reference.cry(params[0], 0, 3) reference.cry(params[1], 0, 2) self.assertCircuitEqual(reference, circuit) def test_ry_blocks(self): """Test that the RealAmplitudes circuit is instantiated correctly.""" two = RealAmplitudes(4) with self.subTest(msg="test rotation gate"): self.assertEqual(len(two.rotation_blocks), 1) self.assertIsInstance(two.rotation_blocks[0].data[0].operation, RYGate) with self.subTest(msg="test parameter bounds"): expected = [(-np.pi, np.pi)] * two.num_parameters np.testing.assert_almost_equal(two.parameter_bounds, expected) def test_ry_circuit_reverse_linear(self): """Test a RealAmplitudes circuit with entanglement = "reverse_linear".""" num_qubits = 3 reps = 2 entanglement = "reverse_linear" parameters = ParameterVector("theta", num_qubits * (reps + 1)) param_iter = iter(parameters) expected = QuantumCircuit(3) for _ in range(reps): for i in range(num_qubits): expected.ry(next(param_iter), i) expected.cx(1, 2) expected.cx(0, 1) for i in range(num_qubits): expected.ry(next(param_iter), i) library = RealAmplitudes( num_qubits, reps=reps, entanglement=entanglement ).assign_parameters(parameters) self.assertCircuitEqual(library, expected) def test_ry_circuit_full(self): """Test a RealAmplitudes circuit with entanglement = "full".""" num_qubits = 3 reps = 2 entanglement = "full" parameters = ParameterVector("theta", num_qubits * (reps + 1)) param_iter = iter(parameters) # ┌──────────┐ ┌──────────┐ ┌──────────┐ # q_0: ┤ Ry(θ[0]) ├──■────■──┤ Ry(θ[3]) ├──────────────■────■──┤ Ry(θ[6]) ├──────────── # ├──────────┤┌─┴─┐ │ └──────────┘┌──────────┐┌─┴─┐ │ └──────────┘┌──────────┐ # q_1: ┤ Ry(θ[1]) ├┤ X ├──┼─────────■────┤ Ry(θ[4]) ├┤ X ├──┼─────────■────┤ Ry(θ[7]) ├ # ├──────────┤└───┘┌─┴─┐ ┌─┴─┐ ├──────────┤└───┘┌─┴─┐ ┌─┴─┐ ├──────────┤ # q_2: ┤ Ry(θ[2]) ├─────┤ X ├─────┤ X ├──┤ Ry(θ[5]) ├─────┤ X ├─────┤ X ├──┤ Ry(θ[8]) ├ # └──────────┘ └───┘ └───┘ └──────────┘ └───┘ └───┘ └──────────┘ expected = QuantumCircuit(3) for _ in range(reps): for i in range(num_qubits): expected.ry(next(param_iter), i) expected.cx(0, 1) expected.cx(0, 2) expected.cx(1, 2) for i in range(num_qubits): expected.ry(next(param_iter), i) library = RealAmplitudes( num_qubits, reps=reps, entanglement=entanglement ).assign_parameters(parameters) self.assertCircuitEqual(library, expected) def test_ryrz_blocks(self): """Test that the EfficientSU2 circuit is instantiated correctly.""" two = EfficientSU2(3) with self.subTest(msg="test rotation gate"): self.assertEqual(len(two.rotation_blocks), 2) self.assertIsInstance(two.rotation_blocks[0].data[0].operation, RYGate) self.assertIsInstance(two.rotation_blocks[1].data[0].operation, RZGate) with self.subTest(msg="test parameter bounds"): expected = [(-np.pi, np.pi)] * two.num_parameters np.testing.assert_almost_equal(two.parameter_bounds, expected) def test_ryrz_circuit(self): """Test an EfficientSU2 circuit.""" num_qubits = 3 reps = 2 entanglement = "circular" parameters = ParameterVector("theta", 2 * num_qubits * (reps + 1)) param_iter = iter(parameters) # ┌──────────┐┌──────────┐┌───┐ ┌──────────┐┌──────────┐ » # q_0: ┤ Ry(θ[0]) ├┤ Rz(θ[3]) ├┤ X ├──■──┤ Ry(θ[6]) ├┤ Rz(θ[9]) ├─────────────» # ├──────────┤├──────────┤└─┬─┘┌─┴─┐└──────────┘├──────────┤┌───────────┐» # q_1: ┤ Ry(θ[1]) ├┤ Rz(θ[4]) ├──┼──┤ X ├─────■──────┤ Ry(θ[7]) ├┤ Rz(θ[10]) ├» # ├──────────┤├──────────┤ │ └───┘ ┌─┴─┐ ├──────────┤├───────────┤» # q_2: ┤ Ry(θ[2]) ├┤ Rz(θ[5]) ├──■──────────┤ X ├────┤ Ry(θ[8]) ├┤ Rz(θ[11]) ├» # └──────────┘└──────────┘ └───┘ └──────────┘└───────────┘» # « ┌───┐ ┌───────────┐┌───────────┐ # «q_0: ┤ X ├──■──┤ Ry(θ[12]) ├┤ Rz(θ[15]) ├───────────── # « └─┬─┘┌─┴─┐└───────────┘├───────────┤┌───────────┐ # «q_1: ──┼──┤ X ├──────■──────┤ Ry(θ[13]) ├┤ Rz(θ[16]) ├ # « │ └───┘ ┌─┴─┐ ├───────────┤├───────────┤ # «q_2: ──■───────────┤ X ├────┤ Ry(θ[14]) ├┤ Rz(θ[17]) ├ # « └───┘ └───────────┘└───────────┘ expected = QuantumCircuit(3) for _ in range(reps): for i in range(num_qubits): expected.ry(next(param_iter), i) for i in range(num_qubits): expected.rz(next(param_iter), i) expected.cx(2, 0) expected.cx(0, 1) expected.cx(1, 2) for i in range(num_qubits): expected.ry(next(param_iter), i) for i in range(num_qubits): expected.rz(next(param_iter), i) library = EfficientSU2(num_qubits, reps=reps, entanglement=entanglement).assign_parameters( parameters ) self.assertCircuitEqual(library, expected) def test_swaprz_blocks(self): """Test that the ExcitationPreserving circuit is instantiated correctly.""" two = ExcitationPreserving(5) with self.subTest(msg="test rotation gate"): self.assertEqual(len(two.rotation_blocks), 1) self.assertIsInstance(two.rotation_blocks[0].data[0].operation, RZGate) with self.subTest(msg="test entanglement gate"): self.assertEqual(len(two.entanglement_blocks), 1) block = two.entanglement_blocks[0] self.assertEqual(len(block.data), 2) self.assertIsInstance(block.data[0].operation, RXXGate) self.assertIsInstance(block.data[1].operation, RYYGate) with self.subTest(msg="test parameter bounds"): expected = [(-np.pi, np.pi)] * two.num_parameters np.testing.assert_almost_equal(two.parameter_bounds, expected) def test_swaprz_circuit(self): """Test a ExcitationPreserving circuit in iswap mode.""" num_qubits = 3 reps = 2 entanglement = "linear" parameters = ParameterVector("theta", num_qubits * (reps + 1) + reps * (num_qubits - 1)) param_iter = iter(parameters) # ┌──────────┐┌────────────┐┌────────────┐ ┌──────────┐ » # q_0: ┤ Rz(θ[0]) ├┤0 ├┤0 ├─┤ Rz(θ[5]) ├───────────────» # ├──────────┤│ Rxx(θ[3]) ││ Ryy(θ[3]) │┌┴──────────┴┐┌────────────┐» # q_1: ┤ Rz(θ[1]) ├┤1 ├┤1 ├┤0 ├┤0 ├» # ├──────────┤└────────────┘└────────────┘│ Rxx(θ[4]) ││ Ryy(θ[4]) │» # q_2: ┤ Rz(θ[2]) ├────────────────────────────┤1 ├┤1 ├» # └──────────┘ └────────────┘└────────────┘» # « ┌────────────┐┌────────────┐┌───────────┐ » # «q_0: ────────────┤0 ├┤0 ├┤ Rz(θ[10]) ├───────────────» # « ┌──────────┐│ Rxx(θ[8]) ││ Ryy(θ[8]) │├───────────┴┐┌────────────┐» # «q_1: ┤ Rz(θ[6]) ├┤1 ├┤1 ├┤0 ├┤0 ├» # « ├──────────┤└────────────┘└────────────┘│ Rxx(θ[9]) ││ Ryy(θ[9]) │» # «q_2: ┤ Rz(θ[7]) ├────────────────────────────┤1 ├┤1 ├» # « └──────────┘ └────────────┘└────────────┘» # « # «q_0: ───────────── # « ┌───────────┐ # «q_1: ┤ Rz(θ[11]) ├ # « ├───────────┤ # «q_2: ┤ Rz(θ[12]) ├ # « └───────────┘ expected = QuantumCircuit(3) for _ in range(reps): for i in range(num_qubits): expected.rz(next(param_iter), i) shared_param = next(param_iter) expected.rxx(shared_param, 0, 1) expected.ryy(shared_param, 0, 1) shared_param = next(param_iter) expected.rxx(shared_param, 1, 2) expected.ryy(shared_param, 1, 2) for i in range(num_qubits): expected.rz(next(param_iter), i) library = ExcitationPreserving( num_qubits, reps=reps, entanglement=entanglement ).assign_parameters(parameters) self.assertCircuitEqual(library, expected) def test_fsim_circuit(self): """Test a ExcitationPreserving circuit in fsim mode.""" num_qubits = 3 reps = 2 entanglement = "linear" # need the parameters in the entanglement blocks to be the same because the order # can get mixed up in ExcitationPreserving (since parameters are not ordered in circuits) parameters = [1] * (num_qubits * (reps + 1) + reps * (1 + num_qubits)) param_iter = iter(parameters) # ┌───────┐┌─────────┐┌─────────┐ ┌───────┐ » # q_0: ┤ Rz(1) ├┤0 ├┤0 ├─■──────┤ Rz(1) ├───────────────────» # ├───────┤│ Rxx(1) ││ Ryy(1) │ │P(1) ┌┴───────┴┐┌─────────┐ » # q_1: ┤ Rz(1) ├┤1 ├┤1 ├─■─────┤0 ├┤0 ├─■─────» # ├───────┤└─────────┘└─────────┘ │ Rxx(1) ││ Ryy(1) │ │P(1) » # q_2: ┤ Rz(1) ├─────────────────────────────┤1 ├┤1 ├─■─────» # └───────┘ └─────────┘└─────────┘ » # « ┌─────────┐┌─────────┐ ┌───────┐ » # «q_0: ─────────┤0 ├┤0 ├─■──────┤ Rz(1) ├───────────────────» # « ┌───────┐│ Rxx(1) ││ Ryy(1) │ │P(1) ┌┴───────┴┐┌─────────┐ » # «q_1: ┤ Rz(1) ├┤1 ├┤1 ├─■─────┤0 ├┤0 ├─■─────» # « ├───────┤└─────────┘└─────────┘ │ Rxx(1) ││ Ryy(1) │ │P(1) » # «q_2: ┤ Rz(1) ├─────────────────────────────┤1 ├┤1 ├─■─────» # « └───────┘ └─────────┘└─────────┘ » # « # «q_0: ───────── # « ┌───────┐ # «q_1: ┤ Rz(1) ├ # « ├───────┤ # «q_2: ┤ Rz(1) ├ # « └───────┘ expected = QuantumCircuit(3) for _ in range(reps): for i in range(num_qubits): expected.rz(next(param_iter), i) shared_param = next(param_iter) expected.rxx(shared_param, 0, 1) expected.ryy(shared_param, 0, 1) expected.cp(next(param_iter), 0, 1) shared_param = next(param_iter) expected.rxx(shared_param, 1, 2) expected.ryy(shared_param, 1, 2) expected.cp(next(param_iter), 1, 2) for i in range(num_qubits): expected.rz(next(param_iter), i) library = ExcitationPreserving( num_qubits, reps=reps, mode="fsim", entanglement=entanglement ).assign_parameters(parameters) self.assertCircuitEqual(library, expected) def test_circular_on_same_block_and_circuit_size(self): """Test circular entanglement works correctly if the circuit and block sizes match.""" two = TwoLocal(2, "ry", "cx", entanglement="circular", reps=1) parameters = np.arange(two.num_parameters) # ┌───────┐ ┌───────┐ # q_0: ┤ Ry(0) ├──■──┤ Ry(2) ├ # ├───────┤┌─┴─┐├───────┤ # q_1: ┤ Ry(1) ├┤ X ├┤ Ry(3) ├ # └───────┘└───┘└───────┘ ref = QuantumCircuit(2) ref.ry(parameters[0], 0) ref.ry(parameters[1], 1) ref.cx(0, 1) ref.ry(parameters[2], 0) ref.ry(parameters[3], 1) self.assertCircuitEqual(two.assign_parameters(parameters), ref) def test_circuit_with_numpy_integers(self): """Test if TwoLocal can be made from numpy integers""" num_qubits = 6 reps = 3 expected_np32 = [ (i, j) for i in np.arange(num_qubits, dtype=np.int32) for j in np.arange(num_qubits, dtype=np.int32) if i < j ] expected_np64 = [ (i, j) for i in np.arange(num_qubits, dtype=np.int64) for j in np.arange(num_qubits, dtype=np.int64) if i < j ] two_np32 = TwoLocal(num_qubits, "ry", "cx", entanglement=expected_np32, reps=reps) two_np64 = TwoLocal(num_qubits, "ry", "cx", entanglement=expected_np64, reps=reps) expected_cx = reps * num_qubits * (num_qubits - 1) / 2 self.assertEqual(two_np32.decompose().count_ops()["cx"], expected_cx) self.assertEqual(two_np64.decompose().count_ops()["cx"], expected_cx) @combine(num_qubits=[4, 5]) def test_full_vs_reverse_linear(self, num_qubits): """Test that 'full' and 'reverse_linear' provide the same unitary element.""" reps = 2 full = RealAmplitudes(num_qubits=num_qubits, entanglement="full", reps=reps) num_params = (reps + 1) * num_qubits np.random.seed(num_qubits) params = np.random.rand(num_params) reverse = RealAmplitudes(num_qubits=num_qubits, entanglement="reverse_linear", reps=reps) full.assign_parameters(params, inplace=True) reverse.assign_parameters(params, inplace=True) self.assertEqual(Operator(full), Operator(reverse)) if __name__ == "__main__": unittest.main()
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test permutation quantum circuits, permutation gates, and quantum circuits that contain permutation gates.""" import io import unittest import numpy as np from qiskit import QuantumRegister from qiskit.test.base import QiskitTestCase from qiskit.circuit import QuantumCircuit from qiskit.circuit.exceptions import CircuitError from qiskit.circuit.library import Permutation, PermutationGate from qiskit.quantum_info import Operator from qiskit.qpy import dump, load class TestPermutationLibrary(QiskitTestCase): """Test library of permutation logic quantum circuits.""" def test_permutation(self): """Test permutation circuit.""" circuit = Permutation(num_qubits=4, pattern=[1, 0, 3, 2]) expected = QuantumCircuit(4) expected.swap(0, 1) expected.swap(2, 3) expected = Operator(expected) simulated = Operator(circuit) self.assertTrue(expected.equiv(simulated)) def test_permutation_bad(self): """Test that [0,..,n-1] permutation is required (no -1 for last element).""" self.assertRaises(CircuitError, Permutation, 4, [1, 0, -1, 2]) class TestPermutationGate(QiskitTestCase): """Tests for the PermutationGate class.""" def test_permutation(self): """Test that Operator can be constructed.""" perm = PermutationGate(pattern=[1, 0, 3, 2]) expected = QuantumCircuit(4) expected.swap(0, 1) expected.swap(2, 3) expected = Operator(expected) simulated = Operator(perm) self.assertTrue(expected.equiv(simulated)) def test_permutation_bad(self): """Test that [0,..,n-1] permutation is required (no -1 for last element).""" self.assertRaises(CircuitError, PermutationGate, [1, 0, -1, 2]) def test_permutation_array(self): """Test correctness of the ``__array__`` method.""" perm = PermutationGate([1, 2, 0]) # The permutation pattern means q1->q0, q2->q1, q0->q2, or equivalently # q0'=q1, q1'=q2, q2'=q0, where the primed values are the values after the # permutation. The following matrix is the expected unitary matrix for this. # As an example, the second column represents the result of applying # the permutation to |001>, i.e. to q2=0, q1=0, q0=1. We should get # q2'=q0=1, q1'=q2=0, q0'=q1=0, that is the state |100>. This corresponds # to the "1" in the 5 row. expected_op = np.array( [ [1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1], ] ) self.assertTrue(np.array_equal(perm.__array__(dtype=int), expected_op)) def test_pattern(self): """Test the ``pattern`` method.""" pattern = [1, 3, 5, 0, 4, 2] perm = PermutationGate(pattern) self.assertTrue(np.array_equal(perm.pattern, pattern)) def test_inverse(self): """Test correctness of the ``inverse`` method.""" perm = PermutationGate([1, 3, 5, 0, 4, 2]) # We have the permutation 1->0, 3->1, 5->2, 0->3, 4->4, 2->5. # The inverse permutations is 0->1, 1->3, 2->5, 3->0, 4->4, 5->2, or # after reordering 3->0, 0->1, 5->2, 1->3, 4->4, 2->5. inverse_perm = perm.inverse() expected_inverse_perm = PermutationGate([3, 0, 5, 1, 4, 2]) self.assertTrue(np.array_equal(inverse_perm.pattern, expected_inverse_perm.pattern)) class TestPermutationGatesOnCircuit(QiskitTestCase): """Tests for quantum circuits containing permutations.""" def test_append_to_circuit(self): """Test method for adding Permutations to quantum circuit.""" qc = QuantumCircuit(5) qc.append(PermutationGate([1, 2, 0]), [0, 1, 2]) qc.append(PermutationGate([2, 3, 0, 1]), [1, 2, 3, 4]) self.assertIsInstance(qc.data[0].operation, PermutationGate) self.assertIsInstance(qc.data[1].operation, PermutationGate) def test_inverse(self): """Test inverse method for circuits with permutations.""" qc = QuantumCircuit(5) qc.append(PermutationGate([1, 2, 3, 0]), [0, 4, 2, 1]) qci = qc.inverse() qci_pattern = qci.data[0].operation.pattern expected_pattern = [3, 0, 1, 2] # The inverse permutations should be defined over the same qubits but with the # inverse permutation pattern. self.assertTrue(np.array_equal(qci_pattern, expected_pattern)) self.assertTrue(np.array_equal(qc.data[0].qubits, qci.data[0].qubits)) def test_reverse_ops(self): """Test reverse_ops method for circuits with permutations.""" qc = QuantumCircuit(5) qc.append(PermutationGate([1, 2, 3, 0]), [0, 4, 2, 1]) qcr = qc.reverse_ops() # The reversed circuit should have the permutation gate with the same pattern and over the # same qubits. self.assertTrue(np.array_equal(qc.data[0].operation.pattern, qcr.data[0].operation.pattern)) self.assertTrue(np.array_equal(qc.data[0].qubits, qcr.data[0].qubits)) def test_conditional(self): """Test adding conditional permutations.""" qc = QuantumCircuit(5, 1) qc.append(PermutationGate([1, 2, 0]), [2, 3, 4]).c_if(0, 1) self.assertIsNotNone(qc.data[0].operation.condition) def test_qasm(self): """Test qasm for circuits with permutations.""" qr = QuantumRegister(5, "q0") circuit = QuantumCircuit(qr) pattern = [2, 4, 3, 0, 1] permutation = PermutationGate(pattern) circuit.append(permutation, [0, 1, 2, 3, 4]) circuit.h(qr[0]) expected_qasm = ( "OPENQASM 2.0;\n" 'include "qelib1.inc";\n' "gate permutation__2_4_3_0_1_ q0,q1,q2,q3,q4 { swap q2,q3; swap q1,q4; swap q0,q3; }\n" "qreg q0[5];\n" "permutation__2_4_3_0_1_ q0[0],q0[1],q0[2],q0[3],q0[4];\n" "h q0[0];\n" ) self.assertEqual(expected_qasm, circuit.qasm()) def test_qpy(self): """Test qpy for circuits with permutations.""" circuit = QuantumCircuit(6, 1) circuit.cx(0, 1) circuit.append(PermutationGate([1, 2, 0]), [2, 4, 5]) circuit.h(4) print(circuit) qpy_file = io.BytesIO() dump(circuit, qpy_file) qpy_file.seek(0) new_circuit = load(qpy_file)[0] self.assertEqual(circuit, new_circuit) if __name__ == "__main__": unittest.main()
https://github.com/swe-train/qiskit__qiskit
swe-train
""" This file allows to test the various QFT implemented. The user must specify: 1) The number of qubits it wants the QFT to be implemented on 2) The kind of QFT want to implement, among the options: -> Normal QFT with SWAP gates at the end -> Normal QFT without SWAP gates at the end -> Inverse QFT with SWAP gates at the end -> Inverse QFT without SWAP gates at the end The user must can also specify, in the main function, the input quantum state. By default is a maximal superposition state This file uses as simulator the local simulator 'statevector_simulator' because this simulator saves the quantum state at the end of the circuit, which is exactly the goal of the test file. This simulator supports sufficient qubits to the size of the QFTs that are going to be used in Shor's Algorithm because the IBM simulator only supports up to 32 qubits """ """ Imports from qiskit""" from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute, IBMQ, BasicAer """ Imports to Python functions """ import time """ Local Imports """ from qfunctions import create_QFT, create_inverse_QFT """ Function to properly print the final state of the simulation """ """ This is only possible in this way because the program uses the statevector_simulator """ def show_good_coef(results, n): i=0 max = pow(2,n) if max > 100: max = 100 """ Iterate to all possible states """ while i<max: binary = bin(i)[2:].zfill(n) number = results.item(i) number = round(number.real, 3) + round(number.imag, 3) * 1j """ Print the respective component of the state if it has a non-zero coefficient """ if number!=0: print('|{}>'.format(binary),number) i=i+1 """ Main program """ if __name__ == '__main__': """ Select how many qubits want to apply the QFT on """ n = int(input('\nPlease select how many qubits want to apply the QFT on: ')) """ Select the kind of QFT to apply using the variable what_to_test: what_to_test = 0: Apply normal QFT with the SWAP gates at the end what_to_test = 1: Apply normal QFT without the SWAP gates at the end what_to_test = 2: Apply inverse QFT with the SWAP gates at the end what_to_test = 3: Apply inverse QFT without the SWAP gates at the end """ print('\nSelect the kind of QFT to apply:') print('Select 0 to apply normal QFT with the SWAP gates at the end') print('Select 1 to apply normal QFT without the SWAP gates at the end') print('Select 2 to apply inverse QFT with the SWAP gates at the end') print('Select 3 to apply inverse QFT without the SWAP gates at the end\n') what_to_test = int(input('Select your option: ')) if what_to_test<0 or what_to_test>3: print('Please select one of the options') exit() print('\nTotal number of qubits used: {0}\n'.format(n)) print('Please check source file to change input quantum state. By default is a maximal superposition state with |+> in every qubit.\n') ts = time.time() """ Create quantum and classical registers """ quantum_reg = QuantumRegister(n) classic_reg = ClassicalRegister(n) """ Create Quantum Circuit """ circuit = QuantumCircuit(quantum_reg, classic_reg) """ Create the input state desired Please change this as you like, by default we put H gates in every qubit, initializing with a maximimal superposition state """ #circuit.h(quantum_reg) """ Test the right QFT according to the variable specified before""" if what_to_test == 0: create_QFT(circuit,quantum_reg,n,1) elif what_to_test == 1: create_QFT(circuit,quantum_reg,n,0) elif what_to_test == 2: create_inverse_QFT(circuit,quantum_reg,n,1) elif what_to_test == 3: create_inverse_QFT(circuit,quantum_reg,n,0) else: print('Noting to implement, exiting program') exit() """ show results of circuit creation """ create_time = round(time.time()-ts, 3) if n < 8: print(circuit) print(f"... circuit creation time = {create_time}") ts = time.time() """ Simulate the created Quantum Circuit """ simulation = execute(circuit, backend=BasicAer.get_backend('statevector_simulator'),shots=1) """ Get the results of the simulation in proper structure """ sim_result=simulation.result() """ Get the statevector of the final quantum state """ outputstate = sim_result.get_statevector(circuit, decimals=3) """ show execution time """ exec_time = round(time.time()-ts, 3) print(f"... circuit execute time = {exec_time}") """ Print final quantum state to user """ print('The final state after applying the QFT is:\n') show_good_coef(outputstate,n)
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ StatePreparation test. """ import unittest import math import numpy as np from ddt import ddt, data from qiskit import QuantumCircuit, QuantumRegister from qiskit.quantum_info import Statevector, Operator from qiskit.test import QiskitTestCase from qiskit.exceptions import QiskitError from qiskit.circuit.library import StatePreparation @ddt class TestStatePreparation(QiskitTestCase): """Test initialization with StatePreparation class""" def test_prepare_from_label(self): """Prepare state from label.""" desired_sv = Statevector.from_label("01+-lr") qc = QuantumCircuit(6) qc.prepare_state("01+-lr", range(6)) actual_sv = Statevector(qc) self.assertTrue(desired_sv == actual_sv) def test_prepare_from_int(self): """Prepare state from int.""" desired_sv = Statevector.from_label("110101") qc = QuantumCircuit(6) qc.prepare_state(53, range(6)) actual_sv = Statevector(qc) self.assertTrue(desired_sv == actual_sv) def test_prepare_from_list(self): """Prepare state from list.""" desired_sv = Statevector([1 / math.sqrt(2), 0, 0, 1 / math.sqrt(2)]) qc = QuantumCircuit(2) qc.prepare_state([1 / math.sqrt(2), 0, 0, 1 / math.sqrt(2)]) actual_sv = Statevector(qc) self.assertTrue(desired_sv == actual_sv) def test_prepare_single_qubit(self): """Prepare state in single qubit.""" qreg = QuantumRegister(2) circuit = QuantumCircuit(qreg) circuit.prepare_state([1 / math.sqrt(2), 1 / math.sqrt(2)], qreg[1]) expected = QuantumCircuit(qreg) expected.prepare_state([1 / math.sqrt(2), 1 / math.sqrt(2)], [qreg[1]]) self.assertEqual(circuit, expected) def test_nonzero_state_incorrect(self): """Test final state incorrect if initial state not zero""" desired_sv = Statevector([1 / math.sqrt(2), 0, 0, 1 / math.sqrt(2)]) qc = QuantumCircuit(2) qc.x(0) qc.prepare_state([1 / math.sqrt(2), 0, 0, 1 / math.sqrt(2)]) actual_sv = Statevector(qc) self.assertFalse(desired_sv == actual_sv) @data(2, "11", [1 / math.sqrt(2), 0, 0, 1 / math.sqrt(2)]) def test_inverse(self, state): """Test inverse of StatePreparation""" qc = QuantumCircuit(2) stateprep = StatePreparation(state) qc.append(stateprep, [0, 1]) qc.append(stateprep.inverse(), [0, 1]) self.assertTrue(np.allclose(Operator(qc).data, np.identity(2**qc.num_qubits))) def test_double_inverse(self): """Test twice inverse of StatePreparation""" desired_sv = Statevector([1 / math.sqrt(2), 0, 0, 1 / math.sqrt(2)]) qc = QuantumCircuit(2) stateprep = StatePreparation([1 / math.sqrt(2), 0, 0, 1 / math.sqrt(2)]) qc.append(stateprep.inverse().inverse(), [0, 1]) actual_sv = Statevector(qc) self.assertTrue(desired_sv == actual_sv) def test_incompatible_state_and_qubit_args(self): """Test error raised if number of qubits not compatible with state arg""" qc = QuantumCircuit(3) with self.assertRaises(QiskitError): qc.prepare_state("11") def test_incompatible_int_state_and_qubit_args(self): """Test error raised if number of qubits not compatible with integer state arg""" # pylint: disable=pointless-statement with self.assertRaises(QiskitError): stateprep = StatePreparation(5, num_qubits=2) stateprep.definition def test_int_state_and_no_qubit_args(self): """Test automatic determination of qubit number""" stateprep = StatePreparation(5) self.assertEqual(stateprep.num_qubits, 3) def test_repeats(self): """Test repeat function repeats correctly""" qc = QuantumCircuit(2) qc.append(StatePreparation("01").repeat(2), [0, 1]) self.assertEqual(qc.decompose().count_ops()["state_preparation"], 2) if __name__ == "__main__": unittest.main()
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test boolean expression.""" import unittest from os import path from ddt import ddt, unpack, data from qiskit.test.base import QiskitTestCase from qiskit import execute, BasicAer from qiskit.utils.optionals import HAS_TWEEDLEDUM if HAS_TWEEDLEDUM: from qiskit.circuit.classicalfunction.boolean_expression import BooleanExpression @unittest.skipUnless(HAS_TWEEDLEDUM, "Tweedledum is required for these tests.") @ddt class TestBooleanExpression(QiskitTestCase): """Test boolean expression.""" @data( ("x | x", "1", True), ("x & x", "0", False), ("(x0 & x1 | ~x2) ^ x4", "0110", False), ("xx & xxx | ( ~z ^ zz)", "0111", True), ) @unpack def test_evaluate(self, expression, input_bitstring, expected): """Test simulate""" expression = BooleanExpression(expression) result = expression.simulate(input_bitstring) self.assertEqual(result, expected) @data( ("x", False), ("not x", True), ("(x0 & x1 | ~x2) ^ x4", True), ("xx & xxx | ( ~z ^ zz)", True), ) @unpack def test_synth(self, expression, expected): """Test synth""" expression = BooleanExpression(expression) expr_circ = expression.synth() new_creg = expr_circ._create_creg(1, "c") expr_circ.add_register(new_creg) expr_circ.measure(expression.num_qubits - 1, new_creg) [result] = ( execute( expr_circ, backend=BasicAer.get_backend("qasm_simulator"), shots=1, seed_simulator=14, ) .result() .get_counts() .keys() ) self.assertEqual(bool(int(result)), expected) @unittest.skipUnless(HAS_TWEEDLEDUM, "Tweedledum is required for these tests.") class TestBooleanExpressionDIMACS(QiskitTestCase): """Loading from a cnf file""" def normalize_filenames(self, filename): """Given a filename, returns the directory in terms of __file__.""" dirname = path.dirname(__file__) return path.join(dirname, filename) def test_simple(self): """Loads simple_v3_c2.cnf and simulate""" filename = self.normalize_filenames("dimacs/simple_v3_c2.cnf") simple = BooleanExpression.from_dimacs_file(filename) self.assertEqual(simple.name, "simple_v3_c2.cnf") self.assertEqual(simple.num_qubits, 4) self.assertTrue(simple.simulate("101")) def test_quinn(self): """Loads quinn.cnf and simulate""" filename = self.normalize_filenames("dimacs/quinn.cnf") simple = BooleanExpression.from_dimacs_file(filename) self.assertEqual(simple.name, "quinn.cnf") self.assertEqual(simple.num_qubits, 16) self.assertFalse(simple.simulate("1010101010101010")) if __name__ == "__main__": unittest.main()
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests ClassicalFunction as a gate.""" import unittest from qiskit.test import QiskitTestCase from qiskit import QuantumCircuit from qiskit.circuit.library.standard_gates import XGate from qiskit.utils.optionals import HAS_TWEEDLEDUM if HAS_TWEEDLEDUM: from . import examples from qiskit.circuit.classicalfunction import classical_function as compile_classical_function @unittest.skipUnless(HAS_TWEEDLEDUM, "Tweedledum is required for these tests.") class TestOracleDecomposition(QiskitTestCase): """Tests ClassicalFunction.decomposition.""" def test_grover_oracle(self): """grover_oracle.decomposition""" oracle = compile_classical_function(examples.grover_oracle) quantum_circuit = QuantumCircuit(5) quantum_circuit.append(oracle, [2, 1, 0, 3, 4]) expected = QuantumCircuit(5) expected.append(XGate().control(4, ctrl_state="1010"), [2, 1, 0, 3, 4]) self.assertEqual(quantum_circuit.decompose(), expected)
https://github.com/swe-train/qiskit__qiskit
swe-train
# 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. """Randomized tests of quantum synthesis.""" import unittest from test.python.quantum_info.test_synthesis import CheckDecompositions from hypothesis import given, strategies, settings import numpy as np from qiskit import execute from qiskit.circuit import QuantumCircuit, QuantumRegister from qiskit.extensions import UnitaryGate from qiskit.providers.basicaer import UnitarySimulatorPy from qiskit.quantum_info.random import random_unitary from qiskit.quantum_info.synthesis.two_qubit_decompose import ( two_qubit_cnot_decompose, TwoQubitBasisDecomposer, Ud, ) class TestSynthesis(CheckDecompositions): """Test synthesis""" seed = strategies.integers(min_value=0, max_value=2**32 - 1) rotation = strategies.floats(min_value=-np.pi * 10, max_value=np.pi * 10) @given(seed) def test_1q_random(self, seed): """Checks one qubit decompositions""" unitary = random_unitary(2, seed=seed) self.check_one_qubit_euler_angles(unitary) self.check_one_qubit_euler_angles(unitary, "U3") self.check_one_qubit_euler_angles(unitary, "U1X") self.check_one_qubit_euler_angles(unitary, "PSX") self.check_one_qubit_euler_angles(unitary, "ZSX") self.check_one_qubit_euler_angles(unitary, "ZYZ") self.check_one_qubit_euler_angles(unitary, "ZXZ") self.check_one_qubit_euler_angles(unitary, "XYX") self.check_one_qubit_euler_angles(unitary, "RR") @settings(deadline=None) @given(seed) def test_2q_random(self, seed): """Checks two qubit decompositions""" unitary = random_unitary(4, seed=seed) self.check_exact_decomposition(unitary.data, two_qubit_cnot_decompose) @given(strategies.tuples(*[seed] * 5)) def test_exact_supercontrolled_decompose_random(self, seeds): """Exact decomposition for random supercontrolled basis and random target""" k1 = np.kron(random_unitary(2, seed=seeds[0]).data, random_unitary(2, seed=seeds[1]).data) k2 = np.kron(random_unitary(2, seed=seeds[2]).data, random_unitary(2, seed=seeds[3]).data) basis_unitary = k1 @ Ud(np.pi / 4, 0, 0) @ k2 decomposer = TwoQubitBasisDecomposer(UnitaryGate(basis_unitary)) self.check_exact_decomposition(random_unitary(4, seed=seeds[4]).data, decomposer) @given(strategies.tuples(*[rotation] * 6), seed) def test_cx_equivalence_0cx_random(self, rnd, seed): """Check random circuits with 0 cx gates locally equivalent to identity.""" qr = QuantumRegister(2, name="q") qc = QuantumCircuit(qr) qc.u(rnd[0], rnd[1], rnd[2], qr[0]) qc.u(rnd[3], rnd[4], rnd[5], qr[1]) sim = UnitarySimulatorPy() unitary = execute(qc, sim, seed_simulator=seed).result().get_unitary() self.assertEqual(two_qubit_cnot_decompose.num_basis_gates(unitary), 0) @given(strategies.tuples(*[rotation] * 12), seed) def test_cx_equivalence_1cx_random(self, rnd, seed): """Check random circuits with 1 cx gates locally equivalent to a cx.""" qr = QuantumRegister(2, name="q") qc = QuantumCircuit(qr) qc.u(rnd[0], rnd[1], rnd[2], qr[0]) qc.u(rnd[3], rnd[4], rnd[5], qr[1]) qc.cx(qr[1], qr[0]) qc.u(rnd[6], rnd[7], rnd[8], qr[0]) qc.u(rnd[9], rnd[10], rnd[11], qr[1]) sim = UnitarySimulatorPy() unitary = execute(qc, sim, seed_simulator=seed).result().get_unitary() self.assertEqual(two_qubit_cnot_decompose.num_basis_gates(unitary), 1) @given(strategies.tuples(*[rotation] * 18), seed) def test_cx_equivalence_2cx_random(self, rnd, seed): """Check random circuits with 2 cx gates locally equivalent to some circuit with 2 cx.""" qr = QuantumRegister(2, name="q") qc = QuantumCircuit(qr) qc.u(rnd[0], rnd[1], rnd[2], qr[0]) qc.u(rnd[3], rnd[4], rnd[5], qr[1]) qc.cx(qr[1], qr[0]) qc.u(rnd[6], rnd[7], rnd[8], qr[0]) qc.u(rnd[9], rnd[10], rnd[11], qr[1]) qc.cx(qr[0], qr[1]) qc.u(rnd[12], rnd[13], rnd[14], qr[0]) qc.u(rnd[15], rnd[16], rnd[17], qr[1]) sim = UnitarySimulatorPy() unitary = execute(qc, sim, seed_simulator=seed).result().get_unitary() self.assertEqual(two_qubit_cnot_decompose.num_basis_gates(unitary), 2) @given(strategies.tuples(*[rotation] * 24), seed) def test_cx_equivalence_3cx_random(self, rnd, seed): """Check random circuits with 3 cx gates are outside the 0, 1, and 2 qubit regions.""" qr = QuantumRegister(2, name="q") qc = QuantumCircuit(qr) qc.u(rnd[0], rnd[1], rnd[2], qr[0]) qc.u(rnd[3], rnd[4], rnd[5], qr[1]) qc.cx(qr[1], qr[0]) qc.u(rnd[6], rnd[7], rnd[8], qr[0]) qc.u(rnd[9], rnd[10], rnd[11], qr[1]) qc.cx(qr[0], qr[1]) qc.u(rnd[12], rnd[13], rnd[14], qr[0]) qc.u(rnd[15], rnd[16], rnd[17], qr[1]) qc.cx(qr[1], qr[0]) qc.u(rnd[18], rnd[19], rnd[20], qr[0]) qc.u(rnd[21], rnd[22], rnd[23], qr[1]) sim = UnitarySimulatorPy() unitary = execute(qc, sim, seed_simulator=seed).result().get_unitary() self.assertEqual(two_qubit_cnot_decompose.num_basis_gates(unitary), 3) if __name__ == "__main__": unittest.main()
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests LogicNetwork.Tweedledum2Qiskit converter.""" import unittest from qiskit.utils.optionals import HAS_TWEEDLEDUM from qiskit.test import QiskitTestCase from qiskit import QuantumCircuit, QuantumRegister from qiskit.circuit.library.standard_gates import XGate if HAS_TWEEDLEDUM: # pylint: disable=import-error from qiskit.circuit.classicalfunction.utils import tweedledum2qiskit from tweedledum.ir import Circuit from tweedledum.operators import X @unittest.skipUnless(HAS_TWEEDLEDUM, "Tweedledum is required for these tests.") class TestTweedledum2Qiskit(QiskitTestCase): """Tests qiskit.transpiler.classicalfunction.utils.tweedledum2qiskit function.""" def test_x(self): """Single uncontrolled X""" tweedledum_circuit = Circuit() tweedledum_circuit.apply_operator(X(), [tweedledum_circuit.create_qubit()]) circuit = tweedledum2qiskit(tweedledum_circuit) expected = QuantumCircuit(1) expected.x(0) self.assertEqual(circuit, expected) def test_cx_0_1(self): """CX(0, 1)""" tweedledum_circuit = Circuit() qubits = [] qubits.append(tweedledum_circuit.create_qubit()) qubits.append(tweedledum_circuit.create_qubit()) tweedledum_circuit.apply_operator(X(), [qubits[0], qubits[1]]) circuit = tweedledum2qiskit(tweedledum_circuit) expected = QuantumCircuit(2) expected.append(XGate().control(1, ctrl_state="1"), [0, 1]) self.assertEqual(circuit, expected) def test_cx_1_0(self): """CX(1, 0)""" tweedledum_circuit = Circuit() qubits = [] qubits.append(tweedledum_circuit.create_qubit()) qubits.append(tweedledum_circuit.create_qubit()) tweedledum_circuit.apply_operator(X(), [qubits[1], qubits[0]]) circuit = tweedledum2qiskit(tweedledum_circuit) expected = QuantumCircuit(2) expected.append(XGate().control(1, ctrl_state="1"), [1, 0]) self.assertEqual(expected, circuit) def test_cx_qreg(self): """CX(0, 1) with qregs parameter""" tweedledum_circuit = Circuit() qubits = [] qubits.append(tweedledum_circuit.create_qubit()) qubits.append(tweedledum_circuit.create_qubit()) tweedledum_circuit.apply_operator(X(), [qubits[1], qubits[0]]) qr = QuantumRegister(2, "qr") circuit = tweedledum2qiskit(tweedledum_circuit, qregs=[qr]) expected = QuantumCircuit(qr) expected.append(XGate().control(1, ctrl_state="1"), [qr[1], qr[0]]) self.assertEqual(expected, circuit)
https://github.com/swe-train/qiskit__qiskit
swe-train
# 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. """Assembler Test.""" import unittest import io from logging import StreamHandler, getLogger import sys import copy import numpy as np from qiskit import pulse from qiskit.circuit import Instruction, Gate, Parameter, ParameterVector from qiskit.circuit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.compiler.assembler import assemble from qiskit.exceptions import QiskitError from qiskit.pulse import Schedule, Acquire, Play from qiskit.pulse.channels import MemorySlot, AcquireChannel, DriveChannel, MeasureChannel from qiskit.pulse.configuration import Kernel, Discriminator from qiskit.pulse.library import gaussian from qiskit.qobj import QasmQobj, PulseQobj from qiskit.qobj.utils import MeasLevel, MeasReturnType from qiskit.pulse.macros import measure from qiskit.test import QiskitTestCase from qiskit.providers.fake_provider import ( FakeOpenPulse2Q, FakeOpenPulse3Q, FakeYorktown, FakeHanoi, ) class RxGate(Gate): """Used to test custom gate assembly. Useful for testing pulse gates with parameters, as well. Note: Parallel maps (e.g., in assemble_circuits) pickle their input, so circuit features have to be defined top level. """ def __init__(self, theta): super().__init__("rxtheta", 1, [theta]) class TestCircuitAssembler(QiskitTestCase): """Tests for assembling circuits to qobj.""" def setUp(self): super().setUp() qr = QuantumRegister(2, name="q") cr = ClassicalRegister(2, name="c") self.circ = QuantumCircuit(qr, cr, name="circ") self.circ.h(qr[0]) self.circ.cx(qr[0], qr[1]) self.circ.measure(qr, cr) self.backend = FakeYorktown() self.backend_config = self.backend.configuration() self.num_qubits = self.backend_config.n_qubits # lo test values self.default_qubit_lo_freq = [5e9 for _ in range(self.num_qubits)] self.default_meas_lo_freq = [6.7e9 for _ in range(self.num_qubits)] self.user_lo_config_dict = { pulse.DriveChannel(0): 5.55e9, pulse.MeasureChannel(0): 6.64e9, pulse.DriveChannel(3): 4.91e9, pulse.MeasureChannel(4): 6.1e9, } self.user_lo_config = pulse.LoConfig(self.user_lo_config_dict) def test_assemble_single_circuit(self): """Test assembling a single circuit.""" qobj = assemble(self.circ, shots=2000, memory=True) self.assertIsInstance(qobj, QasmQobj) self.assertEqual(qobj.config.shots, 2000) self.assertEqual(qobj.config.memory, True) self.assertEqual(len(qobj.experiments), 1) self.assertEqual(qobj.experiments[0].instructions[1].name, "cx") def test_assemble_multiple_circuits(self): """Test assembling multiple circuits, all should have the same config.""" qr0 = QuantumRegister(2, name="q0") qc0 = ClassicalRegister(2, name="c0") circ0 = QuantumCircuit(qr0, qc0, name="circ0") circ0.h(qr0[0]) circ0.cx(qr0[0], qr0[1]) circ0.measure(qr0, qc0) qr1 = QuantumRegister(3, name="q1") qc1 = ClassicalRegister(3, name="c1") circ1 = QuantumCircuit(qr1, qc1, name="circ0") circ1.h(qr1[0]) circ1.cx(qr1[0], qr1[1]) circ1.cx(qr1[0], qr1[2]) circ1.measure(qr1, qc1) qobj = assemble([circ0, circ1], shots=100, memory=False, seed_simulator=6) self.assertIsInstance(qobj, QasmQobj) self.assertEqual(qobj.config.seed_simulator, 6) self.assertEqual(len(qobj.experiments), 2) self.assertEqual(qobj.experiments[1].config.n_qubits, 3) self.assertEqual(len(qobj.experiments), 2) self.assertEqual(len(qobj.experiments[1].instructions), 6) def test_assemble_no_run_config(self): """Test assembling with no run_config, relying on default.""" qobj = assemble(self.circ) self.assertIsInstance(qobj, QasmQobj) self.assertEqual(qobj.config.shots, 1024) def test_shots_greater_than_max_shots(self): """Test assembling with shots greater than max shots""" self.assertRaises(QiskitError, assemble, self.backend, shots=1024000) def test_shots_not_of_type_int(self): """Test assembling with shots having type other than int""" self.assertRaises(QiskitError, assemble, self.backend, shots="1024") def test_shots_of_type_numpy_int64(self): """Test assembling with shots having type numpy.int64""" qobj = assemble(self.circ, shots=np.int64(2048)) self.assertEqual(qobj.config.shots, 2048) def test_default_shots_greater_than_max_shots(self): """Test assembling with default shots greater than max shots""" self.backend_config.max_shots = 5 qobj = assemble(self.circ, self.backend) self.assertIsInstance(qobj, QasmQobj) self.assertEqual(qobj.config.shots, 5) def test_assemble_initialize(self): """Test assembling a circuit with an initialize.""" q = QuantumRegister(2, name="q") circ = QuantumCircuit(q, name="circ") circ.initialize([1 / np.sqrt(2), 0, 0, 1 / np.sqrt(2)], q[:]) qobj = assemble(circ) self.assertIsInstance(qobj, QasmQobj) self.assertEqual(qobj.experiments[0].instructions[0].name, "initialize") np.testing.assert_almost_equal( qobj.experiments[0].instructions[0].params, [0.7071067811865, 0, 0, 0.707106781186] ) def test_assemble_meas_level_meas_return(self): """Test assembling a circuit schedule with `meas_level`.""" qobj = assemble(self.circ, meas_level=1, meas_return="single") self.assertIsInstance(qobj, QasmQobj) self.assertEqual(qobj.config.meas_level, 1) self.assertEqual(qobj.config.meas_return, "single") # no meas_level set qobj = assemble(self.circ) self.assertIsInstance(qobj, QasmQobj) self.assertEqual(qobj.config.meas_level, 2) self.assertEqual(hasattr(qobj.config, "meas_return"), False) def test_assemble_backend_rep_delays(self): """Check that rep_delay is properly set from backend values.""" rep_delay_range = [2.5e-3, 4.5e-3] # sec default_rep_delay = 3.0e-3 setattr(self.backend_config, "rep_delay_range", rep_delay_range) setattr(self.backend_config, "default_rep_delay", default_rep_delay) # dynamic rep rates off setattr(self.backend_config, "dynamic_reprate_enabled", False) qobj = assemble(self.circ, self.backend) self.assertEqual(hasattr(qobj.config, "rep_delay"), False) # dynamic rep rates on setattr(self.backend_config, "dynamic_reprate_enabled", True) qobj = assemble(self.circ, self.backend) self.assertEqual(qobj.config.rep_delay, default_rep_delay * 1e6) def test_assemble_user_rep_time_delay(self): """Check that user runtime config rep_delay works.""" # set custom rep_delay in runtime config rep_delay = 2.2e-6 rep_delay_range = [0, 3e-6] # sec setattr(self.backend_config, "rep_delay_range", rep_delay_range) # dynamic rep rates off (no default so shouldn't be in qobj config) setattr(self.backend_config, "dynamic_reprate_enabled", False) qobj = assemble(self.circ, self.backend, rep_delay=rep_delay) self.assertEqual(hasattr(qobj.config, "rep_delay"), False) # turn on dynamic rep rates, rep_delay should be set setattr(self.backend_config, "dynamic_reprate_enabled", True) qobj = assemble(self.circ, self.backend, rep_delay=rep_delay) self.assertEqual(qobj.config.rep_delay, 2.2) # test ``rep_delay=0`` qobj = assemble(self.circ, self.backend, rep_delay=0) self.assertEqual(qobj.config.rep_delay, 0) # use ``rep_delay`` outside of ``rep_delay_range``` rep_delay_large = 5.0e-6 with self.assertRaises(QiskitError): assemble(self.circ, self.backend, rep_delay=rep_delay_large) def test_assemble_opaque_inst(self): """Test opaque instruction is assembled as-is""" opaque_inst = Instruction(name="my_inst", num_qubits=4, num_clbits=2, params=[0.5, 0.4]) q = QuantumRegister(6, name="q") c = ClassicalRegister(4, name="c") circ = QuantumCircuit(q, c, name="circ") circ.append(opaque_inst, [q[0], q[2], q[5], q[3]], [c[3], c[0]]) qobj = assemble(circ) self.assertIsInstance(qobj, QasmQobj) self.assertEqual(len(qobj.experiments[0].instructions), 1) self.assertEqual(qobj.experiments[0].instructions[0].name, "my_inst") self.assertEqual(qobj.experiments[0].instructions[0].qubits, [0, 2, 5, 3]) self.assertEqual(qobj.experiments[0].instructions[0].memory, [3, 0]) self.assertEqual(qobj.experiments[0].instructions[0].params, [0.5, 0.4]) def test_assemble_unroll_parametervector(self): """Verfiy that assemble unrolls parametervectors ref #5467""" pv1 = ParameterVector("pv1", 3) pv2 = ParameterVector("pv2", 3) qc = QuantumCircuit(2, 2) for i in range(3): qc.rx(pv1[i], 0) qc.ry(pv2[i], 1) qc.barrier() qc.measure([0, 1], [0, 1]) qc.bind_parameters({pv1: [0.1, 0.2, 0.3], pv2: [0.4, 0.5, 0.6]}) qobj = assemble(qc, parameter_binds=[{pv1: [0.1, 0.2, 0.3], pv2: [0.4, 0.5, 0.6]}]) self.assertIsInstance(qobj, QasmQobj) self.assertEqual(qobj.experiments[0].instructions[0].params[0], 0.100000000000000) self.assertEqual(qobj.experiments[0].instructions[1].params[0], 0.400000000000000) self.assertEqual(qobj.experiments[0].instructions[2].params[0], 0.200000000000000) self.assertEqual(qobj.experiments[0].instructions[3].params[0], 0.500000000000000) self.assertEqual(qobj.experiments[0].instructions[4].params[0], 0.300000000000000) self.assertEqual(qobj.experiments[0].instructions[5].params[0], 0.600000000000000) def test_measure_to_registers_when_conditionals(self): """Verify assemble_circuits maps all measure ops on to a register slot for a circuit containing conditionals.""" qr = QuantumRegister(2) cr1 = ClassicalRegister(1) cr2 = ClassicalRegister(2) qc = QuantumCircuit(qr, cr1, cr2) qc.measure(qr[0], cr1) # Measure not required for a later conditional qc.measure(qr[1], cr2[1]) # Measure required for a later conditional qc.h(qr[1]).c_if(cr2, 3) qobj = assemble(qc) first_measure, second_measure = ( op for op in qobj.experiments[0].instructions if op.name == "measure" ) self.assertTrue(hasattr(first_measure, "register")) self.assertEqual(first_measure.register, first_measure.memory) self.assertTrue(hasattr(second_measure, "register")) self.assertEqual(second_measure.register, second_measure.memory) def test_convert_to_bfunc_plus_conditional(self): """Verify assemble_circuits converts conditionals from QASM to Qobj.""" qr = QuantumRegister(1) cr = ClassicalRegister(1) qc = QuantumCircuit(qr, cr) qc.h(qr[0]).c_if(cr, 1) qobj = assemble(qc) bfunc_op, h_op = qobj.experiments[0].instructions self.assertEqual(bfunc_op.name, "bfunc") self.assertEqual(bfunc_op.mask, "0x1") self.assertEqual(bfunc_op.val, "0x1") self.assertEqual(bfunc_op.relation, "==") self.assertTrue(hasattr(h_op, "conditional")) self.assertEqual(bfunc_op.register, h_op.conditional) def test_convert_to_bfunc_plus_conditional_onebit(self): """Verify assemble_circuits converts single bit conditionals from QASM to Qobj.""" qr = QuantumRegister(1) cr = ClassicalRegister(3) qc = QuantumCircuit(qr, cr) qc.h(qr[0]).c_if(cr[2], 1) qobj = assemble(qc) inst_set = qobj.experiments[0].instructions [bfunc_op, h_op] = inst_set self.assertEqual(len(inst_set), 2) self.assertEqual(bfunc_op.name, "bfunc") self.assertEqual(bfunc_op.mask, "0x4") self.assertEqual(bfunc_op.val, "0x4") self.assertEqual(bfunc_op.relation, "==") self.assertTrue(hasattr(h_op, "conditional")) self.assertEqual(bfunc_op.register, h_op.conditional) def test_resize_value_to_register(self): """Verify assemble_circuits converts the value provided on the classical creg to its mapped location on the device register.""" qr = QuantumRegister(1) cr1 = ClassicalRegister(2) cr2 = ClassicalRegister(2) cr3 = ClassicalRegister(1) qc = QuantumCircuit(qr, cr1, cr2, cr3) qc.h(qr[0]).c_if(cr2, 2) qobj = assemble(qc) bfunc_op, h_op = qobj.experiments[0].instructions self.assertEqual(bfunc_op.name, "bfunc") self.assertEqual(bfunc_op.mask, "0xC") self.assertEqual(bfunc_op.val, "0x8") self.assertEqual(bfunc_op.relation, "==") self.assertTrue(hasattr(h_op, "conditional")) self.assertEqual(bfunc_op.register, h_op.conditional) def test_assemble_circuits_raises_for_bind_circuit_mismatch(self): """Verify assemble_circuits raises error for parameterized circuits without matching binds.""" qr = QuantumRegister(2) x = Parameter("x") y = Parameter("y") full_bound_circ = QuantumCircuit(qr) full_param_circ = QuantumCircuit(qr) partial_param_circ = QuantumCircuit(qr) partial_param_circ.p(x, qr[0]) full_param_circ.p(x, qr[0]) full_param_circ.p(y, qr[1]) partial_bind_args = {"parameter_binds": [{x: 1}, {x: 0}]} full_bind_args = {"parameter_binds": [{x: 1, y: 1}, {x: 0, y: 0}]} inconsistent_bind_args = {"parameter_binds": [{x: 1}, {x: 0, y: 0}]} # Raise when parameters passed for non-parametric circuit self.assertRaises(QiskitError, assemble, full_bound_circ, **partial_bind_args) # Raise when no parameters passed for parametric circuit self.assertRaises(QiskitError, assemble, partial_param_circ) self.assertRaises(QiskitError, assemble, full_param_circ) # Raise when circuit has more parameters than run_config self.assertRaises(QiskitError, assemble, full_param_circ, **partial_bind_args) # Raise when not all circuits have all parameters self.assertRaises( QiskitError, assemble, [full_param_circ, partial_param_circ], **full_bind_args ) # Raise when not all binds have all circuit params self.assertRaises(QiskitError, assemble, full_param_circ, **inconsistent_bind_args) def test_assemble_circuits_rases_for_bind_mismatch_over_expressions(self): """Verify assemble_circuits raises for invalid binds for circuit including ParameterExpressions. """ qr = QuantumRegister(1) x = Parameter("x") y = Parameter("y") expr_circ = QuantumCircuit(qr) expr_circ.p(x + y, qr[0]) partial_bind_args = {"parameter_binds": [{x: 1}, {x: 0}]} # Raise when no parameters passed for parametric circuit self.assertRaises(QiskitError, assemble, expr_circ) # Raise when circuit has more parameters than run_config self.assertRaises(QiskitError, assemble, expr_circ, **partial_bind_args) def test_assemble_circuits_binds_parameters(self): """Verify assemble_circuits applies parameter bindings and output circuits are bound.""" qr = QuantumRegister(1) qc1 = QuantumCircuit(qr) qc2 = QuantumCircuit(qr) qc3 = QuantumCircuit(qr) x = Parameter("x") y = Parameter("y") sum_ = x + y product_ = x * y qc1.u(x, y, 0, qr[0]) qc2.rz(x, qr[0]) qc2.rz(y, qr[0]) qc3.u(sum_, product_, 0, qr[0]) bind_args = {"parameter_binds": [{x: 0, y: 0}, {x: 1, y: 0}, {x: 1, y: 1}]} qobj = assemble([qc1, qc2, qc3], **bind_args) self.assertEqual(len(qobj.experiments), 9) self.assertEqual( [len(expt.instructions) for expt in qobj.experiments], [1, 1, 1, 2, 2, 2, 1, 1, 1] ) def _qobj_inst_params(expt_no, inst_no): expt = qobj.experiments[expt_no] inst = expt.instructions[inst_no] return [float(p) for p in inst.params] self.assertEqual(_qobj_inst_params(0, 0), [0, 0, 0]) self.assertEqual(_qobj_inst_params(1, 0), [1, 0, 0]) self.assertEqual(_qobj_inst_params(2, 0), [1, 1, 0]) self.assertEqual(_qobj_inst_params(3, 0), [0]) self.assertEqual(_qobj_inst_params(3, 1), [0]) self.assertEqual(_qobj_inst_params(4, 0), [1]) self.assertEqual(_qobj_inst_params(4, 1), [0]) self.assertEqual(_qobj_inst_params(5, 0), [1]) self.assertEqual(_qobj_inst_params(5, 1), [1]) self.assertEqual(_qobj_inst_params(6, 0), [0, 0, 0]) self.assertEqual(_qobj_inst_params(7, 0), [1, 0, 0]) self.assertEqual(_qobj_inst_params(8, 0), [2, 1, 0]) def test_init_qubits_default(self): """Check that the init_qubits=None assemble option is passed on to the qobj.""" qobj = assemble(self.circ) self.assertEqual(qobj.config.init_qubits, True) def test_init_qubits_true(self): """Check that the init_qubits=True assemble option is passed on to the qobj.""" qobj = assemble(self.circ, init_qubits=True) self.assertEqual(qobj.config.init_qubits, True) def test_init_qubits_false(self): """Check that the init_qubits=False assemble option is passed on to the qobj.""" qobj = assemble(self.circ, init_qubits=False) self.assertEqual(qobj.config.init_qubits, False) def test_circuit_with_global_phase(self): """Test that global phase for a circuit is handled correctly.""" circ = QuantumCircuit(2) circ.h(0) circ.cx(0, 1) circ.measure_all() circ.global_phase = 0.3 * np.pi qobj = assemble([circ, self.circ]) self.assertEqual(getattr(qobj.experiments[1].header, "global_phase"), 0) self.assertEqual(getattr(qobj.experiments[0].header, "global_phase"), 0.3 * np.pi) def test_circuit_global_phase_gate_definitions(self): """Test circuit with global phase on gate definitions.""" class TestGate(Gate): """dummy gate""" def __init__(self): super().__init__("test_gate", 1, []) def _define(self): circ_def = QuantumCircuit(1) circ_def.x(0) circ_def.global_phase = np.pi self._definition = circ_def gate = TestGate() circ = QuantumCircuit(1) circ.append(gate, [0]) qobj = assemble([circ]) self.assertEqual(getattr(qobj.experiments[0].header, "global_phase"), 0) circ.global_phase = np.pi / 2 qobj = assemble([circ]) self.assertEqual(getattr(qobj.experiments[0].header, "global_phase"), np.pi / 2) def test_pulse_gates_single_circ(self): """Test that we can add calibrations to circuits.""" theta = Parameter("theta") circ = QuantumCircuit(2) circ.h(0) circ.append(RxGate(3.14), [0]) circ.append(RxGate(theta), [1]) circ = circ.assign_parameters({theta: 3.14}) with pulse.build() as custom_h_schedule: pulse.play(pulse.library.Drag(50, 0.15, 4, 2), pulse.DriveChannel(0)) with pulse.build() as x180: pulse.play(pulse.library.Gaussian(50, 0.2, 5), pulse.DriveChannel(1)) circ.add_calibration("h", [0], custom_h_schedule) circ.add_calibration(RxGate(3.14), [0], x180) circ.add_calibration(RxGate(3.14), [1], x180) qobj = assemble(circ, FakeOpenPulse2Q()) # Only one circuit, so everything is stored at the job level cals = qobj.config.calibrations lib = qobj.config.pulse_library self.assertFalse(hasattr(qobj.experiments[0].config, "calibrations")) self.assertEqual([gate.name == "rxtheta" for gate in cals.gates].count(True), 2) self.assertEqual([gate.name == "h" for gate in cals.gates].count(True), 1) self.assertEqual(len(lib), 2) self.assertTrue(all(len(item.samples) == 50 for item in lib)) def test_pulse_gates_with_parameteric_pulses(self): """Test that pulse gates are assembled efficiently for backends that enable parametric pulses. """ with pulse.build() as custom_h_schedule: pulse.play(pulse.library.Drag(50, 0.15, 4, 2), pulse.DriveChannel(0)) circ = QuantumCircuit(2) circ.h(0) circ.add_calibration("h", [0], custom_h_schedule) backend = FakeOpenPulse2Q() backend.configuration().parametric_pulses = ["drag"] qobj = assemble(circ, backend) self.assertFalse(hasattr(qobj.config, "pulse_library")) self.assertTrue(hasattr(qobj.config, "calibrations")) def test_pulse_gates_multiple_circuits(self): """Test one circuit with cals and another without.""" with pulse.build() as dummy_sched: pulse.play(pulse.library.Drag(50, 0.15, 4, 2), pulse.DriveChannel(0)) circ = QuantumCircuit(2) circ.h(0) circ.append(RxGate(3.14), [1]) circ.add_calibration("h", [0], dummy_sched) circ.add_calibration(RxGate(3.14), [1], dummy_sched) circ2 = QuantumCircuit(2) circ2.h(0) qobj = assemble([circ, circ2], FakeOpenPulse2Q()) self.assertEqual(len(qobj.config.pulse_library), 1) self.assertEqual(len(qobj.experiments[0].config.calibrations.gates), 2) self.assertFalse(hasattr(qobj.config, "calibrations")) self.assertFalse(hasattr(qobj.experiments[1].config, "calibrations")) def test_pulse_gates_common_cals(self): """Test that common calibrations are added at the top level.""" with pulse.build() as dummy_sched: pulse.play(pulse.library.Drag(50, 0.15, 4, 2), pulse.DriveChannel(0)) circ = QuantumCircuit(2) circ.h(0) circ.append(RxGate(3.14), [1]) circ.add_calibration("h", [0], dummy_sched) circ.add_calibration(RxGate(3.14), [1], dummy_sched) circ2 = QuantumCircuit(2) circ2.h(0) circ2.add_calibration(RxGate(3.14), [1], dummy_sched) qobj = assemble([circ, circ2], FakeOpenPulse2Q()) # Identical pulses are only added once self.assertEqual(len(qobj.config.pulse_library), 1) # Identical calibrations are only added once self.assertEqual(qobj.config.calibrations.gates[0].name, "rxtheta") self.assertEqual(qobj.config.calibrations.gates[0].params, [3.14]) self.assertEqual(qobj.config.calibrations.gates[0].qubits, [1]) self.assertEqual(len(qobj.experiments[0].config.calibrations.gates), 1) self.assertFalse(hasattr(qobj.experiments[1].config, "calibrations")) def test_assemble_adds_circuit_metadata_to_experiment_header(self): """Verify that any circuit metadata is added to the exeriment header.""" circ = QuantumCircuit(2, metadata={"experiment_type": "gst", "execution_number": "1234"}) qobj = assemble(circ, shots=100, memory=False, seed_simulator=6) self.assertEqual( qobj.experiments[0].header.metadata, {"experiment_type": "gst", "execution_number": "1234"}, ) def test_pulse_gates_delay_only(self): """Test that a single delay gate is translated to an instruction.""" circ = QuantumCircuit(2) circ.append(Gate("test", 1, []), [0]) test_sched = pulse.Delay(64, DriveChannel(0)) + pulse.Delay(160, DriveChannel(0)) circ.add_calibration("test", [0], test_sched) qobj = assemble(circ, FakeOpenPulse2Q()) self.assertEqual(len(qobj.config.calibrations.gates[0].instructions), 2) self.assertEqual( qobj.config.calibrations.gates[0].instructions[1].to_dict(), {"name": "delay", "t0": 64, "ch": "d0", "duration": 160}, ) def test_job_qubit_meas_los_no_range(self): """Test that adding job qubit/meas lo freq lists are assembled into the qobj.config, w/ out any lo range.""" qobj = assemble( self.circ, backend=self.backend, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, ) # convert to ghz qubit_lo_freq_ghz = [freq / 1e9 for freq in self.default_qubit_lo_freq] meas_lo_freq_ghz = [freq / 1e9 for freq in self.default_meas_lo_freq] self.assertEqual(qobj.config.qubit_lo_freq, qubit_lo_freq_ghz) self.assertEqual(qobj.config.meas_lo_freq, meas_lo_freq_ghz) def test_job_lo_errors(self): """Test that job lo's are checked against the lo ranges and that errors are thrown if either quantity has an incorrect length or type.""" qubit_lo_range = [[freq - 5e6, freq + 5e6] for freq in self.default_qubit_lo_freq] meas_lo_range = [[freq - 5e6, freq + 5e6] for freq in self.default_meas_lo_freq] # lo range not a nested list with self.assertRaises(QiskitError): assemble( self.circ, backend=self.backend, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, qubit_lo_range=[4.995e9 for i in range(self.num_qubits)], meas_lo_range=meas_lo_range, ) # qubit lo range inner list not 2d with self.assertRaises(QiskitError): assemble( self.circ, backend=self.backend, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, qubit_lo_range=qubit_lo_range, meas_lo_range=[[6.695e9] for i in range(self.num_qubits)], ) # meas lo range inner list not 2d with self.assertRaises(QiskitError): assemble( self.circ, backend=self.backend, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, qubit_lo_range=qubit_lo_range, meas_lo_range=[[6.695e9] for i in range(self.num_qubits)], ) # qubit lo out of range with self.assertRaises(QiskitError): assemble( self.circ, backend=self.backend, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, qubit_lo_range=[[5.005e9, 5.010e9] for i in range(self.num_qubits)], meas_lo_range=meas_lo_range, ) # meas lo out of range with self.assertRaises(QiskitError): assemble( self.circ, backend=self.backend, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, qubit_lo_range=qubit_lo_range, meas_lo_range=[[6.705e9, 6.710e9] for i in range(self.num_qubits)], ) def test_job_qubit_meas_los_w_range(self): """Test that adding job qubit/meas lo freq lists are assembled into the qobj.config, w/ lo ranges input. Verify that lo ranges do not enter into the config.""" qubit_lo_range = [[freq - 5e6, freq + 5e6] for freq in self.default_qubit_lo_freq] meas_lo_range = [[freq - 5e6, freq + 5e6] for freq in self.default_meas_lo_freq] qobj = assemble( self.circ, backend=self.backend, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, qubit_lo_range=qubit_lo_range, meas_lo_range=meas_lo_range, ) # convert to ghz qubit_lo_freq_ghz = [freq / 1e9 for freq in self.default_qubit_lo_freq] meas_lo_freq_ghz = [freq / 1e9 for freq in self.default_meas_lo_freq] self.assertEqual(qobj.config.qubit_lo_freq, qubit_lo_freq_ghz) self.assertEqual(qobj.config.meas_lo_freq, meas_lo_freq_ghz) self.assertNotIn("qubit_lo_range", qobj.config.to_dict()) self.assertNotIn("meas_lo_range", qobj.config.to_dict()) def test_assemble_single_circ_single_lo_config(self): """Test assembling a single circuit, with a single experiment level lo config.""" qobj = assemble( self.circ, self.backend, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, schedule_los=self.user_lo_config, ) self.assertListEqual(qobj.config.qubit_lo_freq, [5.55, 5, 5, 4.91, 5]) self.assertListEqual(qobj.config.meas_lo_freq, [6.64, 6.7, 6.7, 6.7, 6.1]) self.assertEqual(len(qobj.experiments), 1) def test_assemble_single_circ_single_lo_config_dict(self): """Test assembling a single circuit, with a single experiment level lo config supplied as dictionary.""" qobj = assemble( self.circ, self.backend, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, schedule_los=self.user_lo_config_dict, ) self.assertListEqual(qobj.config.qubit_lo_freq, [5.55, 5, 5, 4.91, 5]) self.assertListEqual(qobj.config.meas_lo_freq, [6.64, 6.7, 6.7, 6.7, 6.1]) self.assertEqual(len(qobj.experiments), 1) def test_assemble_single_circ_multi_lo_config(self): """Test assembling a single circuit, with multiple experiment level lo configs (frequency sweep). """ user_lo_config_dict2 = { pulse.DriveChannel(1): 5.55e9, pulse.MeasureChannel(1): 6.64e9, pulse.DriveChannel(4): 4.91e9, pulse.MeasureChannel(3): 6.1e9, } user_lo_config2 = pulse.LoConfig(user_lo_config_dict2) qobj = assemble( self.circ, self.backend, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, schedule_los=[self.user_lo_config, user_lo_config2], ) qubit_lo_freq_ghz = [freq / 1e9 for freq in self.default_qubit_lo_freq] meas_lo_freq_ghz = [freq / 1e9 for freq in self.default_meas_lo_freq] self.assertListEqual(qobj.config.qubit_lo_freq, qubit_lo_freq_ghz) self.assertListEqual(qobj.config.meas_lo_freq, meas_lo_freq_ghz) self.assertEqual(len(qobj.experiments), 2) # experiment 0 los self.assertEqual(qobj.experiments[0].config.qubit_lo_freq, [5.55, 5, 5, 4.91, 5]) self.assertEqual(qobj.experiments[0].config.meas_lo_freq, [6.64, 6.7, 6.7, 6.7, 6.1]) # experiment 1 los self.assertEqual(qobj.experiments[1].config.qubit_lo_freq, [5, 5.55, 5, 5, 4.91]) self.assertEqual(qobj.experiments[1].config.meas_lo_freq, [6.7, 6.64, 6.7, 6.1, 6.7]) def test_assemble_multi_circ_multi_lo_config(self): """Test assembling circuits, with the same number of experiment level lo configs (n:n setup).""" user_lo_config_dict2 = { pulse.DriveChannel(1): 5.55e9, pulse.MeasureChannel(1): 6.64e9, pulse.DriveChannel(4): 4.91e9, pulse.MeasureChannel(3): 6.1e9, } user_lo_config2 = pulse.LoConfig(user_lo_config_dict2) qobj = assemble( [self.circ, self.circ], self.backend, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, schedule_los=[self.user_lo_config, user_lo_config2], ) qubit_lo_freq_ghz = [freq / 1e9 for freq in self.default_qubit_lo_freq] meas_lo_freq_ghz = [freq / 1e9 for freq in self.default_meas_lo_freq] self.assertListEqual(qobj.config.qubit_lo_freq, qubit_lo_freq_ghz) self.assertListEqual(qobj.config.meas_lo_freq, meas_lo_freq_ghz) self.assertEqual(len(qobj.experiments), 2) # experiment 0 los self.assertEqual(qobj.experiments[0].config.qubit_lo_freq, [5.55, 5, 5, 4.91, 5]) self.assertEqual(qobj.experiments[0].config.meas_lo_freq, [6.64, 6.7, 6.7, 6.7, 6.1]) # experiment 1 los self.assertEqual(qobj.experiments[1].config.qubit_lo_freq, [5, 5.55, 5, 5, 4.91]) self.assertEqual(qobj.experiments[1].config.meas_lo_freq, [6.7, 6.64, 6.7, 6.1, 6.7]) def test_assemble_multi_circ_single_lo_config(self): """Test assembling multiple circuits, with a single experiment level lo config (should override job level).""" qobj = assemble( [self.circ, self.circ], self.backend, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, schedule_los=self.user_lo_config, ) self.assertListEqual(qobj.config.qubit_lo_freq, [5.55, 5, 5, 4.91, 5]) self.assertListEqual(qobj.config.meas_lo_freq, [6.64, 6.7, 6.7, 6.7, 6.1]) self.assertEqual(len(qobj.experiments), 2) def test_assemble_multi_circ_wrong_number_of_multi_lo_configs(self): """Test assembling circuits, with a different number of experiment level lo configs (n:m setup). """ with self.assertRaises(QiskitError): assemble( [self.circ, self.circ, self.circ], self.backend, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, schedule_los=[self.user_lo_config, self.user_lo_config], ) def test_assemble_circ_lo_config_errors(self): """Test that lo config errors are raised properly if experiment level los are provided and some are missing or if default values are not provided. Also check that experiment level lo range is validated.""" # no defaults, but have drive/meas experiment level los for each qubit (no error) full_lo_config_dict = { pulse.DriveChannel(0): 4.85e9, pulse.DriveChannel(1): 4.9e9, pulse.DriveChannel(2): 4.95e9, pulse.DriveChannel(3): 5e9, pulse.DriveChannel(4): 5.05e9, pulse.MeasureChannel(0): 6.8e9, pulse.MeasureChannel(1): 6.85e9, pulse.MeasureChannel(2): 6.9e9, pulse.MeasureChannel(3): 6.95e9, pulse.MeasureChannel(4): 7e9, } qobj = assemble(self.circ, self.backend, schedule_los=full_lo_config_dict) self.assertListEqual(qobj.config.qubit_lo_freq, [4.85, 4.9, 4.95, 5, 5.05]) self.assertListEqual(qobj.config.meas_lo_freq, [6.8, 6.85, 6.9, 6.95, 7]) self.assertEqual(len(qobj.experiments), 1) # no defaults and missing experiment level drive lo raises missing_drive_lo_config_dict = copy.deepcopy(full_lo_config_dict) missing_drive_lo_config_dict.pop(pulse.DriveChannel(0)) with self.assertRaises(QiskitError): qobj = assemble(self.circ, self.backend, schedule_los=missing_drive_lo_config_dict) # no defaults and missing experiment level meas lo raises missing_meas_lo_config_dict = copy.deepcopy(full_lo_config_dict) missing_meas_lo_config_dict.pop(pulse.MeasureChannel(0)) with self.assertRaises(QiskitError): qobj = assemble(self.circ, self.backend, schedule_los=missing_meas_lo_config_dict) # verify lo ranges are checked at experiment level lo_values = list(full_lo_config_dict.values()) qubit_lo_range = [[freq - 5e6, freq + 5e6] for freq in lo_values[:5]] meas_lo_range = [[freq - 5e6, freq + 5e6] for freq in lo_values[5:]] # out of range drive lo full_lo_config_dict[pulse.DriveChannel(0)] -= 5.5e6 with self.assertRaises(QiskitError): qobj = assemble( self.circ, self.backend, qubit_lo_range=qubit_lo_range, schedule_los=full_lo_config_dict, ) full_lo_config_dict[pulse.DriveChannel(0)] += 5.5e6 # reset drive value # out of range meas lo full_lo_config_dict[pulse.MeasureChannel(0)] += 5.5e6 with self.assertRaises(QiskitError): qobj = assemble( self.circ, self.backend, meas_lo_range=meas_lo_range, schedule_los=full_lo_config_dict, ) class TestPulseAssembler(QiskitTestCase): """Tests for assembling schedules to qobj.""" def setUp(self): super().setUp() self.backend = FakeOpenPulse2Q() self.backend_config = self.backend.configuration() test_pulse = pulse.Waveform( samples=np.array([0.02739068, 0.05, 0.05, 0.05, 0.02739068], dtype=np.complex128), name="pulse0", ) self.schedule = pulse.Schedule(name="fake_experiment") self.schedule = self.schedule.insert(0, Play(test_pulse, self.backend_config.drive(0))) for i in range(self.backend_config.n_qubits): self.schedule = self.schedule.insert( 5, Acquire(5, self.backend_config.acquire(i), MemorySlot(i)) ) self.user_lo_config_dict = {self.backend_config.drive(0): 4.91e9} self.user_lo_config = pulse.LoConfig(self.user_lo_config_dict) self.default_qubit_lo_freq = [4.9e9, 5.0e9] self.default_meas_lo_freq = [6.5e9, 6.6e9] self.config = {"meas_level": 1, "memory_slot_size": 100, "meas_return": "avg"} self.header = {"backend_name": "FakeOpenPulse2Q", "backend_version": "0.0.0"} def test_assemble_adds_schedule_metadata_to_experiment_header(self): """Verify that any circuit metadata is added to the exeriment header.""" self.schedule.metadata = {"experiment_type": "gst", "execution_number": "1234"} qobj = assemble( self.schedule, shots=100, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, schedule_los=[], ) self.assertEqual( qobj.experiments[0].header.metadata, {"experiment_type": "gst", "execution_number": "1234"}, ) def test_assemble_sample_pulse(self): """Test that the pulse lib and qobj instruction can be paired up.""" schedule = pulse.Schedule() schedule += pulse.Play( pulse.Waveform([0.1] * 16, name="test0"), pulse.DriveChannel(0), name="test1" ) schedule += pulse.Play( pulse.Waveform([0.1] * 16, name="test1"), pulse.DriveChannel(0), name="test2" ) schedule += pulse.Play( pulse.Waveform([0.5] * 16, name="test0"), pulse.DriveChannel(0), name="test1" ) qobj = assemble( schedule, qobj_header=self.header, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, schedule_los=[], **self.config, ) test_dict = qobj.to_dict() experiment = test_dict["experiments"][0] inst0_name = experiment["instructions"][0]["name"] inst1_name = experiment["instructions"][1]["name"] inst2_name = experiment["instructions"][2]["name"] pulses = {} for item in test_dict["config"]["pulse_library"]: pulses[item["name"]] = item["samples"] self.assertTrue(all(name in pulses for name in [inst0_name, inst1_name, inst2_name])) # Their pulses are the same self.assertEqual(inst0_name, inst1_name) self.assertTrue(np.allclose(pulses[inst0_name], [0.1] * 16)) self.assertTrue(np.allclose(pulses[inst2_name], [0.5] * 16)) def test_assemble_single_schedule_without_lo_config(self): """Test assembling a single schedule, no lo config.""" qobj = assemble( self.schedule, qobj_header=self.header, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, schedule_los=[], **self.config, ) test_dict = qobj.to_dict() self.assertListEqual(test_dict["config"]["qubit_lo_freq"], [4.9, 5.0]) self.assertEqual(len(test_dict["experiments"]), 1) self.assertEqual(len(test_dict["experiments"][0]["instructions"]), 2) def test_assemble_multi_schedules_without_lo_config(self): """Test assembling schedules, no lo config.""" qobj = assemble( [self.schedule, self.schedule], qobj_header=self.header, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, **self.config, ) test_dict = qobj.to_dict() self.assertListEqual(test_dict["config"]["qubit_lo_freq"], [4.9, 5.0]) self.assertEqual(len(test_dict["experiments"]), 2) self.assertEqual(len(test_dict["experiments"][0]["instructions"]), 2) def test_assemble_single_schedule_with_lo_config(self): """Test assembling a single schedule, with a single lo config.""" qobj = assemble( self.schedule, qobj_header=self.header, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, schedule_los=self.user_lo_config, **self.config, ) test_dict = qobj.to_dict() self.assertListEqual(test_dict["config"]["qubit_lo_freq"], [4.91, 5.0]) self.assertEqual(len(test_dict["experiments"]), 1) self.assertEqual(len(test_dict["experiments"][0]["instructions"]), 2) def test_assemble_single_schedule_with_lo_config_dict(self): """Test assembling a single schedule, with a single lo config supplied as dictionary.""" qobj = assemble( self.schedule, qobj_header=self.header, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, schedule_los=self.user_lo_config_dict, **self.config, ) test_dict = qobj.to_dict() self.assertListEqual(test_dict["config"]["qubit_lo_freq"], [4.91, 5.0]) self.assertEqual(len(test_dict["experiments"]), 1) self.assertEqual(len(test_dict["experiments"][0]["instructions"]), 2) def test_assemble_single_schedule_with_multi_lo_configs(self): """Test assembling a single schedule, with multiple lo configs (frequency sweep).""" qobj = assemble( self.schedule, qobj_header=self.header, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, schedule_los=[self.user_lo_config, self.user_lo_config], **self.config, ) test_dict = qobj.to_dict() self.assertListEqual(test_dict["config"]["qubit_lo_freq"], [4.9, 5.0]) self.assertEqual(len(test_dict["experiments"]), 2) self.assertEqual(len(test_dict["experiments"][0]["instructions"]), 2) self.assertDictEqual(test_dict["experiments"][0]["config"], {"qubit_lo_freq": [4.91, 5.0]}) def test_assemble_multi_schedules_with_multi_lo_configs(self): """Test assembling schedules, with the same number of lo configs (n:n setup).""" qobj = assemble( [self.schedule, self.schedule], qobj_header=self.header, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, schedule_los=[self.user_lo_config, self.user_lo_config], **self.config, ) test_dict = qobj.to_dict() self.assertListEqual(test_dict["config"]["qubit_lo_freq"], [4.9, 5.0]) self.assertEqual(len(test_dict["experiments"]), 2) self.assertEqual(len(test_dict["experiments"][0]["instructions"]), 2) self.assertDictEqual(test_dict["experiments"][0]["config"], {"qubit_lo_freq": [4.91, 5.0]}) def test_assemble_multi_schedules_with_wrong_number_of_multi_lo_configs(self): """Test assembling schedules, with a different number of lo configs (n:m setup).""" with self.assertRaises(QiskitError): assemble( [self.schedule, self.schedule, self.schedule], qobj_header=self.header, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, schedule_los=[self.user_lo_config, self.user_lo_config], **self.config, ) def test_assemble_meas_map(self): """Test assembling a single schedule, no lo config.""" schedule = Schedule(name="fake_experiment") schedule = schedule.insert(5, Acquire(5, AcquireChannel(0), MemorySlot(0))) schedule = schedule.insert(5, Acquire(5, AcquireChannel(1), MemorySlot(1))) qobj = assemble( schedule, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, meas_map=[[0], [1]], ) self.assertIsInstance(qobj, PulseQobj) qobj = assemble( schedule, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, meas_map=[[0, 1, 2]], ) self.assertIsInstance(qobj, PulseQobj) def test_assemble_memory_slots(self): """Test assembling a schedule and inferring number of memoryslots.""" n_memoryslots = 10 # single acquisition schedule = Acquire( 5, self.backend_config.acquire(0), mem_slot=pulse.MemorySlot(n_memoryslots - 1) ) qobj = assemble( schedule, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, meas_map=[[0], [1]], ) self.assertEqual(qobj.config.memory_slots, n_memoryslots) # this should be in experimental header as well self.assertEqual(qobj.experiments[0].header.memory_slots, n_memoryslots) # multiple acquisition schedule = Acquire( 5, self.backend_config.acquire(0), mem_slot=pulse.MemorySlot(n_memoryslots - 1) ) schedule = schedule.insert( 10, Acquire( 5, self.backend_config.acquire(0), mem_slot=pulse.MemorySlot(n_memoryslots - 1) ), ) qobj = assemble( schedule, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, meas_map=[[0], [1]], ) self.assertEqual(qobj.config.memory_slots, n_memoryslots) # this should be in experimental header as well self.assertEqual(qobj.experiments[0].header.memory_slots, n_memoryslots) def test_assemble_memory_slots_for_schedules(self): """Test assembling schedules with different memory slots.""" n_memoryslots = [10, 5, 7] schedules = [] for n_memoryslot in n_memoryslots: schedule = Acquire( 5, self.backend_config.acquire(0), mem_slot=pulse.MemorySlot(n_memoryslot - 1) ) schedules.append(schedule) qobj = assemble( schedules, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, meas_map=[[0], [1]], ) self.assertEqual(qobj.config.memory_slots, max(n_memoryslots)) self.assertEqual(qobj.experiments[0].header.memory_slots, n_memoryslots[0]) self.assertEqual(qobj.experiments[1].header.memory_slots, n_memoryslots[1]) self.assertEqual(qobj.experiments[2].header.memory_slots, n_memoryslots[2]) def test_pulse_name_conflicts(self): """Test that pulse name conflicts can be resolved.""" name_conflict_pulse = pulse.Waveform( samples=np.array([0.02, 0.05, 0.05, 0.05, 0.02], dtype=np.complex128), name="pulse0" ) self.schedule = self.schedule.insert( 1, Play(name_conflict_pulse, self.backend_config.drive(1)) ) qobj = assemble( self.schedule, qobj_header=self.header, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, schedule_los=[], **self.config, ) self.assertNotEqual(qobj.config.pulse_library[0].name, qobj.config.pulse_library[1].name) def test_pulse_name_conflicts_in_other_schedule(self): """Test two pulses with the same name in different schedule can be resolved.""" backend = FakeHanoi() defaults = backend.defaults() schedules = [] ch_d0 = pulse.DriveChannel(0) for amp in (0.1, 0.2): sched = Schedule() sched += Play(gaussian(duration=100, amp=amp, sigma=30, name="my_pulse"), ch_d0) sched += measure(qubits=[0], backend=backend) << 100 schedules.append(sched) qobj = assemble( schedules, qubit_lo_freq=defaults.qubit_freq_est, meas_lo_freq=defaults.meas_freq_est ) # two user pulses and one measurement pulse should be contained self.assertEqual(len(qobj.config.pulse_library), 3) def test_assemble_with_delay(self): """Test that delay instruction is not ignored in assembly.""" delay_schedule = pulse.Delay(10, self.backend_config.drive(0)) delay_schedule += self.schedule delay_qobj = assemble(delay_schedule, self.backend) self.assertEqual(delay_qobj.experiments[0].instructions[0].name, "delay") self.assertEqual(delay_qobj.experiments[0].instructions[0].duration, 10) self.assertEqual(delay_qobj.experiments[0].instructions[0].t0, 0) def test_delay_removed_on_acq_ch(self): """Test that delay instructions on acquire channels are skipped on assembly with times shifted properly. """ delay0 = pulse.Delay(5, self.backend_config.acquire(0)) delay1 = pulse.Delay(7, self.backend_config.acquire(1)) sched0 = delay0 sched0 += self.schedule # includes ``Acquire`` instr sched0 += delay1 sched1 = self.schedule # includes ``Acquire`` instr sched1 += delay0 sched1 += delay1 sched2 = delay0 sched2 += delay1 sched2 += self.schedule # includes ``Acquire`` instr delay_qobj = assemble([sched0, sched1, sched2], self.backend) # check that no delay instrs occur on acquire channels is_acq_delay = False for exp in delay_qobj.experiments: for instr in exp.instructions: if instr.name == "delay" and "a" in instr.ch: is_acq_delay = True self.assertFalse(is_acq_delay) # check that acquire instr are shifted from ``t0=5`` as needed self.assertEqual(delay_qobj.experiments[0].instructions[1].t0, 10) self.assertEqual(delay_qobj.experiments[0].instructions[1].name, "acquire") self.assertEqual(delay_qobj.experiments[1].instructions[1].t0, 5) self.assertEqual(delay_qobj.experiments[1].instructions[1].name, "acquire") self.assertEqual(delay_qobj.experiments[2].instructions[1].t0, 12) self.assertEqual(delay_qobj.experiments[2].instructions[1].name, "acquire") def test_assemble_schedule_enum(self): """Test assembling a schedule with enum input values to assemble.""" qobj = assemble( self.schedule, qobj_header=self.header, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, schedule_los=[], meas_level=MeasLevel.CLASSIFIED, meas_return=MeasReturnType.AVERAGE, ) test_dict = qobj.to_dict() self.assertEqual(test_dict["config"]["meas_return"], "avg") self.assertEqual(test_dict["config"]["meas_level"], 2) def test_assemble_parametric(self): """Test that parametric pulses can be assembled properly into a PulseQobj.""" amp = [0.5, 0.6, 1, 0.2] angle = [np.pi / 2, 0.6, 0, 0] sched = pulse.Schedule(name="test_parametric") sched += Play( pulse.Gaussian(duration=25, sigma=4, amp=amp[0], angle=angle[0]), DriveChannel(0) ) sched += Play( pulse.Drag(duration=25, amp=amp[1], angle=angle[1], sigma=7.8, beta=4), DriveChannel(1) ) sched += Play(pulse.Constant(duration=25, amp=amp[2], angle=angle[2]), DriveChannel(2)) sched += ( Play( pulse.GaussianSquare(duration=150, amp=amp[3], angle=angle[3], sigma=8, width=140), MeasureChannel(0), ) << sched.duration ) backend = FakeOpenPulse3Q() backend.configuration().parametric_pulses = [ "gaussian", "drag", "gaussian_square", "constant", ] qobj = assemble(sched, backend) self.assertEqual(qobj.config.pulse_library, []) qobj_insts = qobj.experiments[0].instructions self.assertTrue(all(inst.name == "parametric_pulse" for inst in qobj_insts)) self.assertEqual(qobj_insts[0].pulse_shape, "gaussian") self.assertEqual(qobj_insts[1].pulse_shape, "drag") self.assertEqual(qobj_insts[2].pulse_shape, "constant") self.assertEqual(qobj_insts[3].pulse_shape, "gaussian_square") self.assertDictEqual( qobj_insts[0].parameters, {"duration": 25, "sigma": 4, "amp": amp[0] * np.exp(1j * angle[0])}, ) self.assertDictEqual( qobj_insts[1].parameters, {"duration": 25, "sigma": 7.8, "amp": amp[1] * np.exp(1j * angle[1]), "beta": 4}, ) self.assertDictEqual( qobj_insts[2].parameters, {"duration": 25, "amp": amp[2] * np.exp(1j * angle[2])} ) self.assertDictEqual( qobj_insts[3].parameters, {"duration": 150, "sigma": 8, "amp": amp[3] * np.exp(1j * angle[3]), "width": 140}, ) self.assertEqual( qobj.to_dict()["experiments"][0]["instructions"][0]["parameters"]["amp"], amp[0] * np.exp(1j * angle[0]), ) def test_assemble_parametric_unsupported(self): """Test that parametric pulses are translated to Waveform if they're not supported by the backend during assemble time. """ sched = pulse.Schedule(name="test_parametric_to_sample_pulse") sched += Play( pulse.Drag(duration=25, amp=0.5, angle=-0.3, sigma=7.8, beta=4), DriveChannel(1) ) sched += Play(pulse.Constant(duration=25, amp=1), DriveChannel(2)) backend = FakeOpenPulse3Q() backend.configuration().parametric_pulses = ["something_extra"] qobj = assemble(sched, backend) self.assertNotEqual(qobj.config.pulse_library, []) qobj_insts = qobj.experiments[0].instructions self.assertFalse(hasattr(qobj_insts[0], "pulse_shape")) def test_assemble_parametric_pulse_kwarg_with_backend_setting(self): """Test that parametric pulses respect the kwarg over backend""" backend = FakeHanoi() qc = QuantumCircuit(1, 1) qc.x(0) qc.measure(0, 0) with pulse.build(backend, name="x") as x_q0: pulse.play(pulse.Gaussian(duration=128, amp=0.1, sigma=16), pulse.drive_channel(0)) qc.add_calibration("x", (0,), x_q0) qobj = assemble(qc, backend, parametric_pulses=["gaussian"]) self.assertEqual(qobj.config.parametric_pulses, ["gaussian"]) def test_assemble_parametric_pulse_kwarg_empty_list_with_backend_setting(self): """Test that parametric pulses respect the kwarg as empty list over backend""" backend = FakeHanoi() qc = QuantumCircuit(1, 1) qc.x(0) qc.measure(0, 0) with pulse.build(backend, name="x") as x_q0: pulse.play(pulse.Gaussian(duration=128, amp=0.1, sigma=16), pulse.drive_channel(0)) qc.add_calibration("x", (0,), x_q0) qobj = assemble(qc, backend, parametric_pulses=[]) self.assertEqual(qobj.config.parametric_pulses, []) def test_init_qubits_default(self): """Check that the init_qubits=None assemble option is passed on to the qobj.""" qobj = assemble(self.schedule, self.backend) self.assertEqual(qobj.config.init_qubits, True) def test_init_qubits_true(self): """Check that the init_qubits=True assemble option is passed on to the qobj.""" qobj = assemble(self.schedule, self.backend, init_qubits=True) self.assertEqual(qobj.config.init_qubits, True) def test_init_qubits_false(self): """Check that the init_qubits=False assemble option is passed on to the qobj.""" qobj = assemble(self.schedule, self.backend, init_qubits=False) self.assertEqual(qobj.config.init_qubits, False) def test_assemble_backend_rep_times_delays(self): """Check that rep_time and rep_delay are properly set from backend values.""" # use first entry from allowed backend values rep_times = [2.0, 3.0, 4.0] # sec rep_delay_range = [2.5e-3, 4.5e-3] default_rep_delay = 3.0e-3 self.backend_config.rep_times = rep_times setattr(self.backend_config, "rep_delay_range", rep_delay_range) setattr(self.backend_config, "default_rep_delay", default_rep_delay) # dynamic rep rates off qobj = assemble(self.schedule, self.backend) self.assertEqual(qobj.config.rep_time, int(rep_times[0] * 1e6)) self.assertEqual(hasattr(qobj.config, "rep_delay"), False) # dynamic rep rates on setattr(self.backend_config, "dynamic_reprate_enabled", True) # RuntimeWarning bc ``rep_time`` is specified`` when dynamic rep rates not enabled with self.assertWarns(RuntimeWarning): qobj = assemble(self.schedule, self.backend) self.assertEqual(qobj.config.rep_time, int(rep_times[0] * 1e6)) self.assertEqual(qobj.config.rep_delay, default_rep_delay * 1e6) def test_assemble_user_rep_time_delay(self): """Check that user runtime config rep_time and rep_delay work.""" # set custom rep_time and rep_delay in runtime config rep_time = 200.0e-6 rep_delay = 2.5e-6 self.config["rep_time"] = rep_time self.config["rep_delay"] = rep_delay # dynamic rep rates off # RuntimeWarning bc using ``rep_delay`` when dynamic rep rates off with self.assertWarns(RuntimeWarning): qobj = assemble(self.schedule, self.backend, **self.config) self.assertEqual(qobj.config.rep_time, int(rep_time * 1e6)) self.assertEqual(hasattr(qobj.config, "rep_delay"), False) # now remove rep_delay and enable dynamic rep rates # RuntimeWarning bc using ``rep_time`` when dynamic rep rates are enabled del self.config["rep_delay"] setattr(self.backend_config, "dynamic_reprate_enabled", True) with self.assertWarns(RuntimeWarning): qobj = assemble(self.schedule, self.backend, **self.config) self.assertEqual(qobj.config.rep_time, int(rep_time * 1e6)) self.assertEqual(hasattr(qobj.config, "rep_delay"), False) # use ``default_rep_delay`` # ``rep_time`` comes from allowed backend rep_times rep_times = [0.5, 1.0, 1.5] # sec self.backend_config.rep_times = rep_times setattr(self.backend_config, "rep_delay_range", [0, 3.0e-6]) setattr(self.backend_config, "default_rep_delay", 2.2e-6) del self.config["rep_time"] qobj = assemble(self.schedule, self.backend, **self.config) self.assertEqual(qobj.config.rep_time, int(rep_times[0] * 1e6)) self.assertEqual(qobj.config.rep_delay, 2.2) # use qobj ``default_rep_delay`` self.config["rep_delay"] = 1.5e-6 qobj = assemble(self.schedule, self.backend, **self.config) self.assertEqual(qobj.config.rep_time, int(rep_times[0] * 1e6)) self.assertEqual(qobj.config.rep_delay, 1.5) # use ``rep_delay`` outside of ``rep_delay_range self.config["rep_delay"] = 5.0e-6 with self.assertRaises(QiskitError): assemble(self.schedule, self.backend, **self.config) def test_assemble_with_individual_discriminators(self): """Test that assembly works with individual discriminators.""" disc_one = Discriminator("disc_one", test_params=True) disc_two = Discriminator("disc_two", test_params=False) schedule = Schedule() schedule = schedule.append( Acquire(5, AcquireChannel(0), MemorySlot(0), discriminator=disc_one), ) schedule = schedule.append( Acquire(5, AcquireChannel(1), MemorySlot(1), discriminator=disc_two), ) qobj = assemble( schedule, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, meas_map=[[0, 1]], ) qobj_discriminators = qobj.experiments[0].instructions[0].discriminators self.assertEqual(len(qobj_discriminators), 2) self.assertEqual(qobj_discriminators[0].name, "disc_one") self.assertEqual(qobj_discriminators[0].params["test_params"], True) self.assertEqual(qobj_discriminators[1].name, "disc_two") self.assertEqual(qobj_discriminators[1].params["test_params"], False) def test_assemble_with_single_discriminators(self): """Test that assembly works with both a single discriminator.""" disc_one = Discriminator("disc_one", test_params=True) schedule = Schedule() schedule = schedule.append( Acquire(5, AcquireChannel(0), MemorySlot(0), discriminator=disc_one), ) schedule = schedule.append( Acquire(5, AcquireChannel(1), MemorySlot(1)), ) qobj = assemble( schedule, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, meas_map=[[0, 1]], ) qobj_discriminators = qobj.experiments[0].instructions[0].discriminators self.assertEqual(len(qobj_discriminators), 1) self.assertEqual(qobj_discriminators[0].name, "disc_one") self.assertEqual(qobj_discriminators[0].params["test_params"], True) def test_assemble_with_unequal_discriminators(self): """Test that assembly works with incorrect number of discriminators for number of qubits.""" disc_one = Discriminator("disc_one", test_params=True) disc_two = Discriminator("disc_two", test_params=False) schedule = Schedule() schedule += Acquire(5, AcquireChannel(0), MemorySlot(0), discriminator=disc_one) schedule += Acquire(5, AcquireChannel(1), MemorySlot(1), discriminator=disc_two) schedule += Acquire(5, AcquireChannel(2), MemorySlot(2)) with self.assertRaises(QiskitError): assemble( schedule, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, meas_map=[[0, 1, 2]], ) def test_assemble_with_individual_kernels(self): """Test that assembly works with individual kernels.""" disc_one = Kernel("disc_one", test_params=True) disc_two = Kernel("disc_two", test_params=False) schedule = Schedule() schedule = schedule.append( Acquire(5, AcquireChannel(0), MemorySlot(0), kernel=disc_one), ) schedule = schedule.append( Acquire(5, AcquireChannel(1), MemorySlot(1), kernel=disc_two), ) qobj = assemble( schedule, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, meas_map=[[0, 1]], ) qobj_kernels = qobj.experiments[0].instructions[0].kernels self.assertEqual(len(qobj_kernels), 2) self.assertEqual(qobj_kernels[0].name, "disc_one") self.assertEqual(qobj_kernels[0].params["test_params"], True) self.assertEqual(qobj_kernels[1].name, "disc_two") self.assertEqual(qobj_kernels[1].params["test_params"], False) def test_assemble_with_single_kernels(self): """Test that assembly works with both a single kernel.""" disc_one = Kernel("disc_one", test_params=True) schedule = Schedule() schedule = schedule.append( Acquire(5, AcquireChannel(0), MemorySlot(0), kernel=disc_one), ) schedule = schedule.append( Acquire(5, AcquireChannel(1), MemorySlot(1)), ) qobj = assemble( schedule, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, meas_map=[[0, 1]], ) qobj_kernels = qobj.experiments[0].instructions[0].kernels self.assertEqual(len(qobj_kernels), 1) self.assertEqual(qobj_kernels[0].name, "disc_one") self.assertEqual(qobj_kernels[0].params["test_params"], True) def test_assemble_with_unequal_kernels(self): """Test that assembly works with incorrect number of discriminators for number of qubits.""" disc_one = Kernel("disc_one", test_params=True) disc_two = Kernel("disc_two", test_params=False) schedule = Schedule() schedule += Acquire(5, AcquireChannel(0), MemorySlot(0), kernel=disc_one) schedule += Acquire(5, AcquireChannel(1), MemorySlot(1), kernel=disc_two) schedule += Acquire(5, AcquireChannel(2), MemorySlot(2)) with self.assertRaises(QiskitError): assemble( schedule, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, meas_map=[[0, 1, 2]], ) def test_assemble_single_instruction(self): """Test assembling schedules, no lo config.""" inst = pulse.Play(pulse.Constant(100, 1.0), pulse.DriveChannel(0)) self.assertIsInstance(assemble(inst, self.backend), PulseQobj) def test_assemble_overlapping_time(self): """Test that assembly errors when qubits are measured in overlapping time.""" schedule = Schedule() schedule = schedule.append( Acquire(5, AcquireChannel(0), MemorySlot(0)), ) schedule = schedule.append( Acquire(5, AcquireChannel(1), MemorySlot(1)) << 1, ) with self.assertRaises(QiskitError): assemble( schedule, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, meas_map=[[0, 1]], ) def test_assemble_meas_map_vs_insts(self): """Test that assembly errors when the qubits are measured in overlapping time and qubits are not in the first meas_map list.""" schedule = Schedule() schedule += Acquire(5, AcquireChannel(0), MemorySlot(0)) schedule += Acquire(5, AcquireChannel(1), MemorySlot(1)) schedule += Acquire(5, AcquireChannel(2), MemorySlot(2)) << 2 schedule += Acquire(5, AcquireChannel(3), MemorySlot(3)) << 2 with self.assertRaises(QiskitError): assemble( schedule, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, meas_map=[[0], [1, 2], [3]], ) def test_assemble_non_overlapping_time_single_meas_map(self): """Test that assembly works when qubits are measured in non-overlapping time within the same measurement map list.""" schedule = Schedule() schedule = schedule.append( Acquire(5, AcquireChannel(0), MemorySlot(0)), ) schedule = schedule.append( Acquire(5, AcquireChannel(1), MemorySlot(1)) << 5, ) qobj = assemble( schedule, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, meas_map=[[0, 1]], ) self.assertIsInstance(qobj, PulseQobj) def test_assemble_disjoint_time(self): """Test that assembly works when qubits are in disjoint meas map sets.""" schedule = Schedule() schedule = schedule.append( Acquire(5, AcquireChannel(0), MemorySlot(0)), ) schedule = schedule.append( Acquire(5, AcquireChannel(1), MemorySlot(1)) << 1, ) qobj = assemble( schedule, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, meas_map=[[0, 2], [1, 3]], ) self.assertIsInstance(qobj, PulseQobj) def test_assemble_valid_qubits(self): """Test that assembly works when qubits that are in the measurement map is measured.""" schedule = Schedule() schedule = schedule.append( Acquire(5, AcquireChannel(1), MemorySlot(1)), ) schedule = schedule.append( Acquire(5, AcquireChannel(2), MemorySlot(2)), ) schedule = schedule.append( Acquire(5, AcquireChannel(3), MemorySlot(3)), ) qobj = assemble( schedule, qubit_lo_freq=self.default_qubit_lo_freq, meas_lo_freq=self.default_meas_lo_freq, meas_map=[[0, 1, 2], [3]], ) self.assertIsInstance(qobj, PulseQobj) class TestPulseAssemblerMissingKwargs(QiskitTestCase): """Verify that errors are raised in case backend is not provided and kwargs are missing.""" def setUp(self): super().setUp() self.schedule = pulse.Schedule(name="fake_experiment") self.backend = FakeOpenPulse2Q() self.config = self.backend.configuration() self.defaults = self.backend.defaults() self.qubit_lo_freq = list(self.defaults.qubit_freq_est) self.meas_lo_freq = list(self.defaults.meas_freq_est) self.qubit_lo_range = self.config.qubit_lo_range self.meas_lo_range = self.config.meas_lo_range self.schedule_los = { pulse.DriveChannel(0): self.qubit_lo_freq[0], pulse.DriveChannel(1): self.qubit_lo_freq[1], pulse.MeasureChannel(0): self.meas_lo_freq[0], pulse.MeasureChannel(1): self.meas_lo_freq[1], } self.meas_map = self.config.meas_map self.memory_slots = self.config.n_qubits # default rep_time and rep_delay self.rep_time = self.config.rep_times[0] self.rep_delay = None def test_defaults(self): """Test defaults work.""" qobj = assemble( self.schedule, qubit_lo_freq=self.qubit_lo_freq, meas_lo_freq=self.meas_lo_freq, qubit_lo_range=self.qubit_lo_range, meas_lo_range=self.meas_lo_range, schedule_los=self.schedule_los, meas_map=self.meas_map, memory_slots=self.memory_slots, rep_time=self.rep_time, rep_delay=self.rep_delay, ) self.assertIsInstance(qobj, PulseQobj) def test_missing_qubit_lo_freq(self): """Test error raised if qubit_lo_freq missing.""" with self.assertRaises(QiskitError): assemble( self.schedule, qubit_lo_freq=None, meas_lo_freq=self.meas_lo_freq, qubit_lo_range=self.qubit_lo_range, meas_lo_range=self.meas_lo_range, meas_map=self.meas_map, memory_slots=self.memory_slots, rep_time=self.rep_time, rep_delay=self.rep_delay, ) def test_missing_meas_lo_freq(self): """Test error raised if meas_lo_freq missing.""" with self.assertRaises(QiskitError): assemble( self.schedule, qubit_lo_freq=self.qubit_lo_freq, meas_lo_freq=None, qubit_lo_range=self.qubit_lo_range, meas_lo_range=self.meas_lo_range, meas_map=self.meas_map, memory_slots=self.memory_slots, rep_time=self.rep_time, rep_delay=self.rep_delay, ) def test_missing_memory_slots(self): """Test error is not raised if memory_slots are missing.""" qobj = assemble( self.schedule, qubit_lo_freq=self.qubit_lo_freq, meas_lo_freq=self.meas_lo_freq, qubit_lo_range=self.qubit_lo_range, meas_lo_range=self.meas_lo_range, schedule_los=self.schedule_los, meas_map=self.meas_map, memory_slots=None, rep_time=self.rep_time, rep_delay=self.rep_delay, ) self.assertIsInstance(qobj, PulseQobj) def test_missing_rep_time_and_delay(self): """Test qobj is valid if rep_time and rep_delay are missing.""" qobj = assemble( self.schedule, qubit_lo_freq=self.qubit_lo_freq, meas_lo_freq=self.meas_lo_freq, qubit_lo_range=self.qubit_lo_range, meas_lo_range=self.meas_lo_range, schedule_los=self.schedule_los, meas_map=self.meas_map, memory_slots=None, rep_time=None, rep_delay=None, ) self.assertEqual(hasattr(qobj, "rep_time"), False) self.assertEqual(hasattr(qobj, "rep_delay"), False) def test_missing_meas_map(self): """Test that assembly still works if meas_map is missing.""" qobj = assemble( self.schedule, qubit_lo_freq=self.qubit_lo_freq, meas_lo_freq=self.meas_lo_freq, qubit_lo_range=self.qubit_lo_range, meas_lo_range=self.meas_lo_range, schedule_los=self.schedule_los, meas_map=None, memory_slots=self.memory_slots, rep_time=self.rep_time, rep_delay=self.rep_delay, ) self.assertIsInstance(qobj, PulseQobj) def test_missing_lo_ranges(self): """Test that assembly still works if lo_ranges are missing.""" qobj = assemble( self.schedule, qubit_lo_freq=self.qubit_lo_freq, meas_lo_freq=self.meas_lo_freq, qubit_lo_range=None, meas_lo_range=None, schedule_los=self.schedule_los, meas_map=self.meas_map, memory_slots=self.memory_slots, rep_time=self.rep_time, rep_delay=self.rep_delay, ) self.assertIsInstance(qobj, PulseQobj) def test_unsupported_meas_level(self): """Test that assembly raises an error if meas_level is not supported""" backend = FakeOpenPulse2Q() backend.configuration().meas_levels = [1, 2] with self.assertRaises(QiskitError): assemble( self.schedule, backend, qubit_lo_freq=self.qubit_lo_freq, meas_lo_freq=self.meas_lo_freq, qubit_lo_range=self.qubit_lo_range, meas_lo_range=self.meas_lo_range, schedule_los=self.schedule_los, meas_level=0, meas_map=self.meas_map, memory_slots=self.memory_slots, rep_time=self.rep_time, rep_delay=self.rep_delay, ) def test_single_and_deprecated_acquire_styles(self): """Test that acquires are identically combined with Acquires that take a single channel.""" backend = FakeOpenPulse2Q() new_style_schedule = Schedule() acq_dur = 1200 for i in range(2): new_style_schedule += Acquire(acq_dur, AcquireChannel(i), MemorySlot(i)) deprecated_style_schedule = Schedule() for i in range(2): deprecated_style_schedule += Acquire(1200, AcquireChannel(i), MemorySlot(i)) # The Qobj IDs will be different n_qobj = assemble(new_style_schedule, backend) n_qobj.qobj_id = None n_qobj.experiments[0].header.name = None d_qobj = assemble(deprecated_style_schedule, backend) d_qobj.qobj_id = None d_qobj.experiments[0].header.name = None self.assertEqual(n_qobj, d_qobj) assembled_acquire = n_qobj.experiments[0].instructions[0] self.assertEqual(assembled_acquire.qubits, [0, 1]) self.assertEqual(assembled_acquire.memory_slot, [0, 1]) class StreamHandlerRaiseException(StreamHandler): """Handler class that will raise an exception on formatting errors.""" def handleError(self, record): raise sys.exc_info() class TestLogAssembler(QiskitTestCase): """Testing the log_assembly option.""" def setUp(self): super().setUp() logger = getLogger() self.addCleanup(logger.setLevel, logger.level) logger.setLevel("DEBUG") self.output = io.StringIO() logger.addHandler(StreamHandlerRaiseException(self.output)) self.circuit = QuantumCircuit(QuantumRegister(1)) def assertAssembleLog(self, log_msg): """Runs assemble and checks for logs containing specified message""" assemble(self.circuit, shots=2000, memory=True) self.output.seek(0) # Filter unrelated log lines output_lines = self.output.readlines() assembly_log_lines = [x for x in output_lines if log_msg in x] self.assertTrue(len(assembly_log_lines) == 1) def test_assembly_log_time(self): """Check Total Assembly Time is logged""" self.assertAssembleLog("Total Assembly Time") if __name__ == "__main__": unittest.main(verbosity=2)
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Compiler Test.""" import os import unittest from qiskit import BasicAer from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.transpiler import PassManager from qiskit import execute from qiskit.circuit.library import U1Gate, U2Gate from qiskit.compiler import transpile, assemble from qiskit.test import QiskitTestCase from qiskit.providers.fake_provider import FakeRueschlikon, FakeTenerife from qiskit.qobj import QasmQobj class TestCompiler(QiskitTestCase): """Qiskit Compiler Tests.""" def setUp(self): super().setUp() self.seed_simulator = 42 self.backend = BasicAer.get_backend("qasm_simulator") def test_example_multiple_compile(self): """Test a toy example compiling multiple circuits. Pass if the results are correct. """ backend = BasicAer.get_backend("qasm_simulator") coupling_map = [[0, 1], [0, 2], [1, 2], [3, 2], [3, 4], [4, 2]] qr = QuantumRegister(5) cr = ClassicalRegister(5) bell = QuantumCircuit(qr, cr) ghz = QuantumCircuit(qr, cr) # Create a GHZ state ghz.h(qr[0]) for i in range(4): ghz.cx(qr[i], qr[i + 1]) # Insert a barrier before measurement ghz.barrier() # Measure all of the qubits in the standard basis for i in range(5): ghz.measure(qr[i], cr[i]) # Create a Bell state bell.h(qr[0]) bell.cx(qr[0], qr[1]) bell.barrier() bell.measure(qr[0], cr[0]) bell.measure(qr[1], cr[1]) shots = 2048 bell_backend = transpile(bell, backend=backend) ghz_backend = transpile(ghz, backend=backend, coupling_map=coupling_map) bell_qobj = assemble(bell_backend, shots=shots, seed_simulator=10) ghz_qobj = assemble(ghz_backend, shots=shots, seed_simulator=10) bell_result = backend.run(bell_qobj).result() ghz_result = backend.run(ghz_qobj).result() threshold = 0.05 * shots counts_bell = bell_result.get_counts() target_bell = {"00000": shots / 2, "00011": shots / 2} self.assertDictAlmostEqual(counts_bell, target_bell, threshold) counts_ghz = ghz_result.get_counts() target_ghz = {"00000": shots / 2, "11111": shots / 2} self.assertDictAlmostEqual(counts_ghz, target_ghz, threshold) def test_compile_coupling_map(self): """Test compile_coupling_map. If all correct should return data with the same stats. The circuit may be different. """ backend = BasicAer.get_backend("qasm_simulator") qr = QuantumRegister(3, "qr") cr = ClassicalRegister(3, "cr") qc = QuantumCircuit(qr, cr, name="qccccccc") qc.h(qr[0]) qc.cx(qr[0], qr[1]) qc.cx(qr[0], qr[2]) qc.measure(qr[0], cr[0]) qc.measure(qr[1], cr[1]) qc.measure(qr[2], cr[2]) shots = 2048 coupling_map = [[0, 1], [1, 2]] initial_layout = [0, 1, 2] qc_b = transpile( qc, backend=backend, coupling_map=coupling_map, initial_layout=initial_layout ) qobj = assemble(qc_b, shots=shots, seed_simulator=88) job = backend.run(qobj) result = job.result() qasm_to_check = qc.qasm() self.assertEqual(len(qasm_to_check), 173) counts = result.get_counts(qc) target = {"000": shots / 2, "111": shots / 2} threshold = 0.05 * shots self.assertDictAlmostEqual(counts, target, threshold) def test_example_swap_bits(self): """Test a toy example swapping a set bit around. Uses the mapper. Pass if results are correct. """ backend = BasicAer.get_backend("qasm_simulator") coupling_map = [ [0, 1], [0, 8], [1, 2], [1, 9], [2, 3], [2, 10], [3, 4], [3, 11], [4, 5], [4, 12], [5, 6], [5, 13], [6, 7], [6, 14], [7, 15], [8, 9], [9, 10], [10, 11], [11, 12], [12, 13], [13, 14], [14, 15], ] # ┌───┐ ░ ┌─┐ # q0_0: ┤ X ├─X───────────░─┤M├─────────────── # └───┘ │ ░ └╥┘ ┌─┐ # q0_1: ──────┼─────X──X──░──╫────┤M├───────── # │ │ │ ░ ║ └╥┘ ┌─┐ # q0_2: ──────X──X──┼──┼──░──╫─────╫────┤M├─── # │ │ │ ░ ║ ┌─┐ ║ └╥┘ # q1_0: ─────────┼──┼──┼──░──╫─┤M├─╫─────╫──── # │ │ │ ░ ║ └╥┘ ║ ┌─┐ ║ # q1_1: ─────────┼──┼──X──░──╫──╫──╫─┤M├─╫──── # │ │ ░ ║ ║ ║ └╥┘ ║ ┌─┐ # q1_2: ─────────X──X─────░──╫──╫──╫──╫──╫─┤M├ # ░ ║ ║ ║ ║ ║ └╥┘ # c0: 6/═════════════════════╩══╩══╩══╩══╩══╩═ # 0 3 1 4 2 5 n = 3 # make this at least 3 qr0 = QuantumRegister(n) qr1 = QuantumRegister(n) ans = ClassicalRegister(2 * n) qc = QuantumCircuit(qr0, qr1, ans) # Set the first bit of qr0 qc.x(qr0[0]) # Swap the set bit qc.swap(qr0[0], qr0[n - 1]) qc.swap(qr0[n - 1], qr1[n - 1]) qc.swap(qr1[n - 1], qr0[1]) qc.swap(qr0[1], qr1[1]) # Insert a barrier before measurement qc.barrier() # Measure all of the qubits in the standard basis for j in range(n): qc.measure(qr0[j], ans[j]) qc.measure(qr1[j], ans[j + n]) # First version: no mapping result = execute( qc, backend=backend, coupling_map=None, shots=1024, seed_simulator=14 ).result() self.assertEqual(result.get_counts(qc), {"010000": 1024}) # Second version: map to coupling graph result = execute( qc, backend=backend, coupling_map=coupling_map, shots=1024, seed_simulator=14 ).result() self.assertEqual(result.get_counts(qc), {"010000": 1024}) def test_parallel_compile(self): """Trigger parallel routines in compile.""" backend = FakeRueschlikon() qr = QuantumRegister(16) cr = ClassicalRegister(2) qc = QuantumCircuit(qr, cr) qc.h(qr[0]) for k in range(1, 15): qc.cx(qr[0], qr[k]) qc.measure(qr[5], cr[0]) qlist = [qc for k in range(10)] qobj = assemble(transpile(qlist, backend=backend)) self.assertEqual(len(qobj.experiments), 10) def test_no_conflict_backend_passmanager(self): """execute(qc, backend=..., passmanager=...) See: https://github.com/Qiskit/qiskit-terra/issues/5037 """ backend = BasicAer.get_backend("qasm_simulator") qc = QuantumCircuit(2) qc.append(U1Gate(0), [0]) qc.measure_all() job = execute(qc, backend=backend, pass_manager=PassManager()) result = job.result().get_counts() self.assertEqual(result, {"00": 1024}) def test_compile_single_qubit(self): """Compile a single-qubit circuit in a non-trivial layout""" qr = QuantumRegister(1, "qr") circuit = QuantumCircuit(qr) circuit.h(qr[0]) layout = {qr[0]: 12} cmap = [ [1, 0], [1, 2], [2, 3], [4, 3], [4, 10], [5, 4], [5, 6], [5, 9], [6, 8], [7, 8], [9, 8], [9, 10], [11, 3], [11, 10], [11, 12], [12, 2], [13, 1], [13, 12], ] circuit2 = transpile( circuit, backend=None, coupling_map=cmap, basis_gates=["u2"], initial_layout=layout ) qobj = assemble(circuit2) compiled_instruction = qobj.experiments[0].instructions[0] self.assertEqual(compiled_instruction.name, "u2") self.assertEqual(compiled_instruction.qubits, [12]) self.assertEqual(compiled_instruction.params, [0, 3.141592653589793]) def test_compile_pass_manager(self): """Test compile with and without an empty pass manager.""" qr = QuantumRegister(2) cr = ClassicalRegister(2) qc = QuantumCircuit(qr, cr) qc.append(U1Gate(3.14), [qr[0]]) qc.append(U2Gate(3.14, 1.57), [qr[0]]) qc.barrier(qr) qc.measure(qr, cr) backend = BasicAer.get_backend("qasm_simulator") qrtrue = assemble(transpile(qc, backend, seed_transpiler=8), seed_simulator=42) rtrue = backend.run(qrtrue).result() qrfalse = assemble(PassManager().run(qc), seed_simulator=42) rfalse = backend.run(qrfalse).result() self.assertEqual(rtrue.get_counts(), rfalse.get_counts()) def test_mapper_overoptimization(self): """Check mapper overoptimization. The mapper should not change the semantics of the input. An overoptimization introduced issue #81: https://github.com/Qiskit/qiskit-terra/issues/81 """ # ┌───┐ ┌─┐ # q0_0: ┤ X ├──■───────┤M├─────────── # ├───┤┌─┴─┐┌───┐└╥┘ ┌─┐ # q0_1: ┤ Y ├┤ X ├┤ S ├─╫───■──┤M├─── # ├───┤└───┘├───┤ ║ ┌─┴─┐└╥┘┌─┐ # q0_2: ┤ Z ├──■──┤ T ├─╫─┤ X ├─╫─┤M├ # └───┘┌─┴─┐├───┤ ║ └┬─┬┘ ║ └╥┘ # q0_3: ─────┤ X ├┤ H ├─╫──┤M├──╫──╫─ # └───┘└───┘ ║ └╥┘ ║ ║ # c0: 4/════════════════╩═══╩═══╩══╩═ # 0 3 1 2 qr = QuantumRegister(4) cr = ClassicalRegister(4) circ = QuantumCircuit(qr, cr) circ.x(qr[0]) circ.y(qr[1]) circ.z(qr[2]) circ.cx(qr[0], qr[1]) circ.cx(qr[2], qr[3]) circ.s(qr[1]) circ.t(qr[2]) circ.h(qr[3]) circ.cx(qr[1], qr[2]) circ.measure(qr[0], cr[0]) circ.measure(qr[1], cr[1]) circ.measure(qr[2], cr[2]) circ.measure(qr[3], cr[3]) coupling_map = [[0, 2], [1, 2], [2, 3]] shots = 1000 result1 = execute( circ, backend=self.backend, coupling_map=coupling_map, seed_simulator=self.seed_simulator, seed_transpiler=8, shots=shots, ) count1 = result1.result().get_counts() result2 = execute( circ, backend=self.backend, coupling_map=None, seed_simulator=self.seed_simulator, seed_transpiler=8, shots=shots, ) count2 = result2.result().get_counts() self.assertDictAlmostEqual(count1, count2, shots * 0.02) def test_grovers_circuit(self): """Testing a circuit originated in the Grover algorithm""" shots = 1000 coupling_map = None # 6-qubit grovers # # ┌───┐┌───┐ ┌───┐┌───┐ ┌───┐ ┌───┐┌───┐ ░ ┌─┐ # q0_0: ┤ H ├┤ X ├──■──┤ X ├┤ X ├──■──┤ X ├──■──┤ X ├┤ H ├──────░─┤M├─── # ├───┤└───┘ │ └───┘└───┘ │ ├───┤ │ ├───┤├───┤ ░ └╥┘┌─┐ # q0_1: ┤ H ├──■────┼─────────■────┼──┤ X ├──■──┤ X ├┤ H ├──────░──╫─┤M├ # ├───┤ │ ┌─┴─┐ │ ┌─┴─┐└───┘ │ └───┘└───┘ ░ ║ └╥┘ # q0_2: ┤ X ├──┼──┤ X ├──■────┼──┤ X ├───────┼──────────────────░──╫──╫─ # ├───┤┌─┴─┐└───┘ │ ┌─┴─┐└───┘ │ ░ ║ ║ # q0_3: ┤ X ├┤ X ├───────■──┤ X ├────────────┼──────────────────░──╫──╫─ # └───┘└───┘ ┌─┴─┐├───┤┌───┐ ┌─┴─┐┌───┐┌───┐┌───┐ ░ ║ ║ # q0_4: ───────────────┤ X ├┤ X ├┤ H ├─────┤ X ├┤ H ├┤ X ├┤ H ├─░──╫──╫─ # └───┘└───┘└───┘ └───┘└───┘└───┘└───┘ ░ ║ ║ # q0_5: ────────────────────────────────────────────────────────░──╫──╫─ # ░ ║ ║ # c0: 2/═══════════════════════════════════════════════════════════╩══╩═ # 0 1 qr = QuantumRegister(6) cr = ClassicalRegister(2) circuit = QuantumCircuit(qr, cr, name="grovers") circuit.h(qr[0]) circuit.h(qr[1]) circuit.x(qr[2]) circuit.x(qr[3]) circuit.x(qr[0]) circuit.cx(qr[0], qr[2]) circuit.x(qr[0]) circuit.cx(qr[1], qr[3]) circuit.ccx(qr[2], qr[3], qr[4]) circuit.cx(qr[1], qr[3]) circuit.x(qr[0]) circuit.cx(qr[0], qr[2]) circuit.x(qr[0]) circuit.x(qr[1]) circuit.x(qr[4]) circuit.h(qr[4]) circuit.ccx(qr[0], qr[1], qr[4]) circuit.h(qr[4]) circuit.x(qr[0]) circuit.x(qr[1]) circuit.x(qr[4]) circuit.h(qr[0]) circuit.h(qr[1]) circuit.h(qr[4]) circuit.barrier(qr) circuit.measure(qr[0], cr[0]) circuit.measure(qr[1], cr[1]) result = execute( circuit, backend=self.backend, coupling_map=coupling_map, seed_simulator=self.seed_simulator, shots=shots, ) counts = result.result().get_counts() expected_probs = {"00": 0.64, "01": 0.117, "10": 0.113, "11": 0.13} target = {key: shots * val for key, val in expected_probs.items()} threshold = 0.04 * shots self.assertDictAlmostEqual(counts, target, threshold) def test_math_domain_error(self): """Check for floating point errors. The math library operates over floats and introduces floating point errors that should be avoided. See: https://github.com/Qiskit/qiskit-terra/issues/111 """ # ┌───┐┌───┐ ┌─┐ # q0_0: ┤ Y ├┤ X ├─────┤M├───────────────────── # └───┘└─┬─┘ └╥┘ ┌─┐ # q0_1: ───────■────────╫─────────────■──┤M├─── # ┌───┐┌───┐┌───┐ ║ ┌───┐┌───┐┌─┴─┐└╥┘┌─┐ # q0_2: ┤ Z ├┤ H ├┤ Y ├─╫─┤ T ├┤ Z ├┤ X ├─╫─┤M├ # └┬─┬┘└───┘└───┘ ║ └───┘└───┘└───┘ ║ └╥┘ # q0_3: ─┤M├────────────╫─────────────────╫──╫─ # └╥┘ ║ ║ ║ # c0: 4/══╩═════════════╩═════════════════╩══╩═ # 3 0 1 2 qr = QuantumRegister(4) cr = ClassicalRegister(4) circ = QuantumCircuit(qr, cr) circ.y(qr[0]) circ.z(qr[2]) circ.h(qr[2]) circ.cx(qr[1], qr[0]) circ.y(qr[2]) circ.t(qr[2]) circ.z(qr[2]) circ.cx(qr[1], qr[2]) circ.measure(qr[0], cr[0]) circ.measure(qr[1], cr[1]) circ.measure(qr[2], cr[2]) circ.measure(qr[3], cr[3]) coupling_map = [[0, 2], [1, 2], [2, 3]] shots = 2000 job = execute( circ, backend=self.backend, coupling_map=coupling_map, seed_simulator=self.seed_simulator, shots=shots, ) counts = job.result().get_counts() target = {"0001": shots / 2, "0101": shots / 2} threshold = 0.04 * shots self.assertDictAlmostEqual(counts, target, threshold) def test_random_parameter_circuit(self): """Run a circuit with randomly generated parameters.""" qasm_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "qasm") circ = QuantumCircuit.from_qasm_file(os.path.join(qasm_dir, "random_n5_d5.qasm")) coupling_map = [[0, 1], [1, 2], [2, 3], [3, 4]] shots = 1024 qobj = execute( circ, backend=self.backend, coupling_map=coupling_map, shots=shots, seed_simulator=self.seed_simulator, ) counts = qobj.result().get_counts() expected_probs = { "00000": 0.079239867254200971, "00001": 0.032859032998526903, "00010": 0.10752610993531816, "00011": 0.018818532050952699, "00100": 0.054830807251011054, "00101": 0.0034141983951965164, "00110": 0.041649309748902276, "00111": 0.039967731207338125, "01000": 0.10516937819949743, "01001": 0.026635620063700002, "01010": 0.0053475143548793866, "01011": 0.01940513314416064, "01100": 0.0044028405481225047, "01101": 0.057524760052126644, "01110": 0.010795354134597078, "01111": 0.026491296821535528, "10000": 0.094827455395274859, "10001": 0.0008373965072688836, "10010": 0.029082297894094441, "10011": 0.012386622870598416, "10100": 0.018739140061148799, "10101": 0.01367656456536896, "10110": 0.039184170706009248, "10111": 0.062339335178438288, "11000": 0.00293674365989009, "11001": 0.012848433960739968, "11010": 0.018472497159499782, "11011": 0.0088903691234912003, "11100": 0.031305389080034329, "11101": 0.0004788556283690458, "11110": 0.002232419390471667, "11111": 0.017684822659235985, } target = {key: shots * val for key, val in expected_probs.items()} threshold = 0.04 * shots self.assertDictAlmostEqual(counts, target, threshold) def test_yzy_zyz_cases(self): """yzy_to_zyz works in previously failed cases. See: https://github.com/Qiskit/qiskit-terra/issues/607 """ backend = FakeTenerife() qr = QuantumRegister(2) circ1 = QuantumCircuit(qr) circ1.cx(qr[0], qr[1]) circ1.rz(0.7, qr[1]) circ1.rx(1.570796, qr[1]) qobj1 = assemble(transpile(circ1, backend)) self.assertIsInstance(qobj1, QasmQobj) circ2 = QuantumCircuit(qr) circ2.y(qr[0]) circ2.h(qr[0]) circ2.s(qr[0]) circ2.h(qr[0]) qobj2 = assemble(transpile(circ2, backend)) self.assertIsInstance(qobj2, QasmQobj) if __name__ == "__main__": unittest.main(verbosity=2)
https://github.com/swe-train/qiskit__qiskit
swe-train
# 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. """Assembler Test.""" import unittest import numpy as np from numpy.testing import assert_allclose from qiskit import pulse from qiskit.compiler.assembler import assemble from qiskit.assembler.disassemble import disassemble from qiskit.assembler.run_config import RunConfig from qiskit.circuit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.circuit import Gate, Instruction, Parameter from qiskit.circuit.library import RXGate from qiskit.pulse.transforms import target_qobj_transform from qiskit.test import QiskitTestCase from qiskit.providers.fake_provider import FakeOpenPulse2Q import qiskit.quantum_info as qi def _parametric_to_waveforms(schedule): instructions = list(schedule.instructions) for i, time_instruction_tuple in enumerate(schedule.instructions): time, instruction = time_instruction_tuple if not isinstance(instruction.pulse, pulse.library.Waveform): new_inst = pulse.Play(instruction.pulse.get_waveform(), instruction.channel) instructions[i] = (time, new_inst) return tuple(instructions) class TestQuantumCircuitDisassembler(QiskitTestCase): """Tests for disassembling circuits to qobj.""" def test_disassemble_single_circuit(self): """Test disassembling a single circuit.""" qr = QuantumRegister(2, name="q") cr = ClassicalRegister(2, name="c") circ = QuantumCircuit(qr, cr, name="circ") circ.h(qr[0]) circ.cx(qr[0], qr[1]) circ.measure(qr, cr) qubit_lo_freq = [5e9, 5e9] meas_lo_freq = [6.7e9, 6.7e9] qobj = assemble( circ, shots=2000, memory=True, qubit_lo_freq=qubit_lo_freq, meas_lo_freq=meas_lo_freq, ) circuits, run_config_out, headers = disassemble(qobj) run_config_out = RunConfig(**run_config_out) self.assertEqual(run_config_out.n_qubits, 2) self.assertEqual(run_config_out.memory_slots, 2) self.assertEqual(run_config_out.shots, 2000) self.assertEqual(run_config_out.memory, True) self.assertEqual(run_config_out.qubit_lo_freq, qubit_lo_freq) self.assertEqual(run_config_out.meas_lo_freq, meas_lo_freq) self.assertEqual(len(circuits), 1) self.assertEqual(circuits[0], circ) self.assertEqual({}, headers) def test_disassemble_multiple_circuits(self): """Test disassembling multiple circuits, all should have the same config.""" qr0 = QuantumRegister(2, name="q0") qc0 = ClassicalRegister(2, name="c0") circ0 = QuantumCircuit(qr0, qc0, name="circ0") circ0.h(qr0[0]) circ0.cx(qr0[0], qr0[1]) circ0.measure(qr0, qc0) qr1 = QuantumRegister(3, name="q1") qc1 = ClassicalRegister(3, name="c1") circ1 = QuantumCircuit(qr1, qc1, name="circ0") circ1.h(qr1[0]) circ1.cx(qr1[0], qr1[1]) circ1.cx(qr1[0], qr1[2]) circ1.measure(qr1, qc1) qobj = assemble([circ0, circ1], shots=100, memory=False, seed=6) circuits, run_config_out, headers = disassemble(qobj) run_config_out = RunConfig(**run_config_out) self.assertEqual(run_config_out.n_qubits, 3) self.assertEqual(run_config_out.memory_slots, 3) self.assertEqual(run_config_out.shots, 100) self.assertEqual(run_config_out.memory, False) self.assertEqual(run_config_out.seed, 6) self.assertEqual(len(circuits), 2) for circuit in circuits: self.assertIn(circuit, [circ0, circ1]) self.assertEqual({}, headers) def test_disassemble_no_run_config(self): """Test disassembling with no run_config, relying on default.""" qr = QuantumRegister(2, name="q") qc = ClassicalRegister(2, name="c") circ = QuantumCircuit(qr, qc, name="circ") circ.h(qr[0]) circ.cx(qr[0], qr[1]) circ.measure(qr, qc) qobj = assemble(circ) circuits, run_config_out, headers = disassemble(qobj) run_config_out = RunConfig(**run_config_out) self.assertEqual(run_config_out.n_qubits, 2) self.assertEqual(run_config_out.memory_slots, 2) self.assertEqual(len(circuits), 1) self.assertEqual(circuits[0], circ) self.assertEqual({}, headers) def test_disassemble_initialize(self): """Test disassembling a circuit with an initialize.""" q = QuantumRegister(2, name="q") circ = QuantumCircuit(q, name="circ") circ.initialize([1 / np.sqrt(2), 0, 0, 1 / np.sqrt(2)], q[:]) qobj = assemble(circ) circuits, run_config_out, header = disassemble(qobj) run_config_out = RunConfig(**run_config_out) self.assertEqual(run_config_out.n_qubits, 2) self.assertEqual(run_config_out.memory_slots, 0) self.assertEqual(len(circuits), 1) self.assertEqual(circuits[0], circ) self.assertEqual({}, header) def test_disassemble_isometry(self): """Test disassembling a circuit with an isometry.""" q = QuantumRegister(2, name="q") circ = QuantumCircuit(q, name="circ") circ.iso(qi.random_unitary(4).data, circ.qubits, []) qobj = assemble(circ) circuits, run_config_out, header = disassemble(qobj) run_config_out = RunConfig(**run_config_out) self.assertEqual(run_config_out.n_qubits, 2) self.assertEqual(run_config_out.memory_slots, 0) self.assertEqual(len(circuits), 1) # params array assert_allclose(circuits[0]._data[0].operation.params[0], circ._data[0].operation.params[0]) # all other data self.assertEqual( circuits[0]._data[0].operation.params[1:], circ._data[0].operation.params[1:] ) self.assertEqual(circuits[0]._data[0].qubits, circ._data[0].qubits) self.assertEqual(circuits[0]._data[0].clbits, circ._data[0].clbits) self.assertEqual(circuits[0]._data[1:], circ._data[1:]) self.assertEqual({}, header) def test_opaque_instruction(self): """Test the disassembler handles opaque instructions correctly.""" opaque_inst = Instruction(name="my_inst", num_qubits=4, num_clbits=2, params=[0.5, 0.4]) q = QuantumRegister(6, name="q") c = ClassicalRegister(4, name="c") circ = QuantumCircuit(q, c, name="circ") circ.append(opaque_inst, [q[0], q[2], q[5], q[3]], [c[3], c[0]]) qobj = assemble(circ) circuits, run_config_out, header = disassemble(qobj) run_config_out = RunConfig(**run_config_out) self.assertEqual(run_config_out.n_qubits, 6) self.assertEqual(run_config_out.memory_slots, 4) self.assertEqual(len(circuits), 1) self.assertEqual(circuits[0], circ) self.assertEqual({}, header) def test_circuit_with_conditionals(self): """Verify disassemble sets conditionals correctly.""" qr = QuantumRegister(2) cr1 = ClassicalRegister(1) cr2 = ClassicalRegister(2) qc = QuantumCircuit(qr, cr1, cr2) qc.measure(qr[0], cr1) # Measure not required for a later conditional qc.measure(qr[1], cr2[1]) # Measure required for a later conditional qc.h(qr[1]).c_if(cr2, 3) qobj = assemble(qc) circuits, run_config_out, header = disassemble(qobj) run_config_out = RunConfig(**run_config_out) self.assertEqual(run_config_out.n_qubits, 2) self.assertEqual(run_config_out.memory_slots, 3) self.assertEqual(len(circuits), 1) self.assertEqual(circuits[0], qc) self.assertEqual({}, header) def test_circuit_with_simple_conditional(self): """Verify disassemble handles a simple conditional on the only bits.""" qr = QuantumRegister(1) cr = ClassicalRegister(1) qc = QuantumCircuit(qr, cr) qc.h(qr[0]).c_if(cr, 1) qobj = assemble(qc) circuits, run_config_out, header = disassemble(qobj) run_config_out = RunConfig(**run_config_out) self.assertEqual(run_config_out.n_qubits, 1) self.assertEqual(run_config_out.memory_slots, 1) self.assertEqual(len(circuits), 1) self.assertEqual(circuits[0], qc) self.assertEqual({}, header) def test_circuit_with_single_bit_conditions(self): """Verify disassemble handles a simple conditional on a single bit of a register.""" # This circuit would fail to perfectly round-trip if 'cr' below had only one bit in it. # This is because the format of QasmQobj is insufficient to disambiguate single-bit # conditions from conditions on registers with only one bit. Since single-bit conditions are # mostly a hack for the QasmQobj format at all, `disassemble` always prefers to return the # register if it can. It would also fail if registers overlap. qr = QuantumRegister(1) cr = ClassicalRegister(2) qc = QuantumCircuit(qr, cr) qc.h(qr[0]).c_if(cr[0], 1) qobj = assemble(qc) circuits, run_config_out, header = disassemble(qobj) run_config_out = RunConfig(**run_config_out) self.assertEqual(run_config_out.n_qubits, len(qr)) self.assertEqual(run_config_out.memory_slots, len(cr)) self.assertEqual(len(circuits), 1) self.assertEqual(circuits[0], qc) self.assertEqual({}, header) def test_circuit_with_mcx(self): """Verify disassemble handles mcx gate - #6271.""" qr = QuantumRegister(5) cr = ClassicalRegister(5) qc = QuantumCircuit(qr, cr) qc.mcx([0, 1, 2], 4) qobj = assemble(qc) circuits, run_config_out, header = disassemble(qobj) run_config_out = RunConfig(**run_config_out) self.assertEqual(run_config_out.n_qubits, 5) self.assertEqual(run_config_out.memory_slots, 5) self.assertEqual(len(circuits), 1) self.assertEqual(circuits[0], qc) self.assertEqual({}, header) def test_multiple_conditionals_multiple_registers(self): """Verify disassemble handles multiple conditionals and registers.""" qr = QuantumRegister(3) cr1 = ClassicalRegister(3) cr2 = ClassicalRegister(5) cr3 = ClassicalRegister(6) cr4 = ClassicalRegister(1) qc = QuantumCircuit(qr, cr1, cr2, cr3, cr4) qc.x(qr[1]) qc.h(qr) qc.cx(qr[1], qr[0]).c_if(cr3, 14) qc.ccx(qr[0], qr[2], qr[1]).c_if(cr4, 1) qc.h(qr).c_if(cr1, 3) qobj = assemble(qc) circuits, run_config_out, header = disassemble(qobj) run_config_out = RunConfig(**run_config_out) self.assertEqual(run_config_out.n_qubits, 3) self.assertEqual(run_config_out.memory_slots, 15) self.assertEqual(len(circuits), 1) self.assertEqual(circuits[0], qc) self.assertEqual({}, header) def test_circuit_with_bit_conditional_1(self): """Verify disassemble handles conditional on a single bit.""" qr = QuantumRegister(2) cr = ClassicalRegister(2) qc = QuantumCircuit(qr, cr) qc.h(qr[0]).c_if(cr[1], True) qobj = assemble(qc) circuits, run_config_out, header = disassemble(qobj) run_config_out = RunConfig(**run_config_out) self.assertEqual(run_config_out.n_qubits, 2) self.assertEqual(run_config_out.memory_slots, 2) self.assertEqual(len(circuits), 1) self.assertEqual(circuits[0], qc) self.assertEqual({}, header) def test_circuit_with_bit_conditional_2(self): """Verify disassemble handles multiple single bit conditionals.""" qr = QuantumRegister(2) cr = ClassicalRegister(2) cr1 = ClassicalRegister(2) qc = QuantumCircuit(qr, cr, cr1) qc.h(qr[0]).c_if(cr1[1], False) qc.h(qr[1]).c_if(cr[0], True) qc.cx(qr[0], qr[1]).c_if(cr1[0], False) qobj = assemble(qc) circuits, run_config_out, header = disassemble(qobj) run_config_out = RunConfig(**run_config_out) self.assertEqual(run_config_out.n_qubits, 2) self.assertEqual(run_config_out.memory_slots, 4) self.assertEqual(len(circuits), 1) self.assertEqual(circuits[0], qc) self.assertEqual({}, header) def assertCircuitCalibrationsEqual(self, in_circuits, out_circuits): """Verify circuit calibrations are equivalent pre-assembly and post-disassembly""" self.assertEqual(len(in_circuits), len(out_circuits)) for in_qc, out_qc in zip(in_circuits, out_circuits): in_cals = in_qc.calibrations out_cals = out_qc.calibrations self.assertEqual(in_cals.keys(), out_cals.keys()) for gate_name in in_cals: self.assertEqual(in_cals[gate_name].keys(), out_cals[gate_name].keys()) for gate_params, in_sched in in_cals[gate_name].items(): out_sched = out_cals[gate_name][gate_params] self.assertEqual(*map(_parametric_to_waveforms, (in_sched, out_sched))) def test_single_circuit_calibrations(self): """Test that disassembler parses single circuit QOBJ calibrations (from QOBJ-level).""" theta = Parameter("theta") qc = QuantumCircuit(2) qc.h(0) qc.rx(np.pi, 0) qc.rx(theta, 1) qc = qc.assign_parameters({theta: np.pi}) with pulse.build() as h_sched: pulse.play(pulse.library.Drag(1, 0.15, 4, 2), pulse.DriveChannel(0)) with pulse.build() as x180: pulse.play(pulse.library.Gaussian(1, 0.2, 5), pulse.DriveChannel(0)) qc.add_calibration("h", [0], h_sched) qc.add_calibration(RXGate(np.pi), [0], x180) qobj = assemble(qc, FakeOpenPulse2Q()) output_circuits, _, _ = disassemble(qobj) self.assertCircuitCalibrationsEqual([qc], output_circuits) def test_parametric_pulse_circuit_calibrations(self): """Test that disassembler parses parametric pulses back to pulse gates.""" with pulse.build() as h_sched: pulse.play(pulse.library.Drag(50, 0.15, 4, 2), pulse.DriveChannel(0)) qc = QuantumCircuit(2) qc.h(0) qc.add_calibration("h", [0], h_sched) backend = FakeOpenPulse2Q() backend.configuration().parametric_pulses = ["drag"] qobj = assemble(qc, backend) output_circuits, _, _ = disassemble(qobj) out_qc = output_circuits[0] self.assertCircuitCalibrationsEqual([qc], output_circuits) self.assertTrue( all( qc_sched.instructions == out_qc_sched.instructions for (_, qc_gate), (_, out_qc_gate) in zip( qc.calibrations.items(), out_qc.calibrations.items() ) for qc_sched, out_qc_sched in zip(qc_gate.values(), out_qc_gate.values()) ), ) def test_multi_circuit_uncommon_calibrations(self): """Test that disassembler parses uncommon calibrations (stored at QOBJ experiment-level).""" with pulse.build() as sched: pulse.play(pulse.library.Drag(50, 0.15, 4, 2), pulse.DriveChannel(0)) qc_0 = QuantumCircuit(2) qc_0.h(0) qc_0.append(RXGate(np.pi), [1]) qc_0.add_calibration("h", [0], sched) qc_0.add_calibration(RXGate(np.pi), [1], sched) qc_1 = QuantumCircuit(2) qc_1.h(0) circuits = [qc_0, qc_1] qobj = assemble(circuits, FakeOpenPulse2Q()) output_circuits, _, _ = disassemble(qobj) self.assertCircuitCalibrationsEqual(circuits, output_circuits) def test_multi_circuit_common_calibrations(self): """Test that disassembler parses common calibrations (stored at QOBJ-level).""" with pulse.build() as sched: pulse.play(pulse.library.Drag(1, 0.15, 4, 2), pulse.DriveChannel(0)) qc_0 = QuantumCircuit(2) qc_0.h(0) qc_0.append(RXGate(np.pi), [1]) qc_0.add_calibration("h", [0], sched) qc_0.add_calibration(RXGate(np.pi), [1], sched) qc_1 = QuantumCircuit(2) qc_1.h(0) qc_1.add_calibration(RXGate(np.pi), [1], sched) circuits = [qc_0, qc_1] qobj = assemble(circuits, FakeOpenPulse2Q()) output_circuits, _, _ = disassemble(qobj) self.assertCircuitCalibrationsEqual(circuits, output_circuits) def test_single_circuit_delay_calibrations(self): """Test that disassembler parses delay instruction back to delay gate.""" qc = QuantumCircuit(2) qc.append(Gate("test", 1, []), [0]) test_sched = pulse.Delay(64, pulse.DriveChannel(0)) + pulse.Delay( 160, pulse.DriveChannel(0) ) qc.add_calibration("test", [0], test_sched) qobj = assemble(qc, FakeOpenPulse2Q()) output_circuits, _, _ = disassemble(qobj) self.assertEqual(len(qc.calibrations), len(output_circuits[0].calibrations)) self.assertEqual(qc.calibrations.keys(), output_circuits[0].calibrations.keys()) self.assertTrue( all( qc_cal.keys() == out_qc_cal.keys() for qc_cal, out_qc_cal in zip( qc.calibrations.values(), output_circuits[0].calibrations.values() ) ) ) self.assertEqual( qc.calibrations["test"][((0,), ())], output_circuits[0].calibrations["test"][((0,), ())] ) class TestPulseScheduleDisassembler(QiskitTestCase): """Tests for disassembling pulse schedules to qobj.""" def setUp(self): super().setUp() self.backend = FakeOpenPulse2Q() self.backend_config = self.backend.configuration() self.backend_config.parametric_pulses = ["constant", "gaussian", "gaussian_square", "drag"] def test_disassemble_single_schedule(self): """Test disassembling a single schedule.""" d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) with pulse.build(self.backend) as sched: with pulse.align_right(): pulse.play(pulse.library.Constant(10, 1.0), d0) pulse.set_phase(1.0, d0) pulse.shift_phase(3.11, d0) pulse.set_frequency(1e9, d0) pulse.shift_frequency(1e7, d0) pulse.delay(20, d0) pulse.delay(10, d1) pulse.play(pulse.library.Constant(8, 0.1), d1) pulse.measure_all() qobj = assemble(sched, backend=self.backend, shots=2000) scheds, run_config_out, _ = disassemble(qobj) run_config_out = RunConfig(**run_config_out) self.assertEqual(run_config_out.memory_slots, 2) self.assertEqual(run_config_out.shots, 2000) self.assertEqual(run_config_out.memory, False) self.assertEqual(run_config_out.meas_level, 2) self.assertEqual(run_config_out.meas_lo_freq, self.backend.defaults().meas_freq_est) self.assertEqual(run_config_out.qubit_lo_freq, self.backend.defaults().qubit_freq_est) self.assertEqual(run_config_out.rep_time, 99) self.assertEqual(len(scheds), 1) self.assertEqual(scheds[0], target_qobj_transform(sched)) def test_disassemble_multiple_schedules(self): """Test disassembling multiple schedules, all should have the same config.""" d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) with pulse.build(self.backend) as sched0: with pulse.align_right(): pulse.play(pulse.library.Constant(10, 1.0), d0) pulse.set_phase(1.0, d0) pulse.shift_phase(3.11, d0) pulse.set_frequency(1e9, d0) pulse.shift_frequency(1e7, d0) pulse.delay(20, d0) pulse.delay(10, d1) pulse.play(pulse.library.Constant(8, 0.1), d1) pulse.measure_all() with pulse.build(self.backend) as sched1: with pulse.align_right(): pulse.play(pulse.library.Constant(8, 0.1), d0) pulse.play(pulse.library.Waveform([0.0, 1.0]), d1) pulse.set_phase(1.1, d0) pulse.shift_phase(3.5, d0) pulse.set_frequency(2e9, d0) pulse.shift_frequency(3e7, d1) pulse.delay(20, d1) pulse.delay(10, d0) pulse.play(pulse.library.Constant(8, 0.4), d1) pulse.measure_all() qobj = assemble([sched0, sched1], backend=self.backend, shots=2000) scheds, run_config_out, _ = disassemble(qobj) run_config_out = RunConfig(**run_config_out) self.assertEqual(run_config_out.memory_slots, 2) self.assertEqual(run_config_out.shots, 2000) self.assertEqual(run_config_out.memory, False) self.assertEqual(len(scheds), 2) self.assertEqual(scheds[0], target_qobj_transform(sched0)) self.assertEqual(scheds[1], target_qobj_transform(sched1)) def test_disassemble_parametric_pulses(self): """Test disassembling multiple schedules all should have the same config.""" d0 = pulse.DriveChannel(0) with pulse.build(self.backend) as sched: with pulse.align_right(): pulse.play(pulse.library.Constant(10, 1.0), d0) pulse.play(pulse.library.Gaussian(10, 1.0, 2.0), d0) pulse.play(pulse.library.GaussianSquare(10, 1.0, 2.0, 3), d0) pulse.play(pulse.library.Drag(10, 1.0, 2.0, 0.1), d0) qobj = assemble(sched, backend=self.backend, shots=2000) scheds, _, _ = disassemble(qobj) self.assertEqual(scheds[0], target_qobj_transform(sched)) def test_disassemble_schedule_los(self): """Test disassembling schedule los.""" d0 = pulse.DriveChannel(0) m0 = pulse.MeasureChannel(0) d1 = pulse.DriveChannel(1) m1 = pulse.MeasureChannel(1) sched0 = pulse.Schedule() sched1 = pulse.Schedule() schedule_los = [ {d0: 4.5e9, d1: 5e9, m0: 6e9, m1: 7e9}, {d0: 5e9, d1: 4.5e9, m0: 7e9, m1: 6e9}, ] qobj = assemble([sched0, sched1], backend=self.backend, schedule_los=schedule_los) _, run_config_out, _ = disassemble(qobj) run_config_out = RunConfig(**run_config_out) self.assertEqual(run_config_out.schedule_los, schedule_los) if __name__ == "__main__": unittest.main(verbosity=2)
https://github.com/swe-train/qiskit__qiskit
swe-train
# 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=missing-function-docstring """Tests basic functionality of the sequence function""" import unittest from qiskit import QuantumCircuit, pulse from qiskit.compiler import sequence, transpile, schedule from qiskit.pulse.transforms import pad from qiskit.providers.fake_provider import FakeParis from qiskit.test import QiskitTestCase class TestSequence(QiskitTestCase): """Test sequence function.""" def setUp(self): super().setUp() self.backend = FakeParis() def test_sequence_empty(self): self.assertEqual(sequence([], self.backend), []) def test_transpile_and_sequence_agree_with_schedule(self): qc = QuantumCircuit(2, name="bell") qc.h(0) qc.cx(0, 1) qc.measure_all() sc = transpile(qc, self.backend, scheduling_method="alap") actual = sequence(sc, self.backend) expected = schedule(transpile(qc, self.backend), self.backend) self.assertEqual(actual, pad(expected)) def test_transpile_and_sequence_agree_with_schedule_for_circuit_with_delay(self): qc = QuantumCircuit(1, 1, name="t2") qc.h(0) qc.delay(500, 0, unit="ns") qc.h(0) qc.measure(0, 0) sc = transpile(qc, self.backend, scheduling_method="alap") actual = sequence(sc, self.backend) expected = schedule(transpile(qc, self.backend), self.backend) self.assertEqual( actual.exclude(instruction_types=[pulse.Delay]), expected.exclude(instruction_types=[pulse.Delay]), ) @unittest.skip("not yet determined if delays on ancilla should be removed or not") def test_transpile_and_sequence_agree_with_schedule_for_circuits_without_measures(self): qc = QuantumCircuit(2, name="bell_without_measurement") qc.h(0) qc.cx(0, 1) sc = transpile(qc, self.backend, scheduling_method="alap") actual = sequence(sc, self.backend) expected = schedule(transpile(qc, self.backend), self.backend) self.assertEqual(actual, pad(expected))
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests basic functionality of the transpile function""" import copy import io import math import os import sys import unittest from logging import StreamHandler, getLogger from test import combine # pylint: disable=wrong-import-order from unittest.mock import patch import numpy as np import rustworkx as rx from ddt import data, ddt, unpack from qiskit import BasicAer, ClassicalRegister, QuantumCircuit, QuantumRegister, pulse, qasm3, qpy from qiskit.circuit import ( Clbit, ControlFlowOp, ForLoopOp, Gate, IfElseOp, Parameter, Qubit, Reset, SwitchCaseOp, WhileLoopOp, ) from qiskit.circuit.classical import expr from qiskit.circuit.delay import Delay from qiskit.circuit.library import ( CXGate, CZGate, HGate, RXGate, RYGate, RZGate, SXGate, U1Gate, U2Gate, UGate, XGate, ) from qiskit.circuit.measure import Measure from qiskit.compiler import transpile from qiskit.converters import circuit_to_dag from qiskit.dagcircuit import DAGOpNode, DAGOutNode from qiskit.exceptions import QiskitError from qiskit.providers.backend import BackendV2 from qiskit.providers.fake_provider import ( FakeBoeblingen, FakeMelbourne, FakeMumbaiV2, FakeNairobiV2, FakeRueschlikon, FakeSherbrooke, FakeVigo, ) from qiskit.providers.options import Options from qiskit.pulse import InstructionScheduleMap from qiskit.quantum_info import Operator, random_unitary from qiskit.test import QiskitTestCase, slow_test from qiskit.tools import parallel from qiskit.transpiler import CouplingMap, Layout, PassManager, TransformationPass from qiskit.transpiler.exceptions import TranspilerError from qiskit.transpiler.passes import BarrierBeforeFinalMeasurements, GateDirection, VF2PostLayout from qiskit.transpiler.passmanager_config import PassManagerConfig from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager, level_0_pass_manager from qiskit.transpiler.target import InstructionProperties, Target class CustomCX(Gate): """Custom CX gate representation.""" def __init__(self): super().__init__("custom_cx", 2, []) def _define(self): self._definition = QuantumCircuit(2) self._definition.cx(0, 1) def connected_qubits(physical: int, coupling_map: CouplingMap) -> set: """Get the physical qubits that have a connection to this one in the coupling map.""" for component in coupling_map.connected_components(): if physical in (qubits := set(component.graph.nodes())): return qubits raise ValueError(f"physical qubit {physical} is not in the coupling map") @ddt class TestTranspile(QiskitTestCase): """Test transpile function.""" def test_empty_transpilation(self): """Test that transpiling an empty list is a no-op. Regression test of gh-7287.""" self.assertEqual(transpile([]), []) def test_pass_manager_none(self): """Test passing the default (None) pass manager to the transpiler. It should perform the default qiskit flow: unroll, swap_mapper, cx_direction, cx_cancellation, optimize_1q_gates and should be equivalent to using tools.compile """ qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.h(qr[0]) circuit.h(qr[0]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[1], qr[0]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[1], qr[0]) coupling_map = [[1, 0]] basis_gates = ["u1", "u2", "u3", "cx", "id"] backend = BasicAer.get_backend("qasm_simulator") circuit2 = transpile( circuit, backend=backend, coupling_map=coupling_map, basis_gates=basis_gates, ) circuit3 = transpile( circuit, backend=backend, coupling_map=coupling_map, basis_gates=basis_gates ) self.assertEqual(circuit2, circuit3) def test_transpile_basis_gates_no_backend_no_coupling_map(self): """Verify transpile() works with no coupling_map or backend.""" qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.h(qr[0]) circuit.h(qr[0]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) basis_gates = ["u1", "u2", "u3", "cx", "id"] circuit2 = transpile(circuit, basis_gates=basis_gates, optimization_level=0) resources_after = circuit2.count_ops() self.assertEqual({"u2": 2, "cx": 4}, resources_after) def test_transpile_non_adjacent_layout(self): """Transpile pipeline can handle manual layout on non-adjacent qubits. circuit: .. parsed-literal:: ┌───┐ qr_0: ┤ H ├──■──────────── -> 1 └───┘┌─┴─┐ qr_1: ─────┤ X ├──■─────── -> 2 └───┘┌─┴─┐ qr_2: ──────────┤ X ├──■── -> 3 └───┘┌─┴─┐ qr_3: ───────────────┤ X ├ -> 5 └───┘ device: 0 - 1 - 2 - 3 - 4 - 5 - 6 | | | | | | 13 - 12 - 11 - 10 - 9 - 8 - 7 """ qr = QuantumRegister(4, "qr") circuit = QuantumCircuit(qr) circuit.h(qr[0]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[1], qr[2]) circuit.cx(qr[2], qr[3]) coupling_map = FakeMelbourne().configuration().coupling_map basis_gates = FakeMelbourne().configuration().basis_gates initial_layout = [None, qr[0], qr[1], qr[2], None, qr[3]] new_circuit = transpile( circuit, basis_gates=basis_gates, coupling_map=coupling_map, initial_layout=initial_layout, ) qubit_indices = {bit: idx for idx, bit in enumerate(new_circuit.qubits)} for instruction in new_circuit.data: if isinstance(instruction.operation, CXGate): self.assertIn([qubit_indices[x] for x in instruction.qubits], coupling_map) def test_transpile_qft_grid(self): """Transpile pipeline can handle 8-qubit QFT on 14-qubit grid.""" qr = QuantumRegister(8) circuit = QuantumCircuit(qr) for i, _ in enumerate(qr): for j in range(i): circuit.cp(math.pi / float(2 ** (i - j)), qr[i], qr[j]) circuit.h(qr[i]) coupling_map = FakeMelbourne().configuration().coupling_map basis_gates = FakeMelbourne().configuration().basis_gates new_circuit = transpile(circuit, basis_gates=basis_gates, coupling_map=coupling_map) qubit_indices = {bit: idx for idx, bit in enumerate(new_circuit.qubits)} for instruction in new_circuit.data: if isinstance(instruction.operation, CXGate): self.assertIn([qubit_indices[x] for x in instruction.qubits], coupling_map) def test_already_mapped_1(self): """Circuit not remapped if matches topology. See: https://github.com/Qiskit/qiskit-terra/issues/342 """ backend = FakeRueschlikon() coupling_map = backend.configuration().coupling_map basis_gates = backend.configuration().basis_gates qr = QuantumRegister(16, "qr") cr = ClassicalRegister(16, "cr") qc = QuantumCircuit(qr, cr) qc.cx(qr[3], qr[14]) qc.cx(qr[5], qr[4]) qc.h(qr[9]) qc.cx(qr[9], qr[8]) qc.x(qr[11]) qc.cx(qr[3], qr[4]) qc.cx(qr[12], qr[11]) qc.cx(qr[13], qr[4]) qc.measure(qr, cr) new_qc = transpile( qc, coupling_map=coupling_map, basis_gates=basis_gates, initial_layout=Layout.generate_trivial_layout(qr), ) qubit_indices = {bit: idx for idx, bit in enumerate(new_qc.qubits)} cx_qubits = [instr.qubits for instr in new_qc.data if instr.operation.name == "cx"] cx_qubits_physical = [ [qubit_indices[ctrl], qubit_indices[tgt]] for [ctrl, tgt] in cx_qubits ] self.assertEqual( sorted(cx_qubits_physical), [[3, 4], [3, 14], [5, 4], [9, 8], [12, 11], [13, 4]] ) def test_already_mapped_via_layout(self): """Test that a manual layout that satisfies a coupling map does not get altered. See: https://github.com/Qiskit/qiskit-terra/issues/2036 circuit: .. parsed-literal:: ┌───┐ ┌───┐ ░ ┌─┐ qn_0: ┤ H ├──■────────────■──┤ H ├─░─┤M├─── -> 9 └───┘ │ │ └───┘ ░ └╥┘ qn_1: ───────┼────────────┼────────░──╫──── -> 6 │ │ ░ ║ qn_2: ───────┼────────────┼────────░──╫──── -> 5 │ │ ░ ║ qn_3: ───────┼────────────┼────────░──╫──── -> 0 │ │ ░ ║ qn_4: ───────┼────────────┼────────░──╫──── -> 1 ┌───┐┌─┴─┐┌──────┐┌─┴─┐┌───┐ ░ ║ ┌─┐ qn_5: ┤ H ├┤ X ├┤ P(2) ├┤ X ├┤ H ├─░──╫─┤M├ -> 4 └───┘└───┘└──────┘└───┘└───┘ ░ ║ └╥┘ cn: 2/════════════════════════════════╩══╩═ 0 1 device: 0 -- 1 -- 2 -- 3 -- 4 | | 5 -- 6 -- 7 -- 8 -- 9 | | 10 - 11 - 12 - 13 - 14 | | 15 - 16 - 17 - 18 - 19 """ basis_gates = ["u1", "u2", "u3", "cx", "id"] coupling_map = [ [0, 1], [0, 5], [1, 0], [1, 2], [2, 1], [2, 3], [3, 2], [3, 4], [4, 3], [4, 9], [5, 0], [5, 6], [5, 10], [6, 5], [6, 7], [7, 6], [7, 8], [7, 12], [8, 7], [8, 9], [9, 4], [9, 8], [9, 14], [10, 5], [10, 11], [10, 15], [11, 10], [11, 12], [12, 7], [12, 11], [12, 13], [13, 12], [13, 14], [14, 9], [14, 13], [14, 19], [15, 10], [15, 16], [16, 15], [16, 17], [17, 16], [17, 18], [18, 17], [18, 19], [19, 14], [19, 18], ] q = QuantumRegister(6, name="qn") c = ClassicalRegister(2, name="cn") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[5]) qc.cx(q[0], q[5]) qc.p(2, q[5]) qc.cx(q[0], q[5]) qc.h(q[0]) qc.h(q[5]) qc.barrier(q) qc.measure(q[0], c[0]) qc.measure(q[5], c[1]) initial_layout = [ q[3], q[4], None, None, q[5], q[2], q[1], None, None, q[0], None, None, None, None, None, None, None, None, None, None, ] new_qc = transpile( qc, coupling_map=coupling_map, basis_gates=basis_gates, initial_layout=initial_layout ) qubit_indices = {bit: idx for idx, bit in enumerate(new_qc.qubits)} cx_qubits = [instr.qubits for instr in new_qc.data if instr.operation.name == "cx"] cx_qubits_physical = [ [qubit_indices[ctrl], qubit_indices[tgt]] for [ctrl, tgt] in cx_qubits ] self.assertEqual(sorted(cx_qubits_physical), [[9, 4], [9, 4]]) def test_transpile_bell(self): """Test Transpile Bell. If all correct some should exists. """ backend = BasicAer.get_backend("qasm_simulator") qubit_reg = QuantumRegister(2, name="q") clbit_reg = ClassicalRegister(2, name="c") qc = QuantumCircuit(qubit_reg, clbit_reg, name="bell") qc.h(qubit_reg[0]) qc.cx(qubit_reg[0], qubit_reg[1]) qc.measure(qubit_reg, clbit_reg) circuits = transpile(qc, backend) self.assertIsInstance(circuits, QuantumCircuit) def test_transpile_one(self): """Test transpile a single circuit. Check that the top-level `transpile` function returns a single circuit.""" backend = BasicAer.get_backend("qasm_simulator") qubit_reg = QuantumRegister(2) clbit_reg = ClassicalRegister(2) qc = QuantumCircuit(qubit_reg, clbit_reg, name="bell") qc.h(qubit_reg[0]) qc.cx(qubit_reg[0], qubit_reg[1]) qc.measure(qubit_reg, clbit_reg) circuit = transpile(qc, backend) self.assertIsInstance(circuit, QuantumCircuit) def test_transpile_two(self): """Test transpile two circuits. Check that the transpiler returns a list of two circuits. """ backend = BasicAer.get_backend("qasm_simulator") qubit_reg = QuantumRegister(2) clbit_reg = ClassicalRegister(2) qubit_reg2 = QuantumRegister(2) clbit_reg2 = ClassicalRegister(2) qc = QuantumCircuit(qubit_reg, clbit_reg, name="bell") qc.h(qubit_reg[0]) qc.cx(qubit_reg[0], qubit_reg[1]) qc.measure(qubit_reg, clbit_reg) qc_extra = QuantumCircuit(qubit_reg, qubit_reg2, clbit_reg, clbit_reg2, name="extra") qc_extra.measure(qubit_reg, clbit_reg) circuits = transpile([qc, qc_extra], backend) self.assertIsInstance(circuits, list) self.assertEqual(len(circuits), 2) for circuit in circuits: self.assertIsInstance(circuit, QuantumCircuit) def test_transpile_singleton(self): """Test transpile a single-element list with a circuit. Check that `transpile` returns a single-element list. See https://github.com/Qiskit/qiskit-terra/issues/5260 """ backend = BasicAer.get_backend("qasm_simulator") qubit_reg = QuantumRegister(2) clbit_reg = ClassicalRegister(2) qc = QuantumCircuit(qubit_reg, clbit_reg, name="bell") qc.h(qubit_reg[0]) qc.cx(qubit_reg[0], qubit_reg[1]) qc.measure(qubit_reg, clbit_reg) circuits = transpile([qc], backend) self.assertIsInstance(circuits, list) self.assertEqual(len(circuits), 1) self.assertIsInstance(circuits[0], QuantumCircuit) def test_mapping_correction(self): """Test mapping works in previous failed case.""" backend = FakeRueschlikon() qr = QuantumRegister(name="qr", size=11) cr = ClassicalRegister(name="qc", size=11) circuit = QuantumCircuit(qr, cr) circuit.u(1.564784764685993, -1.2378965763410095, 2.9746763177861713, qr[3]) circuit.u(1.2269835563676523, 1.1932982847014162, -1.5597357740824318, qr[5]) circuit.cx(qr[5], qr[3]) circuit.p(0.856768317675967, qr[3]) circuit.u(-3.3911273825190915, 0.0, 0.0, qr[5]) circuit.cx(qr[3], qr[5]) circuit.u(2.159209321625547, 0.0, 0.0, qr[5]) circuit.cx(qr[5], qr[3]) circuit.u(0.30949966910232335, 1.1706201763833217, 1.738408691990081, qr[3]) circuit.u(1.9630571407274755, -0.6818742967975088, 1.8336534616728195, qr[5]) circuit.u(1.330181833806101, 0.6003162754946363, -3.181264980452862, qr[7]) circuit.u(0.4885914820775024, 3.133297443244865, -2.794457469189904, qr[8]) circuit.cx(qr[8], qr[7]) circuit.p(2.2196187596178616, qr[7]) circuit.u(-3.152367609631023, 0.0, 0.0, qr[8]) circuit.cx(qr[7], qr[8]) circuit.u(1.2646005789809263, 0.0, 0.0, qr[8]) circuit.cx(qr[8], qr[7]) circuit.u(0.7517780502091939, 1.2828514296564781, 1.6781179605443775, qr[7]) circuit.u(0.9267400575390405, 2.0526277839695153, 2.034202361069533, qr[8]) circuit.u(2.550304293455634, 3.8250017126569698, -2.1351609599720054, qr[1]) circuit.u(0.9566260876600556, -1.1147561503064538, 2.0571590492298797, qr[4]) circuit.cx(qr[4], qr[1]) circuit.p(2.1899329069137394, qr[1]) circuit.u(-1.8371715243173294, 0.0, 0.0, qr[4]) circuit.cx(qr[1], qr[4]) circuit.u(0.4717053496327104, 0.0, 0.0, qr[4]) circuit.cx(qr[4], qr[1]) circuit.u(2.3167620677708145, -1.2337330260253256, -0.5671322899563955, qr[1]) circuit.u(1.0468499525240678, 0.8680750644809365, -1.4083720073192485, qr[4]) circuit.u(2.4204244021892807, -2.211701932616922, 3.8297006565735883, qr[10]) circuit.u(0.36660280497727255, 3.273119149343493, -1.8003362351299388, qr[6]) circuit.cx(qr[6], qr[10]) circuit.p(1.067395863586385, qr[10]) circuit.u(-0.7044917541291232, 0.0, 0.0, qr[6]) circuit.cx(qr[10], qr[6]) circuit.u(2.1830003849921527, 0.0, 0.0, qr[6]) circuit.cx(qr[6], qr[10]) circuit.u(2.1538343756723917, 2.2653381826084606, -3.550087952059485, qr[10]) circuit.u(1.307627685019188, -0.44686656993522567, -2.3238098554327418, qr[6]) circuit.u(2.2046797998462906, 0.9732961754855436, 1.8527865921467421, qr[9]) circuit.u(2.1665254613904126, -1.281337664694577, -1.2424905413631209, qr[0]) circuit.cx(qr[0], qr[9]) circuit.p(2.6209599970201007, qr[9]) circuit.u(0.04680566321901303, 0.0, 0.0, qr[0]) circuit.cx(qr[9], qr[0]) circuit.u(1.7728411151289603, 0.0, 0.0, qr[0]) circuit.cx(qr[0], qr[9]) circuit.u(2.4866395967434443, 0.48684511243566697, -3.0069186877854728, qr[9]) circuit.u(1.7369112924273789, -4.239660866163805, 1.0623389015296005, qr[0]) circuit.barrier(qr) circuit.measure(qr, cr) circuits = transpile(circuit, backend) self.assertIsInstance(circuits, QuantumCircuit) def test_transpiler_layout_from_intlist(self): """A list of ints gives layout to correctly map circuit. virtual physical q1_0 - 4 ---[H]--- q2_0 - 5 q2_1 - 6 ---[H]--- q3_0 - 8 q3_1 - 9 q3_2 - 10 ---[H]--- """ qr1 = QuantumRegister(1, "qr1") qr2 = QuantumRegister(2, "qr2") qr3 = QuantumRegister(3, "qr3") qc = QuantumCircuit(qr1, qr2, qr3) qc.h(qr1[0]) qc.h(qr2[1]) qc.h(qr3[2]) layout = [4, 5, 6, 8, 9, 10] cmap = [ [1, 0], [1, 2], [2, 3], [4, 3], [4, 10], [5, 4], [5, 6], [5, 9], [6, 8], [7, 8], [9, 8], [9, 10], [11, 3], [11, 10], [11, 12], [12, 2], [13, 1], [13, 12], ] new_circ = transpile( qc, backend=None, coupling_map=cmap, basis_gates=["u2"], initial_layout=layout ) qubit_indices = {bit: idx for idx, bit in enumerate(new_circ.qubits)} mapped_qubits = [] for instruction in new_circ.data: mapped_qubits.append(qubit_indices[instruction.qubits[0]]) self.assertEqual(mapped_qubits, [4, 6, 10]) def test_mapping_multi_qreg(self): """Test mapping works for multiple qregs.""" backend = FakeRueschlikon() qr = QuantumRegister(3, name="qr") qr2 = QuantumRegister(1, name="qr2") qr3 = QuantumRegister(4, name="qr3") cr = ClassicalRegister(3, name="cr") qc = QuantumCircuit(qr, qr2, qr3, cr) qc.h(qr[0]) qc.cx(qr[0], qr2[0]) qc.cx(qr[1], qr3[2]) qc.measure(qr, cr) circuits = transpile(qc, backend) self.assertIsInstance(circuits, QuantumCircuit) def test_transpile_circuits_diff_registers(self): """Transpile list of circuits with different qreg names.""" backend = FakeRueschlikon() circuits = [] for _ in range(2): qr = QuantumRegister(2) cr = ClassicalRegister(2) circuit = QuantumCircuit(qr, cr) circuit.h(qr[0]) circuit.cx(qr[0], qr[1]) circuit.measure(qr, cr) circuits.append(circuit) circuits = transpile(circuits, backend) self.assertIsInstance(circuits[0], QuantumCircuit) def test_wrong_initial_layout(self): """Test transpile with a bad initial layout.""" backend = FakeMelbourne() qubit_reg = QuantumRegister(2, name="q") clbit_reg = ClassicalRegister(2, name="c") qc = QuantumCircuit(qubit_reg, clbit_reg, name="bell") qc.h(qubit_reg[0]) qc.cx(qubit_reg[0], qubit_reg[1]) qc.measure(qubit_reg, clbit_reg) bad_initial_layout = [ QuantumRegister(3, "q")[0], QuantumRegister(3, "q")[1], QuantumRegister(3, "q")[2], ] with self.assertRaises(TranspilerError): transpile(qc, backend, initial_layout=bad_initial_layout) def test_parameterized_circuit_for_simulator(self): """Verify that a parameterized circuit can be transpiled for a simulator backend.""" qr = QuantumRegister(2, name="qr") qc = QuantumCircuit(qr) theta = Parameter("theta") qc.rz(theta, qr[0]) transpiled_qc = transpile(qc, backend=BasicAer.get_backend("qasm_simulator")) expected_qc = QuantumCircuit(qr) expected_qc.append(RZGate(theta), [qr[0]]) self.assertEqual(expected_qc, transpiled_qc) def test_parameterized_circuit_for_device(self): """Verify that a parameterized circuit can be transpiled for a device backend.""" qr = QuantumRegister(2, name="qr") qc = QuantumCircuit(qr) theta = Parameter("theta") qc.rz(theta, qr[0]) transpiled_qc = transpile( qc, backend=FakeMelbourne(), initial_layout=Layout.generate_trivial_layout(qr) ) qr = QuantumRegister(14, "q") expected_qc = QuantumCircuit(qr, global_phase=-1 * theta / 2.0) expected_qc.append(U1Gate(theta), [qr[0]]) self.assertEqual(expected_qc, transpiled_qc) def test_parameter_expression_circuit_for_simulator(self): """Verify that a circuit including expressions of parameters can be transpiled for a simulator backend.""" qr = QuantumRegister(2, name="qr") qc = QuantumCircuit(qr) theta = Parameter("theta") square = theta * theta qc.rz(square, qr[0]) transpiled_qc = transpile(qc, backend=BasicAer.get_backend("qasm_simulator")) expected_qc = QuantumCircuit(qr) expected_qc.append(RZGate(square), [qr[0]]) self.assertEqual(expected_qc, transpiled_qc) def test_parameter_expression_circuit_for_device(self): """Verify that a circuit including expressions of parameters can be transpiled for a device backend.""" qr = QuantumRegister(2, name="qr") qc = QuantumCircuit(qr) theta = Parameter("theta") square = theta * theta qc.rz(square, qr[0]) transpiled_qc = transpile( qc, backend=FakeMelbourne(), initial_layout=Layout.generate_trivial_layout(qr) ) qr = QuantumRegister(14, "q") expected_qc = QuantumCircuit(qr, global_phase=-1 * square / 2.0) expected_qc.append(U1Gate(square), [qr[0]]) self.assertEqual(expected_qc, transpiled_qc) def test_final_measurement_barrier_for_devices(self): """Verify BarrierBeforeFinalMeasurements pass is called in default pipeline for devices.""" qasm_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "qasm") circ = QuantumCircuit.from_qasm_file(os.path.join(qasm_dir, "example.qasm")) layout = Layout.generate_trivial_layout(*circ.qregs) orig_pass = BarrierBeforeFinalMeasurements() with patch.object(BarrierBeforeFinalMeasurements, "run", wraps=orig_pass.run) as mock_pass: transpile( circ, coupling_map=FakeRueschlikon().configuration().coupling_map, initial_layout=layout, ) self.assertTrue(mock_pass.called) def test_do_not_run_gatedirection_with_symmetric_cm(self): """When the coupling map is symmetric, do not run GateDirection.""" qasm_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "qasm") circ = QuantumCircuit.from_qasm_file(os.path.join(qasm_dir, "example.qasm")) layout = Layout.generate_trivial_layout(*circ.qregs) coupling_map = [] for node1, node2 in FakeRueschlikon().configuration().coupling_map: coupling_map.append([node1, node2]) coupling_map.append([node2, node1]) orig_pass = GateDirection(CouplingMap(coupling_map)) with patch.object(GateDirection, "run", wraps=orig_pass.run) as mock_pass: transpile(circ, coupling_map=coupling_map, initial_layout=layout) self.assertFalse(mock_pass.called) def test_optimize_to_nothing(self): """Optimize gates up to fixed point in the default pipeline See https://github.com/Qiskit/qiskit-terra/issues/2035 """ # ┌───┐ ┌───┐┌───┐┌───┐ ┌───┐ # q0_0: ┤ H ├──■──┤ X ├┤ Y ├┤ Z ├──■──┤ H ├──■────■── # └───┘┌─┴─┐└───┘└───┘└───┘┌─┴─┐└───┘┌─┴─┐┌─┴─┐ # q0_1: ─────┤ X ├───────────────┤ X ├─────┤ X ├┤ X ├ # └───┘ └───┘ └───┘└───┘ qr = QuantumRegister(2) circ = QuantumCircuit(qr) circ.h(qr[0]) circ.cx(qr[0], qr[1]) circ.x(qr[0]) circ.y(qr[0]) circ.z(qr[0]) circ.cx(qr[0], qr[1]) circ.h(qr[0]) circ.cx(qr[0], qr[1]) circ.cx(qr[0], qr[1]) after = transpile(circ, coupling_map=[[0, 1], [1, 0]], basis_gates=["u3", "u2", "u1", "cx"]) expected = QuantumCircuit(QuantumRegister(2, "q"), global_phase=-np.pi / 2) msg = f"after:\n{after}\nexpected:\n{expected}" self.assertEqual(after, expected, msg=msg) def test_pass_manager_empty(self): """Test passing an empty PassManager() to the transpiler. It should perform no transformations on the circuit. """ qr = QuantumRegister(2) circuit = QuantumCircuit(qr) circuit.h(qr[0]) circuit.h(qr[0]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) resources_before = circuit.count_ops() pass_manager = PassManager() out_circuit = pass_manager.run(circuit) resources_after = out_circuit.count_ops() self.assertDictEqual(resources_before, resources_after) def test_move_measurements(self): """Measurements applied AFTER swap mapping.""" backend = FakeRueschlikon() cmap = backend.configuration().coupling_map qasm_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "qasm") circ = QuantumCircuit.from_qasm_file(os.path.join(qasm_dir, "move_measurements.qasm")) lay = [0, 1, 15, 2, 14, 3, 13, 4, 12, 5, 11, 6] out = transpile(circ, initial_layout=lay, coupling_map=cmap, routing_method="stochastic") out_dag = circuit_to_dag(out) meas_nodes = out_dag.named_nodes("measure") for meas_node in meas_nodes: is_last_measure = all( isinstance(after_measure, DAGOutNode) for after_measure in out_dag.quantum_successors(meas_node) ) self.assertTrue(is_last_measure) @data(0, 1, 2, 3) def test_init_resets_kept_preset_passmanagers(self, optimization_level): """Test initial resets kept at all preset transpilation levels""" num_qubits = 5 qc = QuantumCircuit(num_qubits) qc.reset(range(num_qubits)) num_resets = transpile(qc, optimization_level=optimization_level).count_ops()["reset"] self.assertEqual(num_resets, num_qubits) @data(0, 1, 2, 3) def test_initialize_reset_is_not_removed(self, optimization_level): """The reset in front of initializer should NOT be removed at beginning""" qr = QuantumRegister(1, "qr") qc = QuantumCircuit(qr) qc.initialize([1.0 / math.sqrt(2), 1.0 / math.sqrt(2)], [qr[0]]) qc.initialize([1.0 / math.sqrt(2), -1.0 / math.sqrt(2)], [qr[0]]) after = transpile(qc, basis_gates=["reset", "u3"], optimization_level=optimization_level) self.assertEqual(after.count_ops()["reset"], 2, msg=f"{after}\n does not have 2 resets.") def test_initialize_FakeMelbourne(self): """Test that the zero-state resets are remove in a device not supporting them.""" desired_vector = [1 / math.sqrt(2), 0, 0, 0, 0, 0, 0, 1 / math.sqrt(2)] qr = QuantumRegister(3, "qr") qc = QuantumCircuit(qr) qc.initialize(desired_vector, [qr[0], qr[1], qr[2]]) out = transpile(qc, backend=FakeMelbourne()) out_dag = circuit_to_dag(out) reset_nodes = out_dag.named_nodes("reset") self.assertEqual(len(reset_nodes), 3) def test_non_standard_basis(self): """Test a transpilation with a non-standard basis""" qr1 = QuantumRegister(1, "q1") qr2 = QuantumRegister(2, "q2") qr3 = QuantumRegister(3, "q3") qc = QuantumCircuit(qr1, qr2, qr3) qc.h(qr1[0]) qc.h(qr2[1]) qc.h(qr3[2]) layout = [4, 5, 6, 8, 9, 10] cmap = [ [1, 0], [1, 2], [2, 3], [4, 3], [4, 10], [5, 4], [5, 6], [5, 9], [6, 8], [7, 8], [9, 8], [9, 10], [11, 3], [11, 10], [11, 12], [12, 2], [13, 1], [13, 12], ] circuit = transpile( qc, backend=None, coupling_map=cmap, basis_gates=["h"], initial_layout=layout ) dag_circuit = circuit_to_dag(circuit) resources_after = dag_circuit.count_ops() self.assertEqual({"h": 3}, resources_after) def test_hadamard_to_rot_gates(self): """Test a transpilation from H to Rx, Ry gates""" qr = QuantumRegister(1) qc = QuantumCircuit(qr) qc.h(0) expected = QuantumCircuit(qr, global_phase=np.pi / 2) expected.append(RYGate(theta=np.pi / 2), [0]) expected.append(RXGate(theta=np.pi), [0]) circuit = transpile(qc, basis_gates=["rx", "ry"], optimization_level=0) self.assertEqual(circuit, expected) def test_basis_subset(self): """Test a transpilation with a basis subset of the standard basis""" qr = QuantumRegister(1, "q1") qc = QuantumCircuit(qr) qc.h(qr[0]) qc.x(qr[0]) qc.t(qr[0]) layout = [4] cmap = [ [1, 0], [1, 2], [2, 3], [4, 3], [4, 10], [5, 4], [5, 6], [5, 9], [6, 8], [7, 8], [9, 8], [9, 10], [11, 3], [11, 10], [11, 12], [12, 2], [13, 1], [13, 12], ] circuit = transpile( qc, backend=None, coupling_map=cmap, basis_gates=["u3"], initial_layout=layout ) dag_circuit = circuit_to_dag(circuit) resources_after = dag_circuit.count_ops() self.assertEqual({"u3": 1}, resources_after) def test_check_circuit_width(self): """Verify transpilation of circuit with virtual qubits greater than physical qubits raises error""" cmap = [ [1, 0], [1, 2], [2, 3], [4, 3], [4, 10], [5, 4], [5, 6], [5, 9], [6, 8], [7, 8], [9, 8], [9, 10], [11, 3], [11, 10], [11, 12], [12, 2], [13, 1], [13, 12], ] qc = QuantumCircuit(15, 15) with self.assertRaises(TranspilerError): transpile(qc, coupling_map=cmap) @data(0, 1, 2, 3) def test_ccx_routing_method_none(self, optimization_level): """CCX without routing method.""" qc = QuantumCircuit(3) qc.cx(0, 1) qc.cx(1, 2) out = transpile( qc, routing_method="none", basis_gates=["u", "cx"], initial_layout=[0, 1, 2], seed_transpiler=0, coupling_map=[[0, 1], [1, 2]], optimization_level=optimization_level, ) self.assertTrue(Operator(qc).equiv(out)) @data(0, 1, 2, 3) def test_ccx_routing_method_none_failed(self, optimization_level): """CCX without routing method cannot be routed.""" qc = QuantumCircuit(3) qc.ccx(0, 1, 2) with self.assertRaises(TranspilerError): transpile( qc, routing_method="none", basis_gates=["u", "cx"], initial_layout=[0, 1, 2], seed_transpiler=0, coupling_map=[[0, 1], [1, 2]], optimization_level=optimization_level, ) @data(0, 1, 2, 3) def test_ms_unrolls_to_cx(self, optimization_level): """Verify a Rx,Ry,Rxx circuit transpile to a U3,CX target.""" qc = QuantumCircuit(2) qc.rx(math.pi / 2, 0) qc.ry(math.pi / 4, 1) qc.rxx(math.pi / 4, 0, 1) out = transpile(qc, basis_gates=["u3", "cx"], optimization_level=optimization_level) self.assertTrue(Operator(qc).equiv(out)) @data(0, 1, 2, 3) def test_ms_can_target_ms(self, optimization_level): """Verify a Rx,Ry,Rxx circuit can transpile to an Rx,Ry,Rxx target.""" qc = QuantumCircuit(2) qc.rx(math.pi / 2, 0) qc.ry(math.pi / 4, 1) qc.rxx(math.pi / 4, 0, 1) out = transpile(qc, basis_gates=["rx", "ry", "rxx"], optimization_level=optimization_level) self.assertTrue(Operator(qc).equiv(out)) @data(0, 1, 2, 3) def test_cx_can_target_ms(self, optimization_level): """Verify a U3,CX circuit can transpiler to a Rx,Ry,Rxx target.""" qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) qc.rz(math.pi / 4, [0, 1]) out = transpile(qc, basis_gates=["rx", "ry", "rxx"], optimization_level=optimization_level) self.assertTrue(Operator(qc).equiv(out)) @data(0, 1, 2, 3) def test_measure_doesnt_unroll_ms(self, optimization_level): """Verify a measure doesn't cause an Rx,Ry,Rxx circuit to unroll to U3,CX.""" qc = QuantumCircuit(2, 2) qc.rx(math.pi / 2, 0) qc.ry(math.pi / 4, 1) qc.rxx(math.pi / 4, 0, 1) qc.measure([0, 1], [0, 1]) out = transpile(qc, basis_gates=["rx", "ry", "rxx"], optimization_level=optimization_level) self.assertEqual(qc, out) @data( ["cx", "u3"], ["cz", "u3"], ["cz", "rx", "rz"], ["rxx", "rx", "ry"], ["iswap", "rx", "rz"], ) def test_block_collection_runs_for_non_cx_bases(self, basis_gates): """Verify block collection is run when a single two qubit gate is in the basis.""" twoq_gate, *_ = basis_gates qc = QuantumCircuit(2) qc.cx(0, 1) qc.cx(1, 0) qc.cx(0, 1) qc.cx(0, 1) out = transpile(qc, basis_gates=basis_gates, optimization_level=3) self.assertLessEqual(out.count_ops()[twoq_gate], 2) @unpack @data( (["u3", "cx"], {"u3": 1, "cx": 1}), (["rx", "rz", "iswap"], {"rx": 6, "rz": 12, "iswap": 2}), (["rx", "ry", "rxx"], {"rx": 6, "ry": 5, "rxx": 1}), ) def test_block_collection_reduces_1q_gate(self, basis_gates, gate_counts): """For synthesis to non-U3 bases, verify we minimize 1q gates.""" qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) out = transpile(qc, basis_gates=basis_gates, optimization_level=3) self.assertTrue(Operator(out).equiv(qc)) self.assertTrue(set(out.count_ops()).issubset(basis_gates)) for basis_gate in basis_gates: self.assertLessEqual(out.count_ops()[basis_gate], gate_counts[basis_gate]) @combine( optimization_level=[0, 1, 2, 3], basis_gates=[ ["u3", "cx"], ["rx", "rz", "iswap"], ["rx", "ry", "rxx"], ], ) def test_translation_method_synthesis(self, optimization_level, basis_gates): """Verify translation_method='synthesis' gets to the basis.""" qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) out = transpile( qc, translation_method="synthesis", basis_gates=basis_gates, optimization_level=optimization_level, ) self.assertTrue(Operator(out).equiv(qc)) self.assertTrue(set(out.count_ops()).issubset(basis_gates)) def test_transpiled_custom_gates_calibration(self): """Test if transpiled calibrations is equal to custom gates circuit calibrations.""" custom_180 = Gate("mycustom", 1, [3.14]) custom_90 = Gate("mycustom", 1, [1.57]) circ = QuantumCircuit(2) circ.append(custom_180, [0]) circ.append(custom_90, [1]) with pulse.build() as q0_x180: pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0)) with pulse.build() as q1_y90: pulse.play(pulse.library.Gaussian(20, -1.0, 3.0), pulse.DriveChannel(1)) # Add calibration circ.add_calibration(custom_180, [0], q0_x180) circ.add_calibration(custom_90, [1], q1_y90) backend = FakeBoeblingen() transpiled_circuit = transpile( circ, backend=backend, layout_method="trivial", ) self.assertEqual(transpiled_circuit.calibrations, circ.calibrations) self.assertEqual(list(transpiled_circuit.count_ops().keys()), ["mycustom"]) self.assertEqual(list(transpiled_circuit.count_ops().values()), [2]) def test_transpiled_basis_gates_calibrations(self): """Test if the transpiled calibrations is equal to basis gates circuit calibrations.""" circ = QuantumCircuit(2) circ.h(0) with pulse.build() as q0_x180: pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0)) # Add calibration circ.add_calibration("h", [0], q0_x180) backend = FakeBoeblingen() transpiled_circuit = transpile( circ, backend=backend, ) self.assertEqual(transpiled_circuit.calibrations, circ.calibrations) def test_transpile_calibrated_custom_gate_on_diff_qubit(self): """Test if the custom, non calibrated gate raises QiskitError.""" custom_180 = Gate("mycustom", 1, [3.14]) circ = QuantumCircuit(2) circ.append(custom_180, [0]) with pulse.build() as q0_x180: pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0)) # Add calibration circ.add_calibration(custom_180, [1], q0_x180) backend = FakeBoeblingen() with self.assertRaises(QiskitError): transpile(circ, backend=backend, layout_method="trivial") def test_transpile_calibrated_nonbasis_gate_on_diff_qubit(self): """Test if the non-basis gates are transpiled if they are on different qubit that is not calibrated.""" circ = QuantumCircuit(2) circ.h(0) circ.h(1) with pulse.build() as q0_x180: pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0)) # Add calibration circ.add_calibration("h", [1], q0_x180) backend = FakeBoeblingen() transpiled_circuit = transpile( circ, backend=backend, ) self.assertEqual(transpiled_circuit.calibrations, circ.calibrations) self.assertEqual(set(transpiled_circuit.count_ops().keys()), {"u2", "h"}) def test_transpile_subset_of_calibrated_gates(self): """Test transpiling a circuit with both basis gate (not-calibrated) and a calibrated gate on different qubits.""" x_180 = Gate("mycustom", 1, [3.14]) circ = QuantumCircuit(2) circ.h(0) circ.append(x_180, [0]) circ.h(1) with pulse.build() as q0_x180: pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0)) circ.add_calibration(x_180, [0], q0_x180) circ.add_calibration("h", [1], q0_x180) # 'h' is calibrated on qubit 1 transpiled_circ = transpile(circ, FakeBoeblingen(), layout_method="trivial") self.assertEqual(set(transpiled_circ.count_ops().keys()), {"u2", "mycustom", "h"}) def test_parameterized_calibrations_transpile(self): """Check that gates can be matched to their calibrations before and after parameter assignment.""" tau = Parameter("tau") circ = QuantumCircuit(3, 3) circ.append(Gate("rxt", 1, [2 * 3.14 * tau]), [0]) def q0_rxt(tau): with pulse.build() as q0_rxt: pulse.play(pulse.library.Gaussian(20, 0.4 * tau, 3.0), pulse.DriveChannel(0)) return q0_rxt circ.add_calibration("rxt", [0], q0_rxt(tau), [2 * 3.14 * tau]) transpiled_circ = transpile(circ, FakeBoeblingen(), layout_method="trivial") self.assertEqual(set(transpiled_circ.count_ops().keys()), {"rxt"}) circ = circ.assign_parameters({tau: 1}) transpiled_circ = transpile(circ, FakeBoeblingen(), layout_method="trivial") self.assertEqual(set(transpiled_circ.count_ops().keys()), {"rxt"}) def test_inst_durations_from_calibrations(self): """Test that circuit calibrations can be used instead of explicitly supplying inst_durations. """ qc = QuantumCircuit(2) qc.append(Gate("custom", 1, []), [0]) with pulse.build() as cal: pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0)) qc.add_calibration("custom", [0], cal) out = transpile(qc, scheduling_method="alap") self.assertEqual(out.duration, cal.duration) @data(0, 1, 2, 3) def test_multiqubit_gates_calibrations(self, opt_level): """Test multiqubit gate > 2q with calibrations works Adapted from issue description in https://github.com/Qiskit/qiskit-terra/issues/6572 """ circ = QuantumCircuit(5) custom_gate = Gate("my_custom_gate", 5, []) circ.append(custom_gate, [0, 1, 2, 3, 4]) circ.measure_all() backend = FakeBoeblingen() with pulse.build(backend, name="custom") as my_schedule: pulse.play( pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.drive_channel(0) ) pulse.play( pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.drive_channel(1) ) pulse.play( pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.drive_channel(2) ) pulse.play( pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.drive_channel(3) ) pulse.play( pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.drive_channel(4) ) pulse.play( pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.ControlChannel(1) ) pulse.play( pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.ControlChannel(2) ) pulse.play( pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.ControlChannel(3) ) pulse.play( pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.ControlChannel(4) ) circ.add_calibration("my_custom_gate", [0, 1, 2, 3, 4], my_schedule, []) trans_circ = transpile(circ, backend, optimization_level=opt_level, layout_method="trivial") self.assertEqual({"measure": 5, "my_custom_gate": 1, "barrier": 1}, trans_circ.count_ops()) @data(0, 1, 2, 3) def test_circuit_with_delay(self, optimization_level): """Verify a circuit with delay can transpile to a scheduled circuit.""" qc = QuantumCircuit(2) qc.h(0) qc.delay(500, 1) qc.cx(0, 1) out = transpile( qc, scheduling_method="alap", basis_gates=["h", "cx"], instruction_durations=[("h", 0, 200), ("cx", [0, 1], 700)], optimization_level=optimization_level, ) self.assertEqual(out.duration, 1200) def test_delay_converts_to_dt(self): """Test that a delay instruction is converted to units of dt given a backend.""" qc = QuantumCircuit(2) qc.delay(1000, [0], unit="us") backend = FakeRueschlikon() backend.configuration().dt = 0.5e-6 out = transpile([qc, qc], backend) self.assertEqual(out[0].data[0].operation.unit, "dt") self.assertEqual(out[1].data[0].operation.unit, "dt") out = transpile(qc, dt=1e-9) self.assertEqual(out.data[0].operation.unit, "dt") def test_scheduling_backend_v2(self): """Test that scheduling method works with Backendv2.""" qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) qc.measure_all() backend = FakeMumbaiV2() out = transpile([qc, qc], backend, scheduling_method="alap") self.assertIn("delay", out[0].count_ops()) self.assertIn("delay", out[1].count_ops()) @data(1, 2, 3) def test_no_infinite_loop(self, optimization_level): """Verify circuit cost always descends and optimization does not flip flop indefinitely.""" qc = QuantumCircuit(1) qc.ry(0.2, 0) out = transpile( qc, basis_gates=["id", "p", "sx", "cx"], optimization_level=optimization_level ) # Expect a -pi/2 global phase for the U3 to RZ/SX conversion, and # a -0.5 * theta phase for RZ to P twice, once at theta, and once at 3 pi # for the second and third RZ gates in the U3 decomposition. expected = QuantumCircuit( 1, global_phase=-np.pi / 2 - 0.5 * (-0.2 + np.pi) - 0.5 * 3 * np.pi ) expected.p(-np.pi, 0) expected.sx(0) expected.p(np.pi - 0.2, 0) expected.sx(0) error_message = ( f"\nOutput circuit:\n{out!s}\n{Operator(out).data}\n" f"Expected circuit:\n{expected!s}\n{Operator(expected).data}" ) self.assertEqual(out, expected, error_message) @data(0, 1, 2, 3) def test_transpile_preserves_circuit_metadata(self, optimization_level): """Verify that transpile preserves circuit metadata in the output.""" circuit = QuantumCircuit(2, metadata={"experiment_id": "1234", "execution_number": 4}) circuit.h(0) circuit.cx(0, 1) cmap = [ [1, 0], [1, 2], [2, 3], [4, 3], [4, 10], [5, 4], [5, 6], [5, 9], [6, 8], [7, 8], [9, 8], [9, 10], [11, 3], [11, 10], [11, 12], [12, 2], [13, 1], [13, 12], ] res = transpile( circuit, basis_gates=["id", "p", "sx", "cx"], coupling_map=cmap, optimization_level=optimization_level, ) self.assertEqual(circuit.metadata, res.metadata) @data(0, 1, 2, 3) def test_transpile_optional_registers(self, optimization_level): """Verify transpile accepts circuits without registers end-to-end.""" qubits = [Qubit() for _ in range(3)] clbits = [Clbit() for _ in range(3)] qc = QuantumCircuit(qubits, clbits) qc.h(0) qc.cx(0, 1) qc.cx(1, 2) qc.measure(qubits, clbits) out = transpile(qc, FakeBoeblingen(), optimization_level=optimization_level) self.assertEqual(len(out.qubits), FakeBoeblingen().configuration().num_qubits) self.assertEqual(len(out.clbits), len(clbits)) @data(0, 1, 2, 3) def test_translate_ecr_basis(self, optimization_level): """Verify that rewriting in ECR basis is efficient.""" circuit = QuantumCircuit(2) circuit.append(random_unitary(4, seed=1), [0, 1]) circuit.barrier() circuit.cx(0, 1) circuit.barrier() circuit.swap(0, 1) circuit.barrier() circuit.iswap(0, 1) res = transpile(circuit, basis_gates=["u", "ecr"], optimization_level=optimization_level) self.assertEqual(res.count_ops()["ecr"], 9) self.assertTrue(Operator(res).equiv(circuit)) def test_optimize_ecr_basis(self): """Test highest optimization level can optimize over ECR.""" circuit = QuantumCircuit(2) circuit.swap(1, 0) circuit.iswap(0, 1) res = transpile(circuit, basis_gates=["u", "ecr"], optimization_level=3) self.assertEqual(res.count_ops()["ecr"], 1) self.assertTrue(Operator(res).equiv(circuit)) def test_approximation_degree_invalid(self): """Test invalid approximation degree raises.""" circuit = QuantumCircuit(2) circuit.swap(0, 1) with self.assertRaises(QiskitError): transpile(circuit, basis_gates=["u", "cz"], approximation_degree=1.1) def test_approximation_degree(self): """Test more approximation gives lower-cost circuit.""" circuit = QuantumCircuit(2) circuit.swap(0, 1) circuit.h(0) circ_10 = transpile( circuit, basis_gates=["u", "cx"], translation_method="synthesis", approximation_degree=0.1, ) circ_90 = transpile( circuit, basis_gates=["u", "cx"], translation_method="synthesis", approximation_degree=0.9, ) self.assertLess(circ_10.depth(), circ_90.depth()) @data(0, 1, 2, 3) def test_synthesis_translation_method_with_single_qubit_gates(self, optimization_level): """Test that synthesis basis translation works for solely 1q circuit""" qc = QuantumCircuit(3) qc.h(0) qc.h(1) qc.h(2) res = transpile( qc, basis_gates=["id", "rz", "x", "sx", "cx"], translation_method="synthesis", optimization_level=optimization_level, ) expected = QuantumCircuit(3, global_phase=3 * np.pi / 4) expected.rz(np.pi / 2, 0) expected.rz(np.pi / 2, 1) expected.rz(np.pi / 2, 2) expected.sx(0) expected.sx(1) expected.sx(2) expected.rz(np.pi / 2, 0) expected.rz(np.pi / 2, 1) expected.rz(np.pi / 2, 2) self.assertEqual(res, expected) @data(0, 1, 2, 3) def test_synthesis_translation_method_with_gates_outside_basis(self, optimization_level): """Test that synthesis translation works for circuits with single gates outside bassis""" qc = QuantumCircuit(2) qc.swap(0, 1) res = transpile( qc, basis_gates=["id", "rz", "x", "sx", "cx"], translation_method="synthesis", optimization_level=optimization_level, ) if optimization_level != 3: self.assertTrue(Operator(qc).equiv(res)) self.assertNotIn("swap", res.count_ops()) else: # Optimization level 3 eliminates the pointless swap self.assertEqual(res, QuantumCircuit(2)) @data(0, 1, 2, 3) def test_target_ideal_gates(self, opt_level): """Test that transpile() with a custom ideal sim target works.""" theta = Parameter("θ") phi = Parameter("ϕ") lam = Parameter("λ") target = Target(num_qubits=2) target.add_instruction(UGate(theta, phi, lam), {(0,): None, (1,): None}) target.add_instruction(CXGate(), {(0, 1): None}) target.add_instruction(Measure(), {(0,): None, (1,): None}) qubit_reg = QuantumRegister(2, name="q") clbit_reg = ClassicalRegister(2, name="c") qc = QuantumCircuit(qubit_reg, clbit_reg, name="bell") qc.h(qubit_reg[0]) qc.cx(qubit_reg[0], qubit_reg[1]) result = transpile(qc, target=target, optimization_level=opt_level) self.assertEqual(Operator.from_circuit(result), Operator.from_circuit(qc)) @data(0, 1, 2, 3) def test_transpile_with_custom_control_flow_target(self, opt_level): """Test transpile() with a target and constrol flow ops.""" target = FakeMumbaiV2().target target.add_instruction(ForLoopOp, name="for_loop") target.add_instruction(WhileLoopOp, name="while_loop") target.add_instruction(IfElseOp, name="if_else") target.add_instruction(SwitchCaseOp, name="switch_case") circuit = QuantumCircuit(6, 1) circuit.h(0) circuit.measure(0, 0) circuit.cx(0, 1) circuit.cz(0, 2) circuit.append(CustomCX(), [1, 2], []) with circuit.for_loop((1,)): circuit.cx(0, 1) circuit.cz(0, 2) circuit.append(CustomCX(), [1, 2], []) with circuit.if_test((circuit.clbits[0], True)) as else_: circuit.cx(0, 1) circuit.cz(0, 2) circuit.append(CustomCX(), [1, 2], []) with else_: circuit.cx(3, 4) circuit.cz(3, 5) circuit.append(CustomCX(), [4, 5], []) with circuit.while_loop((circuit.clbits[0], True)): circuit.cx(3, 4) circuit.cz(3, 5) circuit.append(CustomCX(), [4, 5], []) with circuit.switch(circuit.cregs[0]) as case_: with case_(0): circuit.cx(0, 1) circuit.cz(0, 2) circuit.append(CustomCX(), [1, 2], []) with case_(1): circuit.cx(1, 2) circuit.cz(1, 3) circuit.append(CustomCX(), [2, 3], []) transpiled = transpile( circuit, optimization_level=opt_level, target=target, seed_transpiler=12434 ) # Tests of the complete validity of a circuit are mostly done at the indiviual pass level; # here we're just checking that various passes do appear to have run. self.assertIsInstance(transpiled, QuantumCircuit) # Assert layout ran. self.assertIsNot(getattr(transpiled, "_layout", None), None) def _visit_block(circuit, qubit_mapping=None): for instruction in circuit: qargs = tuple(qubit_mapping[x] for x in instruction.qubits) self.assertTrue(target.instruction_supported(instruction.operation.name, qargs)) if isinstance(instruction.operation, ControlFlowOp): for block in instruction.operation.blocks: new_mapping = { inner: qubit_mapping[outer] for outer, inner in zip(instruction.qubits, block.qubits) } _visit_block(block, new_mapping) # Assert unrolling ran. self.assertNotIsInstance(instruction.operation, CustomCX) # Assert translation ran. self.assertNotIsInstance(instruction.operation, CZGate) # Assert routing ran. _visit_block( transpiled, qubit_mapping={qubit: index for index, qubit in enumerate(transpiled.qubits)}, ) @data(1, 2, 3) def test_transpile_identity_circuit_no_target(self, opt_level): """Test circuit equivalent to identity is optimized away for all optimization levels >0. Reproduce taken from https://github.com/Qiskit/qiskit-terra/issues/9217 """ qr1 = QuantumRegister(3, "state") qr2 = QuantumRegister(2, "ancilla") cr = ClassicalRegister(2, "c") qc = QuantumCircuit(qr1, qr2, cr) qc.h(qr1[0]) qc.cx(qr1[0], qr1[1]) qc.cx(qr1[1], qr1[2]) qc.cx(qr1[1], qr1[2]) qc.cx(qr1[0], qr1[1]) qc.h(qr1[0]) empty_qc = QuantumCircuit(qr1, qr2, cr) result = transpile(qc, optimization_level=opt_level) self.assertEqual(empty_qc, result) @data(0, 1, 2, 3) def test_initial_layout_with_loose_qubits(self, opt_level): """Regression test of gh-10125.""" qc = QuantumCircuit([Qubit(), Qubit()]) qc.cx(0, 1) transpiled = transpile(qc, initial_layout=[1, 0], optimization_level=opt_level) self.assertIsNotNone(transpiled.layout) self.assertEqual( transpiled.layout.initial_layout, Layout({0: qc.qubits[1], 1: qc.qubits[0]}) ) @data(0, 1, 2, 3) def test_initial_layout_with_overlapping_qubits(self, opt_level): """Regression test of gh-10125.""" qr1 = QuantumRegister(2, "qr1") qr2 = QuantumRegister(bits=qr1[:]) qc = QuantumCircuit(qr1, qr2) qc.cx(0, 1) transpiled = transpile(qc, initial_layout=[1, 0], optimization_level=opt_level) self.assertIsNotNone(transpiled.layout) self.assertEqual( transpiled.layout.initial_layout, Layout({0: qc.qubits[1], 1: qc.qubits[0]}) ) @combine(opt_level=[0, 1, 2, 3], basis=[["rz", "x"], ["rx", "z"], ["rz", "y"], ["ry", "x"]]) def test_paulis_to_constrained_1q_basis(self, opt_level, basis): """Test that Pauli-gate circuits can be transpiled to constrained 1q bases that do not contain any root-Pauli gates.""" qc = QuantumCircuit(1) qc.x(0) qc.barrier() qc.y(0) qc.barrier() qc.z(0) transpiled = transpile(qc, basis_gates=basis, optimization_level=opt_level) self.assertGreaterEqual(set(basis) | {"barrier"}, transpiled.count_ops().keys()) self.assertEqual(Operator(qc), Operator(transpiled)) @ddt class TestPostTranspileIntegration(QiskitTestCase): """Test that the output of `transpile` is usable in various other integration contexts.""" def _regular_circuit(self): a = Parameter("a") regs = [ QuantumRegister(2, name="q0"), QuantumRegister(3, name="q1"), ClassicalRegister(2, name="c0"), ] bits = [Qubit(), Qubit(), Clbit()] base = QuantumCircuit(*regs, bits) base.h(0) base.measure(0, 0) base.cx(0, 1) base.cz(0, 2) base.cz(0, 3) base.cz(1, 4) base.cx(1, 5) base.measure(1, 1) base.append(CustomCX(), [3, 6]) base.append(CustomCX(), [5, 4]) base.append(CustomCX(), [5, 3]) base.append(CustomCX(), [2, 4]).c_if(base.cregs[0], 3) base.ry(a, 4) base.measure(4, 2) return base def _control_flow_circuit(self): a = Parameter("a") regs = [ QuantumRegister(2, name="q0"), QuantumRegister(3, name="q1"), ClassicalRegister(2, name="c0"), ] bits = [Qubit(), Qubit(), Clbit()] base = QuantumCircuit(*regs, bits) base.h(0) base.measure(0, 0) with base.if_test((base.cregs[0], 1)) as else_: base.cx(0, 1) base.cz(0, 2) base.cz(0, 3) with else_: base.cz(1, 4) with base.for_loop((1, 2)): base.cx(1, 5) base.measure(2, 2) with base.while_loop((2, False)): base.append(CustomCX(), [3, 6]) base.append(CustomCX(), [5, 4]) base.append(CustomCX(), [5, 3]) base.append(CustomCX(), [2, 4]) base.ry(a, 4) base.measure(4, 2) with base.switch(base.cregs[0]) as case_: with case_(0, 1): base.cz(3, 5) with case_(case_.DEFAULT): base.cz(1, 4) base.append(CustomCX(), [2, 4]) base.append(CustomCX(), [3, 4]) return base def _control_flow_expr_circuit(self): a = Parameter("a") regs = [ QuantumRegister(2, name="q0"), QuantumRegister(3, name="q1"), ClassicalRegister(2, name="c0"), ] bits = [Qubit(), Qubit(), Clbit()] base = QuantumCircuit(*regs, bits) base.h(0) base.measure(0, 0) with base.if_test(expr.equal(base.cregs[0], 1)) as else_: base.cx(0, 1) base.cz(0, 2) base.cz(0, 3) with else_: base.cz(1, 4) with base.for_loop((1, 2)): base.cx(1, 5) base.measure(2, 2) with base.while_loop(expr.logic_not(bits[2])): base.append(CustomCX(), [3, 6]) base.append(CustomCX(), [5, 4]) base.append(CustomCX(), [5, 3]) base.append(CustomCX(), [2, 4]) base.ry(a, 4) base.measure(4, 2) with base.switch(expr.bit_and(base.cregs[0], 2)) as case_: with case_(0, 1): base.cz(3, 5) with case_(case_.DEFAULT): base.cz(1, 4) base.append(CustomCX(), [2, 4]) base.append(CustomCX(), [3, 4]) return base @data(0, 1, 2, 3) def test_qpy_roundtrip(self, optimization_level): """Test that the output of a transpiled circuit can be round-tripped through QPY.""" transpiled = transpile( self._regular_circuit(), backend=FakeMelbourne(), optimization_level=optimization_level, seed_transpiler=2022_10_17, ) # Round-tripping the layout is out-of-scope for QPY while it's a private attribute. transpiled._layout = None buffer = io.BytesIO() qpy.dump(transpiled, buffer) buffer.seek(0) round_tripped = qpy.load(buffer)[0] self.assertEqual(round_tripped, transpiled) @data(0, 1, 2, 3) def test_qpy_roundtrip_backendv2(self, optimization_level): """Test that the output of a transpiled circuit can be round-tripped through QPY.""" transpiled = transpile( self._regular_circuit(), backend=FakeMumbaiV2(), optimization_level=optimization_level, seed_transpiler=2022_10_17, ) # Round-tripping the layout is out-of-scope for QPY while it's a private attribute. transpiled._layout = None buffer = io.BytesIO() qpy.dump(transpiled, buffer) buffer.seek(0) round_tripped = qpy.load(buffer)[0] self.assertEqual(round_tripped, transpiled) @data(0, 1, 2, 3) def test_qpy_roundtrip_control_flow(self, optimization_level): """Test that the output of a transpiled circuit with control flow can be round-tripped through QPY.""" if optimization_level == 3 and sys.platform == "win32": self.skipTest( "This test case triggers a bug in the eigensolver routine on windows. " "See #10345 for more details." ) backend = FakeMelbourne() transpiled = transpile( self._control_flow_circuit(), backend=backend, basis_gates=backend.configuration().basis_gates + ["if_else", "for_loop", "while_loop", "switch_case"], optimization_level=optimization_level, seed_transpiler=2022_10_17, ) # Round-tripping the layout is out-of-scope for QPY while it's a private attribute. transpiled._layout = None buffer = io.BytesIO() qpy.dump(transpiled, buffer) buffer.seek(0) round_tripped = qpy.load(buffer)[0] self.assertEqual(round_tripped, transpiled) @data(0, 1, 2, 3) def test_qpy_roundtrip_control_flow_backendv2(self, optimization_level): """Test that the output of a transpiled circuit with control flow can be round-tripped through QPY.""" backend = FakeMumbaiV2() backend.target.add_instruction(IfElseOp, name="if_else") backend.target.add_instruction(ForLoopOp, name="for_loop") backend.target.add_instruction(WhileLoopOp, name="while_loop") backend.target.add_instruction(SwitchCaseOp, name="switch_case") transpiled = transpile( self._control_flow_circuit(), backend=backend, optimization_level=optimization_level, seed_transpiler=2022_10_17, ) # Round-tripping the layout is out-of-scope for QPY while it's a private attribute. transpiled._layout = None buffer = io.BytesIO() qpy.dump(transpiled, buffer) buffer.seek(0) round_tripped = qpy.load(buffer)[0] self.assertEqual(round_tripped, transpiled) @data(0, 1, 2, 3) def test_qpy_roundtrip_control_flow_expr(self, optimization_level): """Test that the output of a transpiled circuit with control flow including `Expr` nodes can be round-tripped through QPY.""" if optimization_level == 3 and sys.platform == "win32": self.skipTest( "This test case triggers a bug in the eigensolver routine on windows. " "See #10345 for more details." ) backend = FakeMelbourne() transpiled = transpile( self._control_flow_expr_circuit(), backend=backend, basis_gates=backend.configuration().basis_gates + ["if_else", "for_loop", "while_loop", "switch_case"], optimization_level=optimization_level, seed_transpiler=2023_07_26, ) buffer = io.BytesIO() qpy.dump(transpiled, buffer) buffer.seek(0) round_tripped = qpy.load(buffer)[0] self.assertEqual(round_tripped, transpiled) @data(0, 1, 2, 3) def test_qpy_roundtrip_control_flow_expr_backendv2(self, optimization_level): """Test that the output of a transpiled circuit with control flow including `Expr` nodes can be round-tripped through QPY.""" backend = FakeMumbaiV2() backend.target.add_instruction(IfElseOp, name="if_else") backend.target.add_instruction(ForLoopOp, name="for_loop") backend.target.add_instruction(WhileLoopOp, name="while_loop") backend.target.add_instruction(SwitchCaseOp, name="switch_case") transpiled = transpile( self._control_flow_circuit(), backend=backend, optimization_level=optimization_level, seed_transpiler=2023_07_26, ) buffer = io.BytesIO() qpy.dump(transpiled, buffer) buffer.seek(0) round_tripped = qpy.load(buffer)[0] self.assertEqual(round_tripped, transpiled) @data(0, 1, 2, 3) def test_qasm3_output(self, optimization_level): """Test that the output of a transpiled circuit can be dumped into OpenQASM 3.""" transpiled = transpile( self._regular_circuit(), backend=FakeMelbourne(), optimization_level=optimization_level, seed_transpiler=2022_10_17, ) # TODO: There's not a huge amount we can sensibly test for the output here until we can # round-trip the OpenQASM 3 back into a Terra circuit. Mostly we're concerned that the dump # itself doesn't throw an error, though. self.assertIsInstance(qasm3.dumps(transpiled).strip(), str) @data(0, 1, 2, 3) def test_qasm3_output_control_flow(self, optimization_level): """Test that the output of a transpiled circuit with control flow can be dumped into OpenQASM 3.""" backend = FakeMumbaiV2() backend.target.add_instruction(IfElseOp, name="if_else") backend.target.add_instruction(ForLoopOp, name="for_loop") backend.target.add_instruction(WhileLoopOp, name="while_loop") backend.target.add_instruction(SwitchCaseOp, name="switch_case") transpiled = transpile( self._control_flow_circuit(), backend=backend, optimization_level=optimization_level, seed_transpiler=2022_10_17, ) # TODO: There's not a huge amount we can sensibly test for the output here until we can # round-trip the OpenQASM 3 back into a Terra circuit. Mostly we're concerned that the dump # itself doesn't throw an error, though. self.assertIsInstance( qasm3.dumps(transpiled, experimental=qasm3.ExperimentalFeatures.SWITCH_CASE_V1).strip(), str, ) @data(0, 1, 2, 3) def test_qasm3_output_control_flow_expr(self, optimization_level): """Test that the output of a transpiled circuit with control flow and `Expr` nodes can be dumped into OpenQASM 3.""" backend = FakeMumbaiV2() backend.target.add_instruction(IfElseOp, name="if_else") backend.target.add_instruction(ForLoopOp, name="for_loop") backend.target.add_instruction(WhileLoopOp, name="while_loop") backend.target.add_instruction(SwitchCaseOp, name="switch_case") transpiled = transpile( self._control_flow_circuit(), backend=backend, optimization_level=optimization_level, seed_transpiler=2023_07_26, ) # TODO: There's not a huge amount we can sensibly test for the output here until we can # round-trip the OpenQASM 3 back into a Terra circuit. Mostly we're concerned that the dump # itself doesn't throw an error, though. self.assertIsInstance( qasm3.dumps(transpiled, experimental=qasm3.ExperimentalFeatures.SWITCH_CASE_V1).strip(), str, ) @data(0, 1, 2, 3) def test_transpile_target_no_measurement_error(self, opt_level): """Test that transpile with a target which contains ideal measurement works Reproduce from https://github.com/Qiskit/qiskit-terra/issues/8969 """ target = Target() target.add_instruction(Measure(), {(0,): None}) qc = QuantumCircuit(1, 1) qc.measure(0, 0) res = transpile(qc, target=target, optimization_level=opt_level) self.assertEqual(qc, res) def test_transpile_final_layout_updated_with_post_layout(self): """Test that the final layout is correctly set when vf2postlayout runs. Reproduce from #10457 """ def _get_index_layout(transpiled_circuit: QuantumCircuit, num_source_qubits: int): """Return the index layout of a transpiled circuit""" layout = transpiled_circuit.layout if layout is None: return list(range(num_source_qubits)) pos_to_virt = {v: k for k, v in layout.input_qubit_mapping.items()} qubit_indices = [] for index in range(num_source_qubits): qubit_idx = layout.initial_layout[pos_to_virt[index]] if layout.final_layout is not None: qubit_idx = layout.final_layout[transpiled_circuit.qubits[qubit_idx]] qubit_indices.append(qubit_idx) return qubit_indices vf2_post_layout_called = False def callback(**kwargs): nonlocal vf2_post_layout_called if isinstance(kwargs["pass_"], VF2PostLayout): vf2_post_layout_called = True self.assertIsNotNone(kwargs["property_set"]["post_layout"]) backend = FakeVigo() qubits = 3 qc = QuantumCircuit(qubits) for i in range(5): qc.cx(i % qubits, int(i + qubits / 2) % qubits) tqc = transpile(qc, backend=backend, seed_transpiler=4242, callback=callback) self.assertTrue(vf2_post_layout_called) self.assertEqual([3, 2, 1], _get_index_layout(tqc, qubits)) class StreamHandlerRaiseException(StreamHandler): """Handler class that will raise an exception on formatting errors.""" def handleError(self, record): raise sys.exc_info() class TestLogTranspile(QiskitTestCase): """Testing the log_transpile option.""" def setUp(self): super().setUp() logger = getLogger() self.addCleanup(logger.setLevel, logger.level) logger.setLevel("DEBUG") self.output = io.StringIO() logger.addHandler(StreamHandlerRaiseException(self.output)) self.circuit = QuantumCircuit(QuantumRegister(1)) def assertTranspileLog(self, log_msg): """Runs the transpiler and check for logs containing specified message""" transpile(self.circuit) self.output.seek(0) # Filter unrelated log lines output_lines = self.output.readlines() transpile_log_lines = [x for x in output_lines if log_msg in x] self.assertTrue(len(transpile_log_lines) > 0) def test_transpile_log_time(self): """Check Total Transpile Time is logged""" self.assertTranspileLog("Total Transpile Time") class TestTranspileCustomPM(QiskitTestCase): """Test transpile function with custom pass manager""" def test_custom_multiple_circuits(self): """Test transpiling with custom pass manager and multiple circuits. This tests created a deadlock, so it needs to be monitored for timeout. See: https://github.com/Qiskit/qiskit-terra/issues/3925 """ qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) pm_conf = PassManagerConfig( initial_layout=None, basis_gates=["u1", "u2", "u3", "cx"], coupling_map=CouplingMap([[0, 1]]), backend_properties=None, seed_transpiler=1, ) passmanager = level_0_pass_manager(pm_conf) transpiled = passmanager.run([qc, qc]) expected = QuantumCircuit(QuantumRegister(2, "q")) expected.append(U2Gate(0, 3.141592653589793), [0]) expected.cx(0, 1) self.assertEqual(len(transpiled), 2) self.assertEqual(transpiled[0], expected) self.assertEqual(transpiled[1], expected) @ddt class TestTranspileParallel(QiskitTestCase): """Test transpile() in parallel.""" def setUp(self): super().setUp() # Force parallel execution to True to test multiprocessing for this class original_val = parallel.PARALLEL_DEFAULT def restore_default(): parallel.PARALLEL_DEFAULT = original_val self.addCleanup(restore_default) parallel.PARALLEL_DEFAULT = True @data(0, 1, 2, 3) def test_parallel_multiprocessing(self, opt_level): """Test parallel dispatch works with multiprocessing.""" qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) qc.measure_all() backend = FakeMumbaiV2() pm = generate_preset_pass_manager(opt_level, backend) res = pm.run([qc, qc]) for circ in res: self.assertIsInstance(circ, QuantumCircuit) @data(0, 1, 2, 3) def test_parallel_with_target(self, opt_level): """Test that parallel dispatch works with a manual target.""" qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) qc.measure_all() target = FakeMumbaiV2().target res = transpile([qc] * 3, target=target, optimization_level=opt_level) self.assertIsInstance(res, list) for circ in res: self.assertIsInstance(circ, QuantumCircuit) @data(0, 1, 2, 3) def test_parallel_dispatch(self, opt_level): """Test that transpile in parallel works for all optimization levels.""" backend = FakeRueschlikon() qr = QuantumRegister(16) cr = ClassicalRegister(16) qc = QuantumCircuit(qr, cr) qc.h(qr[0]) for k in range(1, 15): qc.cx(qr[0], qr[k]) qc.measure(qr, cr) qlist = [qc for k in range(15)] tqc = transpile( qlist, backend=backend, optimization_level=opt_level, seed_transpiler=424242 ) result = backend.run(tqc, seed_simulator=4242424242, shots=1000).result() counts = result.get_counts() for count in counts: self.assertTrue(math.isclose(count["0000000000000000"], 500, rel_tol=0.1)) self.assertTrue(math.isclose(count["0111111111111111"], 500, rel_tol=0.1)) def test_parallel_dispatch_lazy_cal_loading(self): """Test adding calibration by lazy loading in parallel environment.""" class TestAddCalibration(TransformationPass): """A fake pass to test lazy pulse qobj loading in parallel environment.""" def __init__(self, target): """Instantiate with target.""" super().__init__() self.target = target def run(self, dag): """Run test pass that adds calibration of SX gate of qubit 0.""" dag.add_calibration( "sx", qubits=(0,), schedule=self.target["sx"][(0,)].calibration, # PulseQobj is parsed here ) return dag backend = FakeMumbaiV2() # This target has PulseQobj entries that provides a serialized schedule data pass_ = TestAddCalibration(backend.target) pm = PassManager(passes=[pass_]) self.assertIsNone(backend.target["sx"][(0,)]._calibration._definition) qc = QuantumCircuit(1) qc.sx(0) qc_copied = [qc for _ in range(10)] qcs_cal_added = pm.run(qc_copied) ref_cal = backend.target["sx"][(0,)].calibration for qc_test in qcs_cal_added: added_cal = qc_test.calibrations["sx"][((0,), ())] self.assertEqual(added_cal, ref_cal) @data(0, 1, 2, 3) def test_backendv2_and_basis_gates(self, opt_level): """Test transpile() with BackendV2 and basis_gates set.""" backend = FakeNairobiV2() qc = QuantumCircuit(5) qc.h(0) qc.cz(0, 1) qc.cz(0, 2) qc.cz(0, 3) qc.cz(0, 4) qc.measure_all() tqc = transpile( qc, backend=backend, basis_gates=["u", "cz"], optimization_level=opt_level, seed_transpiler=12345678942, ) op_count = set(tqc.count_ops()) self.assertEqual({"u", "cz", "measure", "barrier"}, op_count) for inst in tqc.data: if inst.operation.name not in {"u", "cz"}: continue qubits = tuple(tqc.find_bit(x).index for x in inst.qubits) self.assertIn(qubits, backend.target.qargs) @data(0, 1, 2, 3) def test_backendv2_and_coupling_map(self, opt_level): """Test transpile() with custom coupling map.""" backend = FakeNairobiV2() qc = QuantumCircuit(5) qc.h(0) qc.cz(0, 1) qc.cz(0, 2) qc.cz(0, 3) qc.cz(0, 4) qc.measure_all() cmap = CouplingMap.from_line(5, bidirectional=False) tqc = transpile( qc, backend=backend, coupling_map=cmap, optimization_level=opt_level, seed_transpiler=12345678942, ) op_count = set(tqc.count_ops()) self.assertTrue({"rz", "sx", "x", "cx", "measure", "barrier"}.issuperset(op_count)) for inst in tqc.data: if len(inst.qubits) == 2: qubit_0 = tqc.find_bit(inst.qubits[0]).index qubit_1 = tqc.find_bit(inst.qubits[1]).index self.assertEqual(qubit_1, qubit_0 + 1) def test_transpile_with_multiple_coupling_maps(self): """Test passing a different coupling map for every circuit""" backend = FakeNairobiV2() qc = QuantumCircuit(3) qc.cx(0, 2) # Add a connection between 0 and 2 so that transpile does not change # the gates cmap = CouplingMap.from_line(7) cmap.add_edge(0, 2) with self.assertRaisesRegex(TranspilerError, "Only a single input coupling"): # Initial layout needed to prevent transpiler from relabeling # qubits to avoid doing the swap transpile( [qc] * 2, backend, coupling_map=[backend.coupling_map, cmap], initial_layout=(0, 1, 2), ) @data(0, 1, 2, 3) def test_backend_and_custom_gate(self, opt_level): """Test transpile() with BackendV2, custom basis pulse gate.""" backend = FakeNairobiV2() inst_map = InstructionScheduleMap() inst_map.add("newgate", [0, 1], pulse.ScheduleBlock()) newgate = Gate("newgate", 2, []) circ = QuantumCircuit(2) circ.append(newgate, [0, 1]) tqc = transpile( circ, backend, inst_map=inst_map, basis_gates=["newgate"], optimization_level=opt_level ) self.assertEqual(len(tqc.data), 1) self.assertEqual(tqc.data[0].operation, newgate) qubits = tuple(tqc.find_bit(x).index for x in tqc.data[0].qubits) self.assertIn(qubits, backend.target.qargs) @ddt class TestTranspileMultiChipTarget(QiskitTestCase): """Test transpile() with a disjoint coupling map.""" def setUp(self): super().setUp() class FakeMultiChip(BackendV2): """Fake multi chip backend.""" def __init__(self): super().__init__() graph = rx.generators.directed_heavy_hex_graph(3) num_qubits = len(graph) * 3 rng = np.random.default_rng(seed=12345678942) rz_props = {} x_props = {} sx_props = {} measure_props = {} delay_props = {} self._target = Target("Fake multi-chip backend", num_qubits=num_qubits) for i in range(num_qubits): qarg = (i,) rz_props[qarg] = InstructionProperties(error=0.0, duration=0.0) x_props[qarg] = InstructionProperties( error=rng.uniform(1e-6, 1e-4), duration=rng.uniform(1e-8, 9e-7) ) sx_props[qarg] = InstructionProperties( error=rng.uniform(1e-6, 1e-4), duration=rng.uniform(1e-8, 9e-7) ) measure_props[qarg] = InstructionProperties( error=rng.uniform(1e-3, 1e-1), duration=rng.uniform(1e-8, 9e-7) ) delay_props[qarg] = None self._target.add_instruction(XGate(), x_props) self._target.add_instruction(SXGate(), sx_props) self._target.add_instruction(RZGate(Parameter("theta")), rz_props) self._target.add_instruction(Measure(), measure_props) self._target.add_instruction(Delay(Parameter("t")), delay_props) cz_props = {} for i in range(3): for root_edge in graph.edge_list(): offset = i * len(graph) edge = (root_edge[0] + offset, root_edge[1] + offset) cz_props[edge] = InstructionProperties( error=rng.uniform(1e-5, 5e-3), duration=rng.uniform(1e-8, 9e-7) ) self._target.add_instruction(CZGate(), cz_props) @property def target(self): return self._target @property def max_circuits(self): return None @classmethod def _default_options(cls): return Options(shots=1024) def run(self, circuit, **kwargs): raise NotImplementedError self.backend = FakeMultiChip() @data(0, 1, 2, 3) def test_basic_connected_circuit(self, opt_level): """Test basic connected circuit on disjoint backend""" qc = QuantumCircuit(5) qc.h(0) qc.cx(0, 1) qc.cx(0, 2) qc.cx(0, 3) qc.cx(0, 4) qc.measure_all() tqc = transpile(qc, self.backend, optimization_level=opt_level) for inst in tqc.data: qubits = tuple(tqc.find_bit(x).index for x in inst.qubits) op_name = inst.operation.name if op_name == "barrier": continue self.assertIn(qubits, self.backend.target[op_name]) @data(0, 1, 2, 3) def test_triple_circuit(self, opt_level): """Test a split circuit with one circuit component per chip.""" qc = QuantumCircuit(30) qc.h(0) qc.h(10) qc.h(20) qc.cx(0, 1) qc.cx(0, 2) qc.cx(0, 3) qc.cx(0, 4) qc.cx(0, 5) qc.cx(0, 6) qc.cx(0, 7) qc.cx(0, 8) qc.cx(0, 9) qc.ecr(10, 11) qc.ecr(10, 12) qc.ecr(10, 13) qc.ecr(10, 14) qc.ecr(10, 15) qc.ecr(10, 16) qc.ecr(10, 17) qc.ecr(10, 18) qc.ecr(10, 19) qc.cy(20, 21) qc.cy(20, 22) qc.cy(20, 23) qc.cy(20, 24) qc.cy(20, 25) qc.cy(20, 26) qc.cy(20, 27) qc.cy(20, 28) qc.cy(20, 29) qc.measure_all() if opt_level == 0: with self.assertRaises(TranspilerError): tqc = transpile(qc, self.backend, optimization_level=opt_level, seed_transpiler=42) return tqc = transpile(qc, self.backend, optimization_level=opt_level, seed_transpiler=42) for inst in tqc.data: qubits = tuple(tqc.find_bit(x).index for x in inst.qubits) op_name = inst.operation.name if op_name == "barrier": continue self.assertIn(qubits, self.backend.target[op_name]) def test_disjoint_control_flow(self): """Test control flow circuit on disjoint coupling map.""" qc = QuantumCircuit(6, 1) qc.h(0) qc.ecr(0, 1) qc.cx(0, 2) qc.measure(0, 0) with qc.if_test((qc.clbits[0], True)): qc.reset(0) qc.cz(1, 0) qc.h(3) qc.cz(3, 4) qc.cz(3, 5) target = self.backend.target target.add_instruction(Reset(), {(i,): None for i in range(target.num_qubits)}) target.add_instruction(IfElseOp, name="if_else") tqc = transpile(qc, target=target) edges = set(target.build_coupling_map().graph.edge_list()) def _visit_block(circuit, qubit_mapping=None): for instruction in circuit: if instruction.operation.name == "barrier": continue qargs = tuple(qubit_mapping[x] for x in instruction.qubits) self.assertTrue(target.instruction_supported(instruction.operation.name, qargs)) if isinstance(instruction.operation, ControlFlowOp): for block in instruction.operation.blocks: new_mapping = { inner: qubit_mapping[outer] for outer, inner in zip(instruction.qubits, block.qubits) } _visit_block(block, new_mapping) elif len(qargs) == 2: self.assertIn(qargs, edges) self.assertIn(instruction.operation.name, target) _visit_block( tqc, qubit_mapping={qubit: index for index, qubit in enumerate(tqc.qubits)}, ) def test_disjoint_control_flow_shared_classical(self): """Test circuit with classical data dependency between connected components.""" creg = ClassicalRegister(19) qc = QuantumCircuit(25) qc.add_register(creg) qc.h(0) for i in range(18): qc.cx(0, i + 1) for i in range(18): qc.measure(i, creg[i]) with qc.if_test((creg, 0)): qc.h(20) qc.ecr(20, 21) qc.ecr(20, 22) qc.ecr(20, 23) qc.ecr(20, 24) target = self.backend.target target.add_instruction(Reset(), {(i,): None for i in range(target.num_qubits)}) target.add_instruction(IfElseOp, name="if_else") tqc = transpile(qc, target=target) def _visit_block(circuit, qubit_mapping=None): for instruction in circuit: if instruction.operation.name == "barrier": continue qargs = tuple(qubit_mapping[x] for x in instruction.qubits) self.assertTrue(target.instruction_supported(instruction.operation.name, qargs)) if isinstance(instruction.operation, ControlFlowOp): for block in instruction.operation.blocks: new_mapping = { inner: qubit_mapping[outer] for outer, inner in zip(instruction.qubits, block.qubits) } _visit_block(block, new_mapping) _visit_block( tqc, qubit_mapping={qubit: index for index, qubit in enumerate(tqc.qubits)}, ) @slow_test @data(2, 3) def test_six_component_circuit(self, opt_level): """Test input circuit with more than 1 component per backend component.""" qc = QuantumCircuit(42) qc.h(0) qc.h(10) qc.h(20) qc.cx(0, 1) qc.cx(0, 2) qc.cx(0, 3) qc.cx(0, 4) qc.cx(0, 5) qc.cx(0, 6) qc.cx(0, 7) qc.cx(0, 8) qc.cx(0, 9) qc.ecr(10, 11) qc.ecr(10, 12) qc.ecr(10, 13) qc.ecr(10, 14) qc.ecr(10, 15) qc.ecr(10, 16) qc.ecr(10, 17) qc.ecr(10, 18) qc.ecr(10, 19) qc.cy(20, 21) qc.cy(20, 22) qc.cy(20, 23) qc.cy(20, 24) qc.cy(20, 25) qc.cy(20, 26) qc.cy(20, 27) qc.cy(20, 28) qc.cy(20, 29) qc.h(30) qc.cx(30, 31) qc.cx(30, 32) qc.cx(30, 33) qc.h(34) qc.cx(34, 35) qc.cx(34, 36) qc.cx(34, 37) qc.h(38) qc.cx(38, 39) qc.cx(39, 40) qc.cx(39, 41) qc.measure_all() tqc = transpile(qc, self.backend, optimization_level=opt_level, seed_transpiler=42) for inst in tqc.data: qubits = tuple(tqc.find_bit(x).index for x in inst.qubits) op_name = inst.operation.name if op_name == "barrier": continue self.assertIn(qubits, self.backend.target[op_name]) def test_six_component_circuit_level_1(self): """Test input circuit with more than 1 component per backend component.""" opt_level = 1 qc = QuantumCircuit(42) qc.h(0) qc.h(10) qc.h(20) qc.cx(0, 1) qc.cx(0, 2) qc.cx(0, 3) qc.cx(0, 4) qc.cx(0, 5) qc.cx(0, 6) qc.cx(0, 7) qc.cx(0, 8) qc.cx(0, 9) qc.ecr(10, 11) qc.ecr(10, 12) qc.ecr(10, 13) qc.ecr(10, 14) qc.ecr(10, 15) qc.ecr(10, 16) qc.ecr(10, 17) qc.ecr(10, 18) qc.ecr(10, 19) qc.cy(20, 21) qc.cy(20, 22) qc.cy(20, 23) qc.cy(20, 24) qc.cy(20, 25) qc.cy(20, 26) qc.cy(20, 27) qc.cy(20, 28) qc.cy(20, 29) qc.h(30) qc.cx(30, 31) qc.cx(30, 32) qc.cx(30, 33) qc.h(34) qc.cx(34, 35) qc.cx(34, 36) qc.cx(34, 37) qc.h(38) qc.cx(38, 39) qc.cx(39, 40) qc.cx(39, 41) qc.measure_all() tqc = transpile(qc, self.backend, optimization_level=opt_level, seed_transpiler=42) for inst in tqc.data: qubits = tuple(tqc.find_bit(x).index for x in inst.qubits) op_name = inst.operation.name if op_name == "barrier": continue self.assertIn(qubits, self.backend.target[op_name]) @data(0, 1, 2, 3) def test_shared_classical_between_components_condition(self, opt_level): """Test a condition sharing classical bits between components.""" creg = ClassicalRegister(19) qc = QuantumCircuit(25) qc.add_register(creg) qc.h(0) for i in range(18): qc.cx(0, i + 1) for i in range(18): qc.measure(i, creg[i]) qc.ecr(20, 21).c_if(creg, 0) tqc = transpile(qc, self.backend, optimization_level=opt_level) def _visit_block(circuit, qubit_mapping=None): for instruction in circuit: if instruction.operation.name == "barrier": continue qargs = tuple(qubit_mapping[x] for x in instruction.qubits) self.assertTrue( self.backend.target.instruction_supported(instruction.operation.name, qargs) ) if isinstance(instruction.operation, ControlFlowOp): for block in instruction.operation.blocks: new_mapping = { inner: qubit_mapping[outer] for outer, inner in zip(instruction.qubits, block.qubits) } _visit_block(block, new_mapping) _visit_block( tqc, qubit_mapping={qubit: index for index, qubit in enumerate(tqc.qubits)}, ) @data(0, 1, 2, 3) def test_shared_classical_between_components_condition_large_to_small(self, opt_level): """Test a condition sharing classical bits between components.""" creg = ClassicalRegister(2) qc = QuantumCircuit(25) qc.add_register(creg) # Component 0 qc.h(24) qc.cx(24, 23) qc.measure(24, creg[0]) qc.measure(23, creg[1]) # Component 1 qc.h(0).c_if(creg, 0) for i in range(18): qc.ecr(0, i + 1).c_if(creg, 0) tqc = transpile(qc, self.backend, optimization_level=opt_level, seed_transpiler=123456789) def _visit_block(circuit, qubit_mapping=None): for instruction in circuit: if instruction.operation.name == "barrier": continue qargs = tuple(qubit_mapping[x] for x in instruction.qubits) self.assertTrue( self.backend.target.instruction_supported(instruction.operation.name, qargs) ) if isinstance(instruction.operation, ControlFlowOp): for block in instruction.operation.blocks: new_mapping = { inner: qubit_mapping[outer] for outer, inner in zip(instruction.qubits, block.qubits) } _visit_block(block, new_mapping) _visit_block( tqc, qubit_mapping={qubit: index for index, qubit in enumerate(tqc.qubits)}, ) # Check that virtual qubits that interact with each other via quantum links are placed into # the same component of the coupling map. initial_layout = tqc.layout.initial_layout coupling_map = self.backend.target.build_coupling_map() components = [ connected_qubits(initial_layout[qc.qubits[23]], coupling_map), connected_qubits(initial_layout[qc.qubits[0]], coupling_map), ] self.assertLessEqual({initial_layout[qc.qubits[i]] for i in [23, 24]}, components[0]) self.assertLessEqual({initial_layout[qc.qubits[i]] for i in range(19)}, components[1]) # Check clbits are in order. # Traverse the output dag over the sole clbit, checking that the qubits of the ops # go in order between the components. This is a sanity check to ensure that routing # doesn't reorder a classical data dependency between components. Inside a component # we have the dag ordering so nothing should be out of order within a component. tqc_dag = circuit_to_dag(tqc) qubit_map = {qubit: index for index, qubit in enumerate(tqc_dag.qubits)} input_node = tqc_dag.input_map[tqc_dag.clbits[0]] first_meas_node = tqc_dag._multi_graph.find_successors_by_edge( input_node._node_id, lambda edge_data: isinstance(edge_data, Clbit) )[0] # The first node should be a measurement self.assertIsInstance(first_meas_node.op, Measure) # This should be in the first component self.assertIn(qubit_map[first_meas_node.qargs[0]], components[0]) op_node = tqc_dag._multi_graph.find_successors_by_edge( first_meas_node._node_id, lambda edge_data: isinstance(edge_data, Clbit) )[0] while isinstance(op_node, DAGOpNode): self.assertIn(qubit_map[op_node.qargs[0]], components[1]) op_node = tqc_dag._multi_graph.find_successors_by_edge( op_node._node_id, lambda edge_data: isinstance(edge_data, Clbit) )[0] @data(1, 2, 3) def test_shared_classical_between_components_condition_large_to_small_reverse_index( self, opt_level ): """Test a condition sharing classical bits between components.""" creg = ClassicalRegister(2) qc = QuantumCircuit(25) qc.add_register(creg) # Component 0 qc.h(0) qc.cx(0, 1) qc.measure(0, creg[0]) qc.measure(1, creg[1]) # Component 1 qc.h(24).c_if(creg, 0) for i in range(23, 5, -1): qc.ecr(24, i).c_if(creg, 0) tqc = transpile(qc, self.backend, optimization_level=opt_level, seed_transpiler=2023) def _visit_block(circuit, qubit_mapping=None): for instruction in circuit: if instruction.operation.name == "barrier": continue qargs = tuple(qubit_mapping[x] for x in instruction.qubits) self.assertTrue( self.backend.target.instruction_supported(instruction.operation.name, qargs) ) if isinstance(instruction.operation, ControlFlowOp): for block in instruction.operation.blocks: new_mapping = { inner: qubit_mapping[outer] for outer, inner in zip(instruction.qubits, block.qubits) } _visit_block(block, new_mapping) _visit_block( tqc, qubit_mapping={qubit: index for index, qubit in enumerate(tqc.qubits)}, ) # Check that virtual qubits that interact with each other via quantum links are placed into # the same component of the coupling map. initial_layout = tqc.layout.initial_layout coupling_map = self.backend.target.build_coupling_map() components = [ connected_qubits(initial_layout[qc.qubits[0]], coupling_map), connected_qubits(initial_layout[qc.qubits[6]], coupling_map), ] self.assertLessEqual({initial_layout[qc.qubits[i]] for i in range(2)}, components[0]) self.assertLessEqual({initial_layout[qc.qubits[i]] for i in range(6, 25)}, components[1]) # Check clbits are in order. # Traverse the output dag over the sole clbit, checking that the qubits of the ops # go in order between the components. This is a sanity check to ensure that routing # doesn't reorder a classical data dependency between components. Inside a component # we have the dag ordering so nothing should be out of order within a component. tqc_dag = circuit_to_dag(tqc) qubit_map = {qubit: index for index, qubit in enumerate(tqc_dag.qubits)} input_node = tqc_dag.input_map[tqc_dag.clbits[0]] first_meas_node = tqc_dag._multi_graph.find_successors_by_edge( input_node._node_id, lambda edge_data: isinstance(edge_data, Clbit) )[0] # The first node should be a measurement self.assertIsInstance(first_meas_node.op, Measure) # This shoulde be in the first ocmponent self.assertIn(qubit_map[first_meas_node.qargs[0]], components[0]) op_node = tqc_dag._multi_graph.find_successors_by_edge( first_meas_node._node_id, lambda edge_data: isinstance(edge_data, Clbit) )[0] while isinstance(op_node, DAGOpNode): self.assertIn(qubit_map[op_node.qargs[0]], components[1]) op_node = tqc_dag._multi_graph.find_successors_by_edge( op_node._node_id, lambda edge_data: isinstance(edge_data, Clbit) )[0] @data(1, 2, 3) def test_chained_data_dependency(self, opt_level): """Test 3 component circuit with shared clbits between each component.""" creg = ClassicalRegister(1) qc = QuantumCircuit(30) qc.add_register(creg) # Component 0 qc.h(0) for i in range(9): qc.cx(0, i + 1) measure_op = Measure() qc.append(measure_op, [9], [creg[0]]) # Component 1 qc.h(10).c_if(creg, 0) for i in range(11, 20): qc.ecr(10, i).c_if(creg, 0) measure_op = Measure() qc.append(measure_op, [19], [creg[0]]) # Component 2 qc.h(20).c_if(creg, 0) for i in range(21, 30): qc.cz(20, i).c_if(creg, 0) measure_op = Measure() qc.append(measure_op, [29], [creg[0]]) tqc = transpile(qc, self.backend, optimization_level=opt_level, seed_transpiler=2023) def _visit_block(circuit, qubit_mapping=None): for instruction in circuit: if instruction.operation.name == "barrier": continue qargs = tuple(qubit_mapping[x] for x in instruction.qubits) self.assertTrue( self.backend.target.instruction_supported(instruction.operation.name, qargs) ) if isinstance(instruction.operation, ControlFlowOp): for block in instruction.operation.blocks: new_mapping = { inner: qubit_mapping[outer] for outer, inner in zip(instruction.qubits, block.qubits) } _visit_block(block, new_mapping) _visit_block( tqc, qubit_mapping={qubit: index for index, qubit in enumerate(tqc.qubits)}, ) # Check that virtual qubits that interact with each other via quantum links are placed into # the same component of the coupling map. initial_layout = tqc.layout.initial_layout coupling_map = self.backend.target.build_coupling_map() components = [ connected_qubits(initial_layout[qc.qubits[0]], coupling_map), connected_qubits(initial_layout[qc.qubits[10]], coupling_map), connected_qubits(initial_layout[qc.qubits[20]], coupling_map), ] self.assertLessEqual({initial_layout[qc.qubits[i]] for i in range(10)}, components[0]) self.assertLessEqual({initial_layout[qc.qubits[i]] for i in range(10, 20)}, components[1]) self.assertLessEqual({initial_layout[qc.qubits[i]] for i in range(20, 30)}, components[2]) # Check clbits are in order. # Traverse the output dag over the sole clbit, checking that the qubits of the ops # go in order between the components. This is a sanity check to ensure that routing # doesn't reorder a classical data dependency between components. Inside a component # we have the dag ordering so nothing should be out of order within a component. tqc_dag = circuit_to_dag(tqc) qubit_map = {qubit: index for index, qubit in enumerate(tqc_dag.qubits)} input_node = tqc_dag.input_map[tqc_dag.clbits[0]] first_meas_node = tqc_dag._multi_graph.find_successors_by_edge( input_node._node_id, lambda edge_data: isinstance(edge_data, Clbit) )[0] self.assertIsInstance(first_meas_node.op, Measure) self.assertIn(qubit_map[first_meas_node.qargs[0]], components[0]) op_node = tqc_dag._multi_graph.find_successors_by_edge( first_meas_node._node_id, lambda edge_data: isinstance(edge_data, Clbit) )[0] while not isinstance(op_node.op, Measure): self.assertIn(qubit_map[op_node.qargs[0]], components[1]) op_node = tqc_dag._multi_graph.find_successors_by_edge( op_node._node_id, lambda edge_data: isinstance(edge_data, Clbit) )[0] self.assertIn(qubit_map[op_node.qargs[0]], components[1]) op_node = tqc_dag._multi_graph.find_successors_by_edge( op_node._node_id, lambda edge_data: isinstance(edge_data, Clbit) )[0] while not isinstance(op_node.op, Measure): self.assertIn(qubit_map[op_node.qargs[0]], components[2]) op_node = tqc_dag._multi_graph.find_successors_by_edge( op_node._node_id, lambda edge_data: isinstance(edge_data, Clbit) )[0] self.assertIn(qubit_map[op_node.qargs[0]], components[2]) @data("sabre", "stochastic", "basic", "lookahead") def test_basic_connected_circuit_dense_layout(self, routing_method): """Test basic connected circuit on disjoint backend""" qc = QuantumCircuit(5) qc.h(0) qc.cx(0, 1) qc.cx(0, 2) qc.cx(0, 3) qc.cx(0, 4) qc.measure_all() tqc = transpile( qc, self.backend, layout_method="dense", routing_method=routing_method, seed_transpiler=42, ) for inst in tqc.data: qubits = tuple(tqc.find_bit(x).index for x in inst.qubits) op_name = inst.operation.name if op_name == "barrier": continue self.assertIn(qubits, self.backend.target[op_name]) # Lookahead swap skipped for performance @data("sabre", "stochastic", "basic") def test_triple_circuit_dense_layout(self, routing_method): """Test a split circuit with one circuit component per chip.""" qc = QuantumCircuit(30) qc.h(0) qc.h(10) qc.h(20) qc.cx(0, 1) qc.cx(0, 2) qc.cx(0, 3) qc.cx(0, 4) qc.cx(0, 5) qc.cx(0, 6) qc.cx(0, 7) qc.cx(0, 8) qc.cx(0, 9) qc.ecr(10, 11) qc.ecr(10, 12) qc.ecr(10, 13) qc.ecr(10, 14) qc.ecr(10, 15) qc.ecr(10, 16) qc.ecr(10, 17) qc.ecr(10, 18) qc.ecr(10, 19) qc.cy(20, 21) qc.cy(20, 22) qc.cy(20, 23) qc.cy(20, 24) qc.cy(20, 25) qc.cy(20, 26) qc.cy(20, 27) qc.cy(20, 28) qc.cy(20, 29) qc.measure_all() tqc = transpile( qc, self.backend, layout_method="dense", routing_method=routing_method, seed_transpiler=42, ) for inst in tqc.data: qubits = tuple(tqc.find_bit(x).index for x in inst.qubits) op_name = inst.operation.name if op_name == "barrier": continue self.assertIn(qubits, self.backend.target[op_name]) @data("sabre", "stochastic", "basic", "lookahead") def test_triple_circuit_invalid_layout(self, routing_method): """Test a split circuit with one circuit component per chip.""" qc = QuantumCircuit(30) qc.h(0) qc.h(10) qc.h(20) qc.cx(0, 1) qc.cx(0, 2) qc.cx(0, 3) qc.cx(0, 4) qc.cx(0, 5) qc.cx(0, 6) qc.cx(0, 7) qc.cx(0, 8) qc.cx(0, 9) qc.ecr(10, 11) qc.ecr(10, 12) qc.ecr(10, 13) qc.ecr(10, 14) qc.ecr(10, 15) qc.ecr(10, 16) qc.ecr(10, 17) qc.ecr(10, 18) qc.ecr(10, 19) qc.cy(20, 21) qc.cy(20, 22) qc.cy(20, 23) qc.cy(20, 24) qc.cy(20, 25) qc.cy(20, 26) qc.cy(20, 27) qc.cy(20, 28) qc.cy(20, 29) qc.measure_all() with self.assertRaises(TranspilerError): transpile( qc, self.backend, layout_method="trivial", routing_method=routing_method, seed_transpiler=42, ) # Lookahead swap skipped for performance reasons @data("sabre", "stochastic", "basic") def test_six_component_circuit_dense_layout(self, routing_method): """Test input circuit with more than 1 component per backend component.""" qc = QuantumCircuit(42) qc.h(0) qc.h(10) qc.h(20) qc.cx(0, 1) qc.cx(0, 2) qc.cx(0, 3) qc.cx(0, 4) qc.cx(0, 5) qc.cx(0, 6) qc.cx(0, 7) qc.cx(0, 8) qc.cx(0, 9) qc.ecr(10, 11) qc.ecr(10, 12) qc.ecr(10, 13) qc.ecr(10, 14) qc.ecr(10, 15) qc.ecr(10, 16) qc.ecr(10, 17) qc.ecr(10, 18) qc.ecr(10, 19) qc.cy(20, 21) qc.cy(20, 22) qc.cy(20, 23) qc.cy(20, 24) qc.cy(20, 25) qc.cy(20, 26) qc.cy(20, 27) qc.cy(20, 28) qc.cy(20, 29) qc.h(30) qc.cx(30, 31) qc.cx(30, 32) qc.cx(30, 33) qc.h(34) qc.cx(34, 35) qc.cx(34, 36) qc.cx(34, 37) qc.h(38) qc.cx(38, 39) qc.cx(39, 40) qc.cx(39, 41) qc.measure_all() tqc = transpile( qc, self.backend, layout_method="dense", routing_method=routing_method, seed_transpiler=42, ) for inst in tqc.data: qubits = tuple(tqc.find_bit(x).index for x in inst.qubits) op_name = inst.operation.name if op_name == "barrier": continue self.assertIn(qubits, self.backend.target[op_name]) @data(0, 1, 2, 3) def test_transpile_target_with_qubits_without_ops(self, opt_level): """Test qubits without operations aren't ever used.""" target = Target(num_qubits=5) target.add_instruction(XGate(), {(i,): InstructionProperties(error=0.5) for i in range(3)}) target.add_instruction(HGate(), {(i,): InstructionProperties(error=0.5) for i in range(3)}) target.add_instruction( CXGate(), {edge: InstructionProperties(error=0.5) for edge in [(0, 1), (1, 2), (2, 0)]} ) qc = QuantumCircuit(3) qc.x(0) qc.cx(0, 1) qc.cx(0, 2) tqc = transpile(qc, target=target, optimization_level=opt_level) invalid_qubits = {3, 4} self.assertEqual(tqc.num_qubits, 5) for inst in tqc.data: for bit in inst.qubits: self.assertNotIn(tqc.find_bit(bit).index, invalid_qubits) @data(0, 1, 2, 3) def test_transpile_target_with_qubits_without_ops_with_routing(self, opt_level): """Test qubits without operations aren't ever used.""" target = Target(num_qubits=5) target.add_instruction(XGate(), {(i,): InstructionProperties(error=0.5) for i in range(4)}) target.add_instruction(HGate(), {(i,): InstructionProperties(error=0.5) for i in range(4)}) target.add_instruction( CXGate(), {edge: InstructionProperties(error=0.5) for edge in [(0, 1), (1, 2), (2, 0), (2, 3)]}, ) qc = QuantumCircuit(4) qc.x(0) qc.cx(0, 1) qc.cx(0, 2) qc.cx(1, 3) qc.cx(0, 3) tqc = transpile(qc, target=target, optimization_level=opt_level) invalid_qubits = { 4, } self.assertEqual(tqc.num_qubits, 5) for inst in tqc.data: for bit in inst.qubits: self.assertNotIn(tqc.find_bit(bit).index, invalid_qubits) @data(0, 1, 2, 3) def test_transpile_target_with_qubits_without_ops_circuit_too_large(self, opt_level): """Test qubits without operations aren't ever used and error if circuit needs them.""" target = Target(num_qubits=5) target.add_instruction(XGate(), {(i,): InstructionProperties(error=0.5) for i in range(3)}) target.add_instruction(HGate(), {(i,): InstructionProperties(error=0.5) for i in range(3)}) target.add_instruction( CXGate(), {edge: InstructionProperties(error=0.5) for edge in [(0, 1), (1, 2), (2, 0)]} ) qc = QuantumCircuit(4) qc.x(0) qc.cx(0, 1) qc.cx(0, 2) qc.cx(0, 3) with self.assertRaises(TranspilerError): transpile(qc, target=target, optimization_level=opt_level) @data(0, 1, 2, 3) def test_transpile_target_with_qubits_without_ops_circuit_too_large_disconnected( self, opt_level ): """Test qubits without operations aren't ever used if a disconnected circuit needs them.""" target = Target(num_qubits=5) target.add_instruction(XGate(), {(i,): InstructionProperties(error=0.5) for i in range(3)}) target.add_instruction(HGate(), {(i,): InstructionProperties(error=0.5) for i in range(3)}) target.add_instruction( CXGate(), {edge: InstructionProperties(error=0.5) for edge in [(0, 1), (1, 2), (2, 0)]} ) qc = QuantumCircuit(5) qc.x(0) qc.x(1) qc.x(3) qc.x(4) with self.assertRaises(TranspilerError): transpile(qc, target=target, optimization_level=opt_level) @data(0, 1, 2, 3) def test_transpile_does_not_affect_backend_coupling(self, opt_level): """Test that transpiliation of a circuit does not mutate the `CouplingMap` stored by a V2 backend. Regression test of gh-9997.""" if opt_level == 3: raise unittest.SkipTest("unitary resynthesis fails due to gh-10004") qc = QuantumCircuit(127) for i in range(1, 127): qc.ecr(0, i) backend = FakeSherbrooke() original_map = copy.deepcopy(backend.coupling_map) transpile(qc, backend, optimization_level=opt_level) self.assertEqual(original_map, backend.coupling_map) @combine( optimization_level=[0, 1, 2, 3], scheduling_method=["asap", "alap"], ) def test_transpile_target_with_qubits_without_delays_with_scheduling( self, optimization_level, scheduling_method ): """Test qubits without operations aren't ever used.""" no_delay_qubits = [1, 3, 4] target = Target(num_qubits=5, dt=1) target.add_instruction( XGate(), {(i,): InstructionProperties(duration=160) for i in range(4)} ) target.add_instruction( HGate(), {(i,): InstructionProperties(duration=160) for i in range(4)} ) target.add_instruction( CXGate(), { edge: InstructionProperties(duration=800) for edge in [(0, 1), (1, 2), (2, 0), (2, 3)] }, ) target.add_instruction( Delay(Parameter("t")), {(i,): None for i in range(4) if i not in no_delay_qubits} ) qc = QuantumCircuit(4) qc.x(0) qc.cx(0, 1) qc.cx(0, 2) qc.cx(1, 3) qc.cx(0, 3) tqc = transpile( qc, target=target, optimization_level=optimization_level, scheduling_method=scheduling_method, ) invalid_qubits = { 4, } self.assertEqual(tqc.num_qubits, 5) for inst in tqc.data: for bit in inst.qubits: self.assertNotIn(tqc.find_bit(bit).index, invalid_qubits) if isinstance(inst.operation, Delay): self.assertNotIn(tqc.find_bit(bit).index, no_delay_qubits)
https://github.com/swe-train/qiskit__qiskit
swe-train
# 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. """Test for the converter dag dependency to circuit and circuit to dag dependency.""" import unittest from qiskit.converters.dagdependency_to_circuit import dagdependency_to_circuit from qiskit.converters.circuit_to_dagdependency import circuit_to_dagdependency from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.test import QiskitTestCase class TestCircuitToDagCanonical(QiskitTestCase): """Test QuantumCircuit to DAGDependency.""" def test_circuit_and_dag_canonical(self): """Check convert to dag dependency and back""" qr = QuantumRegister(3) cr = ClassicalRegister(3) circuit_in = QuantumCircuit(qr, cr) circuit_in.h(qr[0]) circuit_in.h(qr[1]) circuit_in.measure(qr[0], cr[0]) circuit_in.measure(qr[1], cr[1]) circuit_in.x(qr[0]).c_if(cr, 0x3) circuit_in.measure(qr[0], cr[0]) circuit_in.measure(qr[1], cr[1]) circuit_in.measure(qr[2], cr[2]) dag_dependency = circuit_to_dagdependency(circuit_in) circuit_out = dagdependency_to_circuit(dag_dependency) self.assertEqual(circuit_out, circuit_in) def test_circuit_and_dag_canonical2(self): """Check convert to dag dependency and back also when the option ``create_preds_and_succs`` is False.""" qr = QuantumRegister(3) cr = ClassicalRegister(3) circuit_in = QuantumCircuit(qr, cr) circuit_in.h(qr[0]) circuit_in.h(qr[1]) circuit_in.measure(qr[0], cr[0]) circuit_in.measure(qr[1], cr[1]) circuit_in.x(qr[0]).c_if(cr, 0x3) circuit_in.measure(qr[0], cr[0]) circuit_in.measure(qr[1], cr[1]) circuit_in.measure(qr[2], cr[2]) dag_dependency = circuit_to_dagdependency(circuit_in, create_preds_and_succs=False) circuit_out = dagdependency_to_circuit(dag_dependency) self.assertEqual(circuit_out, circuit_in) def test_calibrations(self): """Test that calibrations are properly copied over.""" circuit_in = QuantumCircuit(1) circuit_in.add_calibration("h", [0], None) self.assertEqual(len(circuit_in.calibrations), 1) dag_dependency = circuit_to_dagdependency(circuit_in) self.assertEqual(len(dag_dependency.calibrations), 1) circuit_out = dagdependency_to_circuit(dag_dependency) self.assertEqual(len(circuit_out.calibrations), 1) def test_metadata(self): """Test circuit metadata is preservered through conversion.""" meta_dict = {"experiment_id": "1234", "execution_number": 4} qr = QuantumRegister(2) circuit_in = QuantumCircuit(qr, metadata=meta_dict) circuit_in.h(qr[0]) circuit_in.cx(qr[0], qr[1]) circuit_in.measure_all() dag_dependency = circuit_to_dagdependency(circuit_in) self.assertEqual(dag_dependency.metadata, meta_dict) circuit_out = dagdependency_to_circuit(dag_dependency) self.assertEqual(circuit_out.metadata, meta_dict) if __name__ == "__main__": unittest.main(verbosity=2)
https://github.com/swe-train/qiskit__qiskit
swe-train
# 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. """Test for the converter dag dependency to circuit and circuit to dag dependency V2.""" import unittest from qiskit.converters.dagdependency_to_circuit import dagdependency_to_circuit from qiskit.converters.circuit_to_dagdependency_v2 import _circuit_to_dagdependency_v2 from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from test import QiskitTestCase # pylint: disable=wrong-import-order class TestCircuitToDAGDependencyV2(QiskitTestCase): """Test QuantumCircuit to DAGDependencyV2.""" def test_circuit_and_dag_canonical(self): """Check convert to dag dependency and back""" qr = QuantumRegister(3) cr = ClassicalRegister(3) circuit_in = QuantumCircuit(qr, cr) circuit_in.h(qr[0]) circuit_in.h(qr[1]) circuit_in.measure(qr[0], cr[0]) circuit_in.measure(qr[1], cr[1]) circuit_in.x(qr[0]).c_if(cr, 0x3) circuit_in.measure(qr[0], cr[0]) circuit_in.measure(qr[1], cr[1]) circuit_in.measure(qr[2], cr[2]) dag_dependency = _circuit_to_dagdependency_v2(circuit_in) circuit_out = dagdependency_to_circuit(dag_dependency) self.assertEqual(circuit_out, circuit_in) def test_calibrations(self): """Test that calibrations are properly copied over.""" circuit_in = QuantumCircuit(1) circuit_in.add_calibration("h", [0], None) self.assertEqual(len(circuit_in.calibrations), 1) dag_dependency = _circuit_to_dagdependency_v2(circuit_in) self.assertEqual(len(dag_dependency.calibrations), 1) circuit_out = dagdependency_to_circuit(dag_dependency) self.assertEqual(len(circuit_out.calibrations), 1) def test_metadata(self): """Test circuit metadata is preservered through conversion.""" meta_dict = {"experiment_id": "1234", "execution_number": 4} qr = QuantumRegister(2) circuit_in = QuantumCircuit(qr, metadata=meta_dict) circuit_in.h(qr[0]) circuit_in.cx(qr[0], qr[1]) circuit_in.measure_all() dag_dependency = _circuit_to_dagdependency_v2(circuit_in) self.assertEqual(dag_dependency.metadata, meta_dict) circuit_out = dagdependency_to_circuit(dag_dependency) self.assertEqual(circuit_out.metadata, meta_dict) if __name__ == "__main__": unittest.main(verbosity=2)
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for the converters.""" import math import numpy as np from qiskit import QuantumRegister, QuantumCircuit from qiskit.circuit import Gate, Qubit from qiskit.quantum_info import Operator from qiskit.test import QiskitTestCase from qiskit.exceptions import QiskitError class TestCircuitToGate(QiskitTestCase): """Test QuantumCircuit to Gate""" def test_simple_circuit(self): """test simple circuit""" qr1 = QuantumRegister(4, "qr1") qr2 = QuantumRegister(3, "qr2") qr3 = QuantumRegister(3, "qr3") circ = QuantumCircuit(qr1, qr2, qr3) circ.cx(qr1[1], qr2[2]) gate = circ.to_gate() q = QuantumRegister(10, "q") self.assertIsInstance(gate, Gate) self.assertEqual(gate.definition[0].qubits, (q[1], q[6])) def test_circuit_with_registerless_bits(self): """Test a circuit with registerless bits can be converted to a gate.""" qr1 = QuantumRegister(2) qubits = [Qubit(), Qubit(), Qubit()] qr2 = QuantumRegister(3) circ = QuantumCircuit(qr1, qubits, qr2) circ.cx(3, 5) gate = circ.to_gate() self.assertIsInstance(gate, Gate) self.assertEqual(gate.num_qubits, len(qr1) + len(qubits) + len(qr2)) gate_definition = gate.definition cx = gate_definition.data[0] self.assertEqual(cx.qubits, (gate_definition.qubits[3], gate_definition.qubits[5])) self.assertEqual(cx.clbits, ()) def test_circuit_with_overlapping_registers(self): """Test that the conversion works when the given circuit has bits that are contained in more than one register.""" qubits = [Qubit() for _ in [None] * 10] qr1 = QuantumRegister(bits=qubits[:6]) qr2 = QuantumRegister(bits=qubits[4:]) circ = QuantumCircuit(qubits, qr1, qr2) circ.cx(3, 5) gate = circ.to_gate() self.assertIsInstance(gate, Gate) self.assertEqual(gate.num_qubits, len(qubits)) gate_definition = gate.definition cx = gate_definition.data[0] self.assertEqual(cx.qubits, (gate_definition.qubits[3], gate_definition.qubits[5])) self.assertEqual(cx.clbits, ()) def test_raises(self): """test circuit which can't be converted raises""" circ1 = QuantumCircuit(3) circ1.x(0) circ1.cx(0, 1) circ1.barrier() circ2 = QuantumCircuit(1, 1) circ2.measure(0, 0) circ3 = QuantumCircuit(1) circ3.x(0) circ3.reset(0) with self.assertRaises(QiskitError): # TODO: accept barrier circ1.to_gate() with self.assertRaises(QiskitError): # measure and reset are not valid circ2.to_gate() def test_generated_gate_inverse(self): """Test inverse of generated gate works.""" qr1 = QuantumRegister(2, "qr1") circ = QuantumCircuit(qr1) circ.cx(qr1[1], qr1[0]) gate = circ.to_gate() out_gate = gate.inverse() self.assertIsInstance(out_gate, Gate) def test_to_gate_label(self): """Test label setting.""" qr1 = QuantumRegister(2, "qr1") circ = QuantumCircuit(qr1, name="a circuit name") circ.cx(qr1[1], qr1[0]) gate = circ.to_gate(label="a label") self.assertEqual(gate.label, "a label") def test_zero_operands(self): """Test that a gate can be created, even if it has zero operands.""" base = QuantumCircuit(global_phase=math.pi) gate = base.to_gate() self.assertEqual(gate.num_qubits, 0) self.assertEqual(gate.num_clbits, 0) self.assertEqual(gate.definition, base) compound = QuantumCircuit(1) compound.append(gate, [], []) np.testing.assert_allclose(-np.eye(2), Operator(compound), atol=1e-16)
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for the converters.""" import math import unittest import numpy as np from qiskit.converters import circuit_to_instruction from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.circuit import Qubit, Clbit, Instruction from qiskit.circuit import Parameter from qiskit.quantum_info import Operator from qiskit.test import QiskitTestCase from qiskit.exceptions import QiskitError class TestCircuitToInstruction(QiskitTestCase): """Test Circuit to Instruction.""" def test_flatten_circuit_registers(self): """Check correct flattening""" qr1 = QuantumRegister(4, "qr1") qr2 = QuantumRegister(3, "qr2") qr3 = QuantumRegister(3, "qr3") cr1 = ClassicalRegister(4, "cr1") cr2 = ClassicalRegister(1, "cr2") circ = QuantumCircuit(qr1, qr2, qr3, cr1, cr2) circ.cx(qr1[1], qr2[2]) circ.measure(qr3[0], cr2[0]) inst = circuit_to_instruction(circ) q = QuantumRegister(10, "q") c = ClassicalRegister(5, "c") self.assertEqual(inst.definition[0].qubits, (q[1], q[6])) self.assertEqual(inst.definition[1].qubits, (q[7],)) self.assertEqual(inst.definition[1].clbits, (c[4],)) def test_flatten_registers_of_circuit_single_bit_cond(self): """Check correct mapping of registers gates conditioned on single classical bits.""" qr1 = QuantumRegister(2, "qr1") qr2 = QuantumRegister(3, "qr2") cr1 = ClassicalRegister(3, "cr1") cr2 = ClassicalRegister(3, "cr2") circ = QuantumCircuit(qr1, qr2, cr1, cr2) circ.h(qr1[0]).c_if(cr1[1], True) circ.h(qr2[1]).c_if(cr2[0], False) circ.cx(qr1[1], qr2[2]).c_if(cr2[2], True) circ.measure(qr2[2], cr2[0]) inst = circuit_to_instruction(circ) q = QuantumRegister(5, "q") c = ClassicalRegister(6, "c") self.assertEqual(inst.definition[0].qubits, (q[0],)) self.assertEqual(inst.definition[1].qubits, (q[3],)) self.assertEqual(inst.definition[2].qubits, (q[1], q[4])) self.assertEqual(inst.definition[0].operation.condition, (c[1], True)) self.assertEqual(inst.definition[1].operation.condition, (c[3], False)) self.assertEqual(inst.definition[2].operation.condition, (c[5], True)) def test_flatten_circuit_registerless(self): """Test that the conversion works when the given circuit has bits that are not contained in any register.""" qr1 = QuantumRegister(2) qubits = [Qubit(), Qubit(), Qubit()] qr2 = QuantumRegister(3) cr1 = ClassicalRegister(2) clbits = [Clbit(), Clbit(), Clbit()] cr2 = ClassicalRegister(3) circ = QuantumCircuit(qr1, qubits, qr2, cr1, clbits, cr2) circ.cx(3, 5) circ.measure(4, 4) inst = circuit_to_instruction(circ) self.assertEqual(inst.num_qubits, len(qr1) + len(qubits) + len(qr2)) self.assertEqual(inst.num_clbits, len(cr1) + len(clbits) + len(cr2)) inst_definition = inst.definition cx = inst_definition.data[0] measure = inst_definition.data[1] self.assertEqual(cx.qubits, (inst_definition.qubits[3], inst_definition.qubits[5])) self.assertEqual(cx.clbits, ()) self.assertEqual(measure.qubits, (inst_definition.qubits[4],)) self.assertEqual(measure.clbits, (inst_definition.clbits[4],)) def test_flatten_circuit_overlapping_registers(self): """Test that the conversion works when the given circuit has bits that are contained in more than one register.""" qubits = [Qubit() for _ in [None] * 10] qr1 = QuantumRegister(bits=qubits[:6]) qr2 = QuantumRegister(bits=qubits[4:]) clbits = [Clbit() for _ in [None] * 10] cr1 = ClassicalRegister(bits=clbits[:6]) cr2 = ClassicalRegister(bits=clbits[4:]) circ = QuantumCircuit(qubits, clbits, qr1, qr2, cr1, cr2) circ.cx(3, 5) circ.measure(4, 4) inst = circuit_to_instruction(circ) self.assertEqual(inst.num_qubits, len(qubits)) self.assertEqual(inst.num_clbits, len(clbits)) inst_definition = inst.definition cx = inst_definition.data[0] measure = inst_definition.data[1] self.assertEqual(cx.qubits, (inst_definition.qubits[3], inst_definition.qubits[5])) self.assertEqual(cx.clbits, ()) self.assertEqual(measure.qubits, (inst_definition.qubits[4],)) self.assertEqual(measure.clbits, (inst_definition.clbits[4],)) def test_flatten_parameters(self): """Verify parameters from circuit are moved to instruction.params""" qr = QuantumRegister(3, "qr") qc = QuantumCircuit(qr) theta = Parameter("theta") phi = Parameter("phi") sum_ = theta + phi qc.rz(theta, qr[0]) qc.rz(phi, qr[1]) qc.u(theta, phi, 0, qr[2]) qc.rz(sum_, qr[0]) inst = circuit_to_instruction(qc) self.assertEqual(inst.params, [phi, theta]) self.assertEqual(inst.definition[0].operation.params, [theta]) self.assertEqual(inst.definition[1].operation.params, [phi]) self.assertEqual(inst.definition[2].operation.params, [theta, phi, 0]) self.assertEqual(str(inst.definition[3].operation.params[0]), "phi + theta") def test_underspecified_parameter_map_raises(self): """Verify we raise if not all circuit parameters are present in parameter_map.""" qr = QuantumRegister(3, "qr") qc = QuantumCircuit(qr) theta = Parameter("theta") phi = Parameter("phi") sum_ = theta + phi gamma = Parameter("gamma") qc.rz(theta, qr[0]) qc.rz(phi, qr[1]) qc.u(theta, phi, 0, qr[2]) qc.rz(sum_, qr[0]) self.assertRaises(QiskitError, circuit_to_instruction, qc, {theta: gamma}) # Raise if provided more parameters than present in the circuit delta = Parameter("delta") self.assertRaises( QiskitError, circuit_to_instruction, qc, {theta: gamma, phi: phi, delta: delta} ) def test_parameter_map(self): """Verify alternate parameter specification""" qr = QuantumRegister(3, "qr") qc = QuantumCircuit(qr) theta = Parameter("theta") phi = Parameter("phi") sum_ = theta + phi gamma = Parameter("gamma") qc.rz(theta, qr[0]) qc.rz(phi, qr[1]) qc.u(theta, phi, 0, qr[2]) qc.rz(sum_, qr[0]) inst = circuit_to_instruction(qc, {theta: gamma, phi: phi}) self.assertEqual(inst.params, [gamma, phi]) self.assertEqual(inst.definition[0].operation.params, [gamma]) self.assertEqual(inst.definition[1].operation.params, [phi]) self.assertEqual(inst.definition[2].operation.params, [gamma, phi, 0]) self.assertEqual(str(inst.definition[3].operation.params[0]), "gamma + phi") def test_registerless_classical_bits(self): """Test that conditions on registerless classical bits can be handled during the conversion. Regression test of gh-7394.""" expected = QuantumCircuit([Qubit(), Clbit()]) expected.h(0).c_if(expected.clbits[0], 0) test = circuit_to_instruction(expected) self.assertIsInstance(test, Instruction) self.assertIsInstance(test.definition, QuantumCircuit) self.assertEqual(len(test.definition.data), 1) test_instruction = test.definition.data[0] expected_instruction = expected.data[0] self.assertIs(type(test_instruction.operation), type(expected_instruction.operation)) self.assertEqual(test_instruction.operation.condition, (test.definition.clbits[0], 0)) def test_zero_operands(self): """Test that an instruction can be created, even if it has zero operands.""" base = QuantumCircuit(global_phase=math.pi) instruction = base.to_instruction() self.assertEqual(instruction.num_qubits, 0) self.assertEqual(instruction.num_clbits, 0) self.assertEqual(instruction.definition, base) compound = QuantumCircuit(1) compound.append(instruction, [], []) np.testing.assert_allclose(-np.eye(2), Operator(compound), atol=1e-16) if __name__ == "__main__": unittest.main(verbosity=2)
https://github.com/swe-train/qiskit__qiskit
swe-train
# 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. """Test for the converter dag dependency to dag circuit and dag circuit to dag dependency.""" import unittest from qiskit.converters.circuit_to_dag import circuit_to_dag from qiskit.converters.dag_to_dagdependency import dag_to_dagdependency from qiskit.converters.dagdependency_to_dag import dagdependency_to_dag from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.test import QiskitTestCase class TestCircuitToDagDependency(QiskitTestCase): """Test DAGCircuit to DAGDependency.""" def test_circuit_and_dag_dependency(self): """Check convert to dag dependency and back""" qr = QuantumRegister(3) cr = ClassicalRegister(3) circuit_in = QuantumCircuit(qr, cr) circuit_in.h(qr[0]) circuit_in.h(qr[1]) circuit_in.measure(qr[0], cr[0]) circuit_in.measure(qr[1], cr[1]) circuit_in.x(qr[0]).c_if(cr, 0x3) circuit_in.measure(qr[0], cr[0]) circuit_in.measure(qr[1], cr[1]) circuit_in.measure(qr[2], cr[2]) dag_in = circuit_to_dag(circuit_in) dag_dependency = dag_to_dagdependency(dag_in) dag_out = dagdependency_to_dag(dag_dependency) self.assertEqual(dag_out, dag_in) def test_circuit_and_dag_dependency2(self): """Check convert to dag dependency and back also when the option ``create_preds_and_succs`` is False.""" qr = QuantumRegister(3) cr = ClassicalRegister(3) circuit_in = QuantumCircuit(qr, cr) circuit_in.h(qr[0]) circuit_in.h(qr[1]) circuit_in.measure(qr[0], cr[0]) circuit_in.measure(qr[1], cr[1]) circuit_in.x(qr[0]).c_if(cr, 0x3) circuit_in.measure(qr[0], cr[0]) circuit_in.measure(qr[1], cr[1]) circuit_in.measure(qr[2], cr[2]) dag_in = circuit_to_dag(circuit_in) dag_dependency = dag_to_dagdependency(dag_in, create_preds_and_succs=False) dag_out = dagdependency_to_dag(dag_dependency) self.assertEqual(dag_out, dag_in) def test_metadata(self): """Test circuit metadata is preservered through conversion.""" meta_dict = {"experiment_id": "1234", "execution_number": 4} qr = QuantumRegister(2) circuit_in = QuantumCircuit(qr, metadata=meta_dict) circuit_in.h(qr[0]) circuit_in.cx(qr[0], qr[1]) circuit_in.measure_all() dag = circuit_to_dag(circuit_in) self.assertEqual(dag.metadata, meta_dict) dag_dependency = dag_to_dagdependency(dag) self.assertEqual(dag_dependency.metadata, meta_dict) dag_out = dagdependency_to_dag(dag_dependency) self.assertEqual(dag_out.metadata, meta_dict) if __name__ == "__main__": unittest.main(verbosity=2)
https://github.com/swe-train/qiskit__qiskit
swe-train
# 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. """Test for the converter dag dependency to dag circuit and dag circuit to dag dependency.""" import unittest from qiskit.converters.circuit_to_dag import circuit_to_dag from qiskit.converters.dag_to_dagdependency_v2 import _dag_to_dagdependency_v2 from qiskit.converters.dagdependency_to_dag import dagdependency_to_dag from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from test import QiskitTestCase # pylint: disable=wrong-import-order class TestCircuitToDagDependencyV2(QiskitTestCase): """Test DAGCircuit to DAGDependencyV2.""" def test_circuit_and_dag_dependency(self): """Check convert to dag dependency and back""" qr = QuantumRegister(3) cr = ClassicalRegister(3) circuit_in = QuantumCircuit(qr, cr) circuit_in.h(qr[0]) circuit_in.h(qr[1]) circuit_in.measure(qr[0], cr[0]) circuit_in.measure(qr[1], cr[1]) circuit_in.x(qr[0]).c_if(cr, 0x3) circuit_in.measure(qr[0], cr[0]) circuit_in.measure(qr[1], cr[1]) circuit_in.measure(qr[2], cr[2]) dag_in = circuit_to_dag(circuit_in) dag_dependency = _dag_to_dagdependency_v2(dag_in) dag_out = dagdependency_to_dag(dag_dependency) self.assertEqual(dag_out, dag_in) def test_metadata(self): """Test circuit metadata is preservered through conversion.""" meta_dict = {"experiment_id": "1234", "execution_number": 4} qr = QuantumRegister(2) circuit_in = QuantumCircuit(qr, metadata=meta_dict) circuit_in.h(qr[0]) circuit_in.cx(qr[0], qr[1]) circuit_in.measure_all() dag = circuit_to_dag(circuit_in) self.assertEqual(dag.metadata, meta_dict) dag_dependency = _dag_to_dagdependency_v2(dag) self.assertEqual(dag_dependency.metadata, meta_dict) dag_out = dagdependency_to_dag(dag_dependency) self.assertEqual(dag_out.metadata, meta_dict) if __name__ == "__main__": unittest.main(verbosity=2)
https://github.com/swe-train/qiskit__qiskit
swe-train
# 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. """Test functionality to collect, split and consolidate blocks from DAGCircuits.""" import unittest from qiskit import QuantumRegister, ClassicalRegister from qiskit.converters import ( circuit_to_dag, circuit_to_dagdependency, circuit_to_instruction, dag_to_circuit, dagdependency_to_circuit, ) from qiskit.test import QiskitTestCase from qiskit.circuit import QuantumCircuit, Measure, Clbit from qiskit.dagcircuit.collect_blocks import BlockCollector, BlockSplitter, BlockCollapser class TestCollectBlocks(QiskitTestCase): """Tests to verify correctness of collecting, splitting, and consolidating blocks from DAGCircuit and DAGDependency. Additional tests appear as a part of CollectLinearFunctions and CollectCliffords passes. """ def test_collect_gates_from_dagcircuit_1(self): """Test collecting CX gates from DAGCircuits.""" qc = QuantumCircuit(5) qc.cx(0, 1) qc.cx(0, 2) qc.z(0) qc.cx(0, 3) qc.cx(0, 4) block_collector = BlockCollector(circuit_to_dag(qc)) blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name == "cx", split_blocks=False, min_block_size=2, ) # The middle z-gate leads to two blocks of size 2 each self.assertEqual(len(blocks), 2) self.assertEqual(len(blocks[0]), 2) self.assertEqual(len(blocks[1]), 2) def test_collect_gates_from_dagcircuit_2(self): """Test collecting both CX and Z gates from DAGCircuits.""" qc = QuantumCircuit(5) qc.cx(0, 1) qc.cx(0, 2) qc.z(0) qc.cx(0, 3) qc.cx(0, 4) block_collector = BlockCollector(circuit_to_dag(qc)) blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name in ["cx", "z"], split_blocks=False, min_block_size=1, ) # All of the gates are part of a single block self.assertEqual(len(blocks), 1) self.assertEqual(len(blocks[0]), 5) def test_collect_gates_from_dagcircuit_3(self): """Test collecting CX gates from DAGCircuits.""" qc = QuantumCircuit(5) qc.cx(0, 1) qc.cx(0, 2) qc.z(0) qc.cx(1, 3) qc.cx(0, 3) qc.cx(0, 4) block_collector = BlockCollector(circuit_to_dag(qc)) blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name in ["cx"], split_blocks=False, min_block_size=1, ) # We should end up with two CX blocks: even though there is "a path # around z(0)", without commutativity analysis z(0) prevents from # including all CX-gates into the same block self.assertEqual(len(blocks), 2) def test_collect_gates_from_dagdependency_1(self): """Test collecting CX gates from DAGDependency.""" qc = QuantumCircuit(5) qc.cx(0, 1) qc.cx(0, 2) qc.z(0) qc.cx(0, 3) qc.cx(0, 4) block_collector = BlockCollector(circuit_to_dagdependency(qc)) blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name == "cx", split_blocks=False, min_block_size=1, ) # The middle z-gate commutes with CX-gates, which leads to a single block of length 4 self.assertEqual(len(blocks), 1) self.assertEqual(len(blocks[0]), 4) def test_collect_gates_from_dagdependency_2(self): """Test collecting both CX and Z gates from DAGDependency.""" qc = QuantumCircuit(5) qc.cx(0, 1) qc.cx(0, 2) qc.z(0) qc.cx(0, 3) qc.cx(0, 4) block_collector = BlockCollector(circuit_to_dagdependency(qc)) blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name in ["cx", "z"], split_blocks=False, min_block_size=1, ) # All the gates are part of a single block self.assertEqual(len(blocks), 1) self.assertEqual(len(blocks[0]), 5) def test_collect_and_split_gates_from_dagcircuit(self): """Test collecting and splitting blocks from DAGCircuit.""" qc = QuantumCircuit(6) qc.cx(0, 1) qc.cx(3, 5) qc.cx(2, 4) qc.swap(1, 0) qc.cz(5, 3) block_collector = BlockCollector(circuit_to_dag(qc)) blocks = block_collector.collect_all_matching_blocks( lambda node: True, split_blocks=False, min_block_size=1, ) # All the gates are part of a single block self.assertEqual(len(blocks), 1) self.assertEqual(len(blocks[0]), 5) # Split the first block into sub-blocks over disjoint qubit sets # We should get 3 sub-blocks split_blocks = BlockSplitter().run(blocks[0]) self.assertEqual(len(split_blocks), 3) def test_collect_and_split_gates_from_dagdependency(self): """Test collecting and splitting blocks from DAGDependecy.""" qc = QuantumCircuit(6) qc.cx(0, 1) qc.cx(3, 5) qc.cx(2, 4) qc.swap(1, 0) qc.cz(5, 3) block_collector = BlockCollector(circuit_to_dagdependency(qc)) blocks = block_collector.collect_all_matching_blocks( lambda node: True, split_blocks=False, min_block_size=1, ) # All the gates are part of a single block self.assertEqual(len(blocks), 1) self.assertEqual(len(blocks[0]), 5) # Split the first block into sub-blocks over disjoint qubit sets # We should get 3 sub-blocks split_blocks = BlockSplitter().run(blocks[0]) self.assertEqual(len(split_blocks), 3) def test_circuit_has_measure(self): """Test that block collection works properly when there is a measure in the middle of the circuit.""" qc = QuantumCircuit(2, 1) qc.cx(1, 0) qc.x(0) qc.x(1) qc.measure(0, 0) qc.x(0) qc.cx(1, 0) block_collector = BlockCollector(circuit_to_dag(qc)) blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name in ["x", "cx"], split_blocks=False, min_block_size=1, ) # measure prevents combining the two blocks self.assertEqual(len(blocks), 2) self.assertEqual(len(blocks[0]), 3) self.assertEqual(len(blocks[1]), 2) def test_circuit_has_measure_dagdependency(self): """Test that block collection works properly when there is a measure in the middle of the circuit.""" qc = QuantumCircuit(2, 1) qc.cx(1, 0) qc.x(0) qc.x(1) qc.measure(0, 0) qc.x(0) qc.cx(1, 0) block_collector = BlockCollector(circuit_to_dagdependency(qc)) blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name in ["x", "cx"], split_blocks=False, min_block_size=1, ) # measure prevents combining the two blocks self.assertEqual(len(blocks), 2) self.assertEqual(len(blocks[0]), 3) self.assertEqual(len(blocks[1]), 2) def test_circuit_has_conditional_gates(self): """Test that block collection works properly when there the circuit contains conditional gates.""" qc = QuantumCircuit(2, 1) qc.x(0) qc.x(1) qc.cx(1, 0) qc.x(1).c_if(0, 1) qc.x(0) qc.x(1) qc.cx(0, 1) # If the filter_function does not look at conditions, we should collect all # gates into the block. block_collector = BlockCollector(circuit_to_dag(qc)) blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name in ["x", "cx"], split_blocks=False, min_block_size=1, ) self.assertEqual(len(blocks), 1) self.assertEqual(len(blocks[0]), 7) # If the filter_function does look at conditions, we should not collect the middle # conditional gate (note that x(1) following the measure is collected into the first # block). block_collector = BlockCollector(circuit_to_dag(qc)) blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name in ["x", "cx"] and not getattr(node.op, "condition", None), split_blocks=False, min_block_size=1, ) self.assertEqual(len(blocks), 2) self.assertEqual(len(blocks[0]), 4) self.assertEqual(len(blocks[1]), 2) def test_circuit_has_conditional_gates_dagdependency(self): """Test that block collection works properly when there the circuit contains conditional gates.""" qc = QuantumCircuit(2, 1) qc.x(0) qc.x(1) qc.cx(1, 0) qc.x(1).c_if(0, 1) qc.x(0) qc.x(1) qc.cx(0, 1) # If the filter_function does not look at conditions, we should collect all # gates into the block. block_collector = BlockCollector(circuit_to_dagdependency(qc)) blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name in ["x", "cx"], split_blocks=False, min_block_size=1, ) self.assertEqual(len(blocks), 1) self.assertEqual(len(blocks[0]), 7) # If the filter_function does look at conditions, we should not collect the middle # conditional gate (note that x(1) following the measure is collected into the first # block). block_collector = BlockCollector(circuit_to_dag(qc)) blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name in ["x", "cx"] and not getattr(node.op, "condition", None), split_blocks=False, min_block_size=1, ) self.assertEqual(len(blocks), 2) self.assertEqual(len(blocks[0]), 4) self.assertEqual(len(blocks[1]), 2) def test_multiple_collection_methods(self): """Test that block collection allows to collect blocks using several different filter functions.""" qc = QuantumCircuit(5) qc.cx(0, 1) qc.cx(0, 2) qc.swap(1, 4) qc.swap(4, 3) qc.z(0) qc.z(1) qc.z(2) qc.z(3) qc.z(4) qc.swap(3, 4) qc.cx(0, 3) qc.cx(0, 4) block_collector = BlockCollector(circuit_to_dag(qc)) linear_blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name in ["cx", "swap"], split_blocks=False, min_block_size=1, ) cx_blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name in ["cx"], split_blocks=False, min_block_size=1, ) swapz_blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name in ["swap", "z"], split_blocks=False, min_block_size=1, ) # We should end up with two linear blocks self.assertEqual(len(linear_blocks), 2) self.assertEqual(len(linear_blocks[0]), 4) self.assertEqual(len(linear_blocks[1]), 3) # We should end up with two cx blocks self.assertEqual(len(cx_blocks), 2) self.assertEqual(len(cx_blocks[0]), 2) self.assertEqual(len(cx_blocks[1]), 2) # We should end up with one swap,z blocks self.assertEqual(len(swapz_blocks), 1) self.assertEqual(len(swapz_blocks[0]), 8) def test_min_block_size(self): """Test that the option min_block_size for collecting blocks works correctly.""" # original circuit circuit = QuantumCircuit(2) circuit.cx(0, 1) circuit.h(0) circuit.cx(0, 1) circuit.cx(1, 0) circuit.h(0) circuit.cx(0, 1) circuit.cx(1, 0) circuit.cx(0, 1) block_collector = BlockCollector(circuit_to_dag(circuit)) # When min_block_size = 1, we should obtain 3 linear blocks blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name in ["cx", "swap"], split_blocks=False, min_block_size=1, ) self.assertEqual(len(blocks), 3) # When min_block_size = 2, we should obtain 2 linear blocks blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name in ["cx", "swap"], split_blocks=False, min_block_size=2, ) self.assertEqual(len(blocks), 2) # When min_block_size = 3, we should obtain 1 linear block blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name in ["cx", "swap"], split_blocks=False, min_block_size=3, ) self.assertEqual(len(blocks), 1) # When min_block_size = 4, we should obtain no linear blocks blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name in ["cx", "swap"], split_blocks=False, min_block_size=4, ) self.assertEqual(len(blocks), 0) def test_split_blocks(self): """Test that splitting blocks of nodes into sub-blocks works correctly.""" # original circuit is linear circuit = QuantumCircuit(5) circuit.cx(0, 2) circuit.cx(1, 4) circuit.cx(2, 0) circuit.cx(0, 3) circuit.swap(3, 2) circuit.swap(4, 1) block_collector = BlockCollector(circuit_to_dag(circuit)) # If we do not split block into sub-blocks, we expect a single linear block. blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name in ["cx", "swap"], split_blocks=False, min_block_size=2, ) self.assertEqual(len(blocks), 1) # If we do split block into sub-blocks, we expect two linear blocks: # one over qubits {0, 2, 3}, and another over qubits {1, 4}. blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name in ["cx", "swap"], split_blocks=True, min_block_size=2, ) self.assertEqual(len(blocks), 2) def test_do_not_split_blocks(self): """Test that splitting blocks of nodes into sub-blocks works correctly.""" # original circuit is linear circuit = QuantumCircuit(5) circuit.cx(0, 3) circuit.cx(0, 2) circuit.cx(1, 4) circuit.swap(4, 2) block_collector = BlockCollector(circuit_to_dagdependency(circuit)) # Check that we have a single linear block blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name in ["cx", "swap"], split_blocks=True, min_block_size=1, ) self.assertEqual(len(blocks), 1) def test_collect_blocks_with_cargs(self): """Test collecting and collapsing blocks with classical bits appearing as cargs.""" qc = QuantumCircuit(3) qc.h(0) qc.h(1) qc.h(2) qc.measure_all() dag = circuit_to_dag(qc) # Collect all measure instructions blocks = BlockCollector(dag).collect_all_matching_blocks( lambda node: isinstance(node.op, Measure), split_blocks=False, min_block_size=1 ) # We should have a single block consisting of 3 measures self.assertEqual(len(blocks), 1) self.assertEqual(len(blocks[0]), 3) self.assertEqual(blocks[0][0].op, Measure()) self.assertEqual(blocks[0][1].op, Measure()) self.assertEqual(blocks[0][2].op, Measure()) def _collapse_fn(circuit): op = circuit_to_instruction(circuit) op.name = "COLLAPSED" return op # Collapse block with measures into a single "COLLAPSED" block dag = BlockCollapser(dag).collapse_to_operation(blocks, _collapse_fn) collapsed_qc = dag_to_circuit(dag) self.assertEqual(len(collapsed_qc.data), 5) self.assertEqual(collapsed_qc.data[0].operation.name, "h") self.assertEqual(collapsed_qc.data[1].operation.name, "h") self.assertEqual(collapsed_qc.data[2].operation.name, "h") self.assertEqual(collapsed_qc.data[3].operation.name, "barrier") self.assertEqual(collapsed_qc.data[4].operation.name, "COLLAPSED") self.assertEqual(collapsed_qc.data[4].operation.definition.num_qubits, 3) self.assertEqual(collapsed_qc.data[4].operation.definition.num_clbits, 3) def test_collect_blocks_with_cargs_dagdependency(self): """Test collecting and collapsing blocks with classical bits appearing as cargs, using DAGDependency.""" qc = QuantumCircuit(3) qc.h(0) qc.h(1) qc.h(2) qc.measure_all() dag = circuit_to_dagdependency(qc) # Collect all measure instructions blocks = BlockCollector(dag).collect_all_matching_blocks( lambda node: isinstance(node.op, Measure), split_blocks=False, min_block_size=1 ) # We should have a single block consisting of 3 measures self.assertEqual(len(blocks), 1) self.assertEqual(len(blocks[0]), 3) self.assertEqual(blocks[0][0].op, Measure()) self.assertEqual(blocks[0][1].op, Measure()) self.assertEqual(blocks[0][2].op, Measure()) def _collapse_fn(circuit): op = circuit_to_instruction(circuit) op.name = "COLLAPSED" return op # Collapse block with measures into a single "COLLAPSED" block dag = BlockCollapser(dag).collapse_to_operation(blocks, _collapse_fn) collapsed_qc = dagdependency_to_circuit(dag) self.assertEqual(len(collapsed_qc.data), 5) self.assertEqual(collapsed_qc.data[0].operation.name, "h") self.assertEqual(collapsed_qc.data[1].operation.name, "h") self.assertEqual(collapsed_qc.data[2].operation.name, "h") self.assertEqual(collapsed_qc.data[3].operation.name, "barrier") self.assertEqual(collapsed_qc.data[4].operation.name, "COLLAPSED") self.assertEqual(collapsed_qc.data[4].operation.definition.num_qubits, 3) self.assertEqual(collapsed_qc.data[4].operation.definition.num_clbits, 3) def test_collect_blocks_with_clbits(self): """Test collecting and collapsing blocks with classical bits appearing under condition.""" qc = QuantumCircuit(4, 3) qc.cx(0, 1).c_if(0, 1) qc.cx(2, 3) qc.cx(1, 2) qc.cx(0, 1) qc.cx(2, 3).c_if(1, 0) dag = circuit_to_dag(qc) # Collect all cx gates (including the conditional ones) blocks = BlockCollector(dag).collect_all_matching_blocks( lambda node: node.op.name == "cx", split_blocks=False, min_block_size=1 ) # We should have a single block consisting of all CX nodes self.assertEqual(len(blocks), 1) self.assertEqual(len(blocks[0]), 5) def _collapse_fn(circuit): op = circuit_to_instruction(circuit) op.name = "COLLAPSED" return op # Collapse block with measures into a single "COLLAPSED" block dag = BlockCollapser(dag).collapse_to_operation(blocks, _collapse_fn) collapsed_qc = dag_to_circuit(dag) self.assertEqual(len(collapsed_qc.data), 1) self.assertEqual(collapsed_qc.data[0].operation.name, "COLLAPSED") self.assertEqual(collapsed_qc.data[0].operation.definition.num_qubits, 4) self.assertEqual(collapsed_qc.data[0].operation.definition.num_clbits, 2) def test_collect_blocks_with_clbits_dagdependency(self): """Test collecting and collapsing blocks with classical bits appearing under conditions, using DAGDependency.""" qc = QuantumCircuit(4, 3) qc.cx(0, 1).c_if(0, 1) qc.cx(2, 3) qc.cx(1, 2) qc.cx(0, 1) qc.cx(2, 3).c_if(1, 0) dag = circuit_to_dagdependency(qc) # Collect all cx gates (including the conditional ones) blocks = BlockCollector(dag).collect_all_matching_blocks( lambda node: node.op.name == "cx", split_blocks=False, min_block_size=1 ) # We should have a single block consisting of all CX nodes self.assertEqual(len(blocks), 1) self.assertEqual(len(blocks[0]), 5) def _collapse_fn(circuit): op = circuit_to_instruction(circuit) op.name = "COLLAPSED" return op # Collapse block with measures into a single "COLLAPSED" block dag = BlockCollapser(dag).collapse_to_operation(blocks, _collapse_fn) collapsed_qc = dagdependency_to_circuit(dag) self.assertEqual(len(collapsed_qc.data), 1) self.assertEqual(collapsed_qc.data[0].operation.name, "COLLAPSED") self.assertEqual(collapsed_qc.data[0].operation.definition.num_qubits, 4) self.assertEqual(collapsed_qc.data[0].operation.definition.num_clbits, 2) def test_collect_blocks_with_clbits2(self): """Test collecting and collapsing blocks with classical bits appearing under condition.""" qreg = QuantumRegister(4, "qr") creg = ClassicalRegister(3, "cr") cbit = Clbit() qc = QuantumCircuit(qreg, creg, [cbit]) qc.cx(0, 1).c_if(creg[1], 1) qc.cx(2, 3).c_if(cbit, 0) qc.cx(1, 2) qc.cx(0, 1).c_if(creg[2], 1) dag = circuit_to_dag(qc) # Collect all cx gates (including the conditional ones) blocks = BlockCollector(dag).collect_all_matching_blocks( lambda node: node.op.name == "cx", split_blocks=False, min_block_size=1 ) # We should have a single block consisting of all CX nodes self.assertEqual(len(blocks), 1) self.assertEqual(len(blocks[0]), 4) def _collapse_fn(circuit): op = circuit_to_instruction(circuit) op.name = "COLLAPSED" return op # Collapse block with measures into a single "COLLAPSED" block dag = BlockCollapser(dag).collapse_to_operation(blocks, _collapse_fn) collapsed_qc = dag_to_circuit(dag) self.assertEqual(len(collapsed_qc.data), 1) self.assertEqual(collapsed_qc.data[0].operation.name, "COLLAPSED") self.assertEqual(collapsed_qc.data[0].operation.definition.num_qubits, 4) self.assertEqual(collapsed_qc.data[0].operation.definition.num_clbits, 3) def test_collect_blocks_with_clbits2_dagdependency(self): """Test collecting and collapsing blocks with classical bits appearing under condition, using DAGDependency.""" qreg = QuantumRegister(4, "qr") creg = ClassicalRegister(3, "cr") cbit = Clbit() qc = QuantumCircuit(qreg, creg, [cbit]) qc.cx(0, 1).c_if(creg[1], 1) qc.cx(2, 3).c_if(cbit, 0) qc.cx(1, 2) qc.cx(0, 1).c_if(creg[2], 1) dag = circuit_to_dag(qc) # Collect all cx gates (including the conditional ones) blocks = BlockCollector(dag).collect_all_matching_blocks( lambda node: node.op.name == "cx", split_blocks=False, min_block_size=1 ) # We should have a single block consisting of all CX nodes self.assertEqual(len(blocks), 1) self.assertEqual(len(blocks[0]), 4) def _collapse_fn(circuit): op = circuit_to_instruction(circuit) op.name = "COLLAPSED" return op # Collapse block with measures into a single "COLLAPSED" block dag = BlockCollapser(dag).collapse_to_operation(blocks, _collapse_fn) collapsed_qc = dag_to_circuit(dag) self.assertEqual(len(collapsed_qc.data), 1) self.assertEqual(collapsed_qc.data[0].operation.name, "COLLAPSED") self.assertEqual(collapsed_qc.data[0].operation.definition.num_qubits, 4) self.assertEqual(collapsed_qc.data[0].operation.definition.num_clbits, 3) def test_collect_blocks_with_cregs(self): """Test collecting and collapsing blocks with classical registers appearing under condition.""" qreg = QuantumRegister(4, "qr") creg = ClassicalRegister(3, "cr") creg2 = ClassicalRegister(2, "cr2") qc = QuantumCircuit(qreg, creg, creg2) qc.cx(0, 1).c_if(creg, 3) qc.cx(1, 2) qc.cx(0, 1).c_if(creg[2], 1) dag = circuit_to_dag(qc) # Collect all cx gates (including the conditional ones) blocks = BlockCollector(dag).collect_all_matching_blocks( lambda node: node.op.name == "cx", split_blocks=False, min_block_size=1 ) # We should have a single block consisting of all CX nodes self.assertEqual(len(blocks), 1) self.assertEqual(len(blocks[0]), 3) def _collapse_fn(circuit): op = circuit_to_instruction(circuit) op.name = "COLLAPSED" return op # Collapse block with measures into a single "COLLAPSED" block dag = BlockCollapser(dag).collapse_to_operation(blocks, _collapse_fn) collapsed_qc = dag_to_circuit(dag) self.assertEqual(len(collapsed_qc.data), 1) self.assertEqual(collapsed_qc.data[0].operation.name, "COLLAPSED") self.assertEqual(len(collapsed_qc.data[0].operation.definition.cregs), 1) self.assertEqual(collapsed_qc.data[0].operation.definition.num_qubits, 3) self.assertEqual(collapsed_qc.data[0].operation.definition.num_clbits, 3) def test_collect_blocks_with_cregs_dagdependency(self): """Test collecting and collapsing blocks with classical registers appearing under condition, using DAGDependency.""" qreg = QuantumRegister(4, "qr") creg = ClassicalRegister(3, "cr") creg2 = ClassicalRegister(2, "cr2") qc = QuantumCircuit(qreg, creg, creg2) qc.cx(0, 1).c_if(creg, 3) qc.cx(1, 2) qc.cx(0, 1).c_if(creg[2], 1) dag = circuit_to_dagdependency(qc) # Collect all cx gates (including the conditional ones) blocks = BlockCollector(dag).collect_all_matching_blocks( lambda node: node.op.name == "cx", split_blocks=False, min_block_size=1 ) # We should have a single block consisting of all CX nodes self.assertEqual(len(blocks), 1) self.assertEqual(len(blocks[0]), 3) def _collapse_fn(circuit): op = circuit_to_instruction(circuit) op.name = "COLLAPSED" return op # Collapse block with measures into a single "COLLAPSED" block dag = BlockCollapser(dag).collapse_to_operation(blocks, _collapse_fn) collapsed_qc = dagdependency_to_circuit(dag) self.assertEqual(len(collapsed_qc.data), 1) self.assertEqual(collapsed_qc.data[0].operation.name, "COLLAPSED") self.assertEqual(len(collapsed_qc.data[0].operation.definition.cregs), 1) self.assertEqual(collapsed_qc.data[0].operation.definition.num_qubits, 3) self.assertEqual(collapsed_qc.data[0].operation.definition.num_clbits, 3) def test_collect_blocks_backwards_dagcircuit(self): """Test collecting H gates from DAGCircuit in the forward vs. the reverse directions.""" qc = QuantumCircuit(4) qc.h(0) qc.h(1) qc.h(2) qc.h(3) qc.cx(1, 2) qc.z(0) qc.z(1) qc.z(2) qc.z(3) block_collector = BlockCollector(circuit_to_dag(qc)) # When collecting in the forward direction, there are two blocks of # single-qubit gates: the first of size 6, and the second of size 2. blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name in ["h", "z"], split_blocks=False, min_block_size=1, collect_from_back=False, ) self.assertEqual(len(blocks), 2) self.assertEqual(len(blocks[0]), 6) self.assertEqual(len(blocks[1]), 2) # When collecting in the backward direction, there are also two blocks of # single-qubit ates: but now the first is of size 2, and the second is of size 6. blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name in ["h", "z"], split_blocks=False, min_block_size=1, collect_from_back=True, ) self.assertEqual(len(blocks), 2) self.assertEqual(len(blocks[0]), 2) self.assertEqual(len(blocks[1]), 6) def test_collect_blocks_backwards_dagdependency(self): """Test collecting H gates from DAGDependency in the forward vs. the reverse directions.""" qc = QuantumCircuit(4) qc.z(0) qc.z(1) qc.z(2) qc.z(3) qc.cx(1, 2) qc.h(0) qc.h(1) qc.h(2) qc.h(3) block_collector = BlockCollector(circuit_to_dagdependency(qc)) # When collecting in the forward direction, there are two blocks of # single-qubit gates: the first of size 6, and the second of size 2. blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name in ["h", "z"], split_blocks=False, min_block_size=1, collect_from_back=False, ) self.assertEqual(len(blocks), 2) self.assertEqual(len(blocks[0]), 6) self.assertEqual(len(blocks[1]), 2) # When collecting in the backward direction, there are also two blocks of # single-qubit ates: but now the first is of size 1, and the second is of size 7 # (note that z(1) and CX(1, 2) commute). blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name in ["h", "z"], split_blocks=False, min_block_size=1, collect_from_back=True, ) self.assertEqual(len(blocks), 2) self.assertEqual(len(blocks[0]), 1) self.assertEqual(len(blocks[1]), 7) def test_split_layers_dagcircuit(self): """Test that splitting blocks of nodes into layers works correctly.""" # original circuit is linear circuit = QuantumCircuit(5) circuit.cx(0, 2) circuit.cx(1, 4) circuit.cx(2, 0) circuit.cx(0, 3) circuit.swap(3, 2) circuit.swap(4, 1) block_collector = BlockCollector(circuit_to_dag(circuit)) # If we split the gates into depth-1 layers, we expect four linear blocks: # CX(0, 2), CX(1, 4) # CX(2, 0), CX(4, 1) # CX(0, 3) # CX(3, 2) blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name in ["cx", "swap"], split_blocks=False, min_block_size=1, split_layers=True, ) self.assertEqual(len(blocks), 4) self.assertEqual(len(blocks[0]), 2) self.assertEqual(len(blocks[1]), 2) self.assertEqual(len(blocks[2]), 1) self.assertEqual(len(blocks[3]), 1) def test_split_layers_dagdependency(self): """Test that splitting blocks of nodes into layers works correctly.""" # original circuit is linear circuit = QuantumCircuit(5) circuit.cx(0, 2) circuit.cx(1, 4) circuit.cx(2, 0) circuit.cx(0, 3) circuit.swap(3, 2) circuit.swap(4, 1) block_collector = BlockCollector(circuit_to_dagdependency(circuit)) # If we split the gates into depth-1 layers, we expect four linear blocks: # CX(0, 2), CX(1, 4) # CX(2, 0), CX(4, 1) # CX(0, 3) # CX(3, 2) blocks = block_collector.collect_all_matching_blocks( lambda node: node.op.name in ["cx", "swap"], split_blocks=False, min_block_size=1, split_layers=True, ) self.assertEqual(len(blocks), 4) self.assertEqual(len(blocks[0]), 2) self.assertEqual(len(blocks[1]), 2) self.assertEqual(len(blocks[2]), 1) self.assertEqual(len(blocks[3]), 1) if __name__ == "__main__": unittest.main()
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2022, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for BackendSampler.""" import math import unittest from unittest.mock import patch from test import combine from test.python.transpiler._dummy_passes import DummyTP import numpy as np from ddt import ddt from qiskit import QuantumCircuit from qiskit.circuit.library import RealAmplitudes from qiskit.primitives import BackendSampler, SamplerResult from qiskit.providers import JobStatus, JobV1 from qiskit.providers.fake_provider import FakeNairobi, FakeNairobiV2 from qiskit.providers.basicaer import QasmSimulatorPy from qiskit.test import QiskitTestCase from qiskit.transpiler import PassManager from qiskit.utils import optionals BACKENDS = [FakeNairobi(), FakeNairobiV2()] @ddt class TestBackendSampler(QiskitTestCase): """Test BackendSampler""" def setUp(self): super().setUp() hadamard = QuantumCircuit(1, 1) hadamard.h(0) hadamard.measure(0, 0) bell = QuantumCircuit(2) bell.h(0) bell.cx(0, 1) bell.measure_all() self._circuit = [hadamard, bell] self._target = [ {0: 0.5, 1: 0.5}, {0: 0.5, 3: 0.5, 1: 0, 2: 0}, ] self._pqc = RealAmplitudes(num_qubits=2, reps=2) self._pqc.measure_all() self._pqc2 = RealAmplitudes(num_qubits=2, reps=3) self._pqc2.measure_all() self._pqc_params = [[0.0] * 6, [1.0] * 6] self._pqc_target = [{0: 1}, {0: 0.0148, 1: 0.3449, 2: 0.0531, 3: 0.5872}] self._theta = [ [0, 1, 1, 2, 3, 5], [1, 2, 3, 4, 5, 6], [0, 1, 2, 3, 4, 5, 6, 7], ] def _generate_circuits_target(self, indices): if isinstance(indices, list): circuits = [self._circuit[j] for j in indices] target = [self._target[j] for j in indices] else: raise ValueError(f"invalid index {indices}") return circuits, target def _generate_params_target(self, indices): if isinstance(indices, int): params = self._pqc_params[indices] target = self._pqc_target[indices] elif isinstance(indices, list): params = [self._pqc_params[j] for j in indices] target = [self._pqc_target[j] for j in indices] else: raise ValueError(f"invalid index {indices}") return params, target def _compare_probs(self, prob, target): if not isinstance(prob, list): prob = [prob] if not isinstance(target, list): target = [target] self.assertEqual(len(prob), len(target)) for p, targ in zip(prob, target): for key, t_val in targ.items(): if key in p: self.assertAlmostEqual(p[key], t_val, delta=0.1) else: self.assertAlmostEqual(t_val, 0, delta=0.1) @combine(backend=BACKENDS) def test_sampler_run(self, backend): """Test Sampler.run().""" bell = self._circuit[1] sampler = BackendSampler(backend=backend) job = sampler.run(circuits=[bell], shots=1000) self.assertIsInstance(job, JobV1) result = job.result() self.assertIsInstance(result, SamplerResult) self.assertEqual(result.quasi_dists[0].shots, 1000) self.assertEqual(result.quasi_dists[0].stddev_upper_bound, math.sqrt(1 / 1000)) self._compare_probs(result.quasi_dists, self._target[1]) @combine(backend=BACKENDS) def test_sample_run_multiple_circuits(self, backend): """Test Sampler.run() with multiple circuits.""" # executes three Bell circuits # Argument `parameters` is optional. bell = self._circuit[1] sampler = BackendSampler(backend=backend) result = sampler.run([bell, bell, bell]).result() # print([q.binary_probabilities() for q in result.quasi_dists]) self._compare_probs(result.quasi_dists[0], self._target[1]) self._compare_probs(result.quasi_dists[1], self._target[1]) self._compare_probs(result.quasi_dists[2], self._target[1]) @combine(backend=BACKENDS) def test_sampler_run_with_parameterized_circuits(self, backend): """Test Sampler.run() with parameterized circuits.""" # parameterized circuit pqc = self._pqc pqc2 = self._pqc2 theta1, theta2, theta3 = self._theta sampler = BackendSampler(backend=backend) result = sampler.run([pqc, pqc, pqc2], [theta1, theta2, theta3]).result() # result of pqc(theta1) prob1 = { "00": 0.1309248462975777, "01": 0.3608720796028448, "10": 0.09324865232050054, "11": 0.41495442177907715, } self.assertDictAlmostEqual(result.quasi_dists[0].binary_probabilities(), prob1, delta=0.1) # result of pqc(theta2) prob2 = { "00": 0.06282290651933871, "01": 0.02877144385576705, "10": 0.606654494132085, "11": 0.3017511554928094, } self.assertDictAlmostEqual(result.quasi_dists[1].binary_probabilities(), prob2, delta=0.1) # result of pqc2(theta3) prob3 = { "00": 0.1880263994380416, "01": 0.6881971261189544, "10": 0.09326232720582443, "11": 0.030514147237179892, } self.assertDictAlmostEqual(result.quasi_dists[2].binary_probabilities(), prob3, delta=0.1) @combine(backend=BACKENDS) def test_run_1qubit(self, backend): """test for 1-qubit cases""" qc = QuantumCircuit(1) qc.measure_all() qc2 = QuantumCircuit(1) qc2.x(0) qc2.measure_all() sampler = BackendSampler(backend=backend) result = sampler.run([qc, qc2]).result() self.assertIsInstance(result, SamplerResult) self.assertEqual(len(result.quasi_dists), 2) self.assertDictAlmostEqual(result.quasi_dists[0], {0: 1}, 0.1) self.assertDictAlmostEqual(result.quasi_dists[1], {1: 1}, 0.1) @combine(backend=BACKENDS) def test_run_2qubit(self, backend): """test for 2-qubit cases""" qc0 = QuantumCircuit(2) qc0.measure_all() qc1 = QuantumCircuit(2) qc1.x(0) qc1.measure_all() qc2 = QuantumCircuit(2) qc2.x(1) qc2.measure_all() qc3 = QuantumCircuit(2) qc3.x([0, 1]) qc3.measure_all() sampler = BackendSampler(backend=backend) result = sampler.run([qc0, qc1, qc2, qc3]).result() self.assertIsInstance(result, SamplerResult) self.assertEqual(len(result.quasi_dists), 4) self.assertDictAlmostEqual(result.quasi_dists[0], {0: 1}, 0.1) self.assertDictAlmostEqual(result.quasi_dists[1], {1: 1}, 0.1) self.assertDictAlmostEqual(result.quasi_dists[2], {2: 1}, 0.1) self.assertDictAlmostEqual(result.quasi_dists[3], {3: 1}, 0.1) @combine(backend=BACKENDS) def test_run_errors(self, backend): """Test for errors""" qc1 = QuantumCircuit(1) qc1.measure_all() qc2 = RealAmplitudes(num_qubits=1, reps=1) qc2.measure_all() sampler = BackendSampler(backend=backend) with self.assertRaises(ValueError): sampler.run([qc1], [[1e2]]).result() with self.assertRaises(ValueError): sampler.run([qc2], [[]]).result() with self.assertRaises(ValueError): sampler.run([qc2], [[1e2]]).result() @combine(backend=BACKENDS) def test_run_empty_parameter(self, backend): """Test for empty parameter""" n = 5 qc = QuantumCircuit(n, n - 1) qc.measure(range(n - 1), range(n - 1)) sampler = BackendSampler(backend=backend) with self.subTest("one circuit"): result = sampler.run([qc], shots=1000).result() self.assertEqual(len(result.quasi_dists), 1) for q_d in result.quasi_dists: quasi_dist = {k: v for k, v in q_d.items() if v != 0.0} self.assertDictAlmostEqual(quasi_dist, {0: 1.0}, delta=0.1) self.assertEqual(len(result.metadata), 1) with self.subTest("two circuits"): result = sampler.run([qc, qc], shots=1000).result() self.assertEqual(len(result.quasi_dists), 2) for q_d in result.quasi_dists: quasi_dist = {k: v for k, v in q_d.items() if v != 0.0} self.assertDictAlmostEqual(quasi_dist, {0: 1.0}, delta=0.1) self.assertEqual(len(result.metadata), 2) @combine(backend=BACKENDS) def test_run_numpy_params(self, backend): """Test for numpy array as parameter values""" qc = RealAmplitudes(num_qubits=2, reps=2) qc.measure_all() k = 5 params_array = np.random.rand(k, qc.num_parameters) params_list = params_array.tolist() params_list_array = list(params_array) sampler = BackendSampler(backend=backend) target = sampler.run([qc] * k, params_list).result() with self.subTest("ndarrary"): result = sampler.run([qc] * k, params_array).result() self.assertEqual(len(result.metadata), k) for i in range(k): self.assertDictAlmostEqual(result.quasi_dists[i], target.quasi_dists[i], delta=0.1) with self.subTest("list of ndarray"): result = sampler.run([qc] * k, params_list_array).result() self.assertEqual(len(result.metadata), k) for i in range(k): self.assertDictAlmostEqual(result.quasi_dists[i], target.quasi_dists[i], delta=0.1) @combine(backend=BACKENDS) def test_run_with_shots_option(self, backend): """test with shots option.""" params, target = self._generate_params_target([1]) sampler = BackendSampler(backend=backend) result = sampler.run( circuits=[self._pqc], parameter_values=params, shots=1024, seed=15 ).result() self._compare_probs(result.quasi_dists, target) @combine(backend=BACKENDS) def test_primitive_job_status_done(self, backend): """test primitive job's status""" bell = self._circuit[1] sampler = BackendSampler(backend=backend) job = sampler.run(circuits=[bell]) _ = job.result() self.assertEqual(job.status(), JobStatus.DONE) def test_primitive_job_size_limit_backend_v2(self): """Test primitive respects backend's job size limit.""" class FakeNairobiLimitedCircuits(FakeNairobiV2): """FakeNairobiV2 with job size limit.""" @property def max_circuits(self): return 1 qc = QuantumCircuit(1) qc.measure_all() qc2 = QuantumCircuit(1) qc2.x(0) qc2.measure_all() sampler = BackendSampler(backend=FakeNairobiLimitedCircuits()) result = sampler.run([qc, qc2]).result() self.assertIsInstance(result, SamplerResult) self.assertEqual(len(result.quasi_dists), 2) self.assertDictAlmostEqual(result.quasi_dists[0], {0: 1}, 0.1) self.assertDictAlmostEqual(result.quasi_dists[1], {1: 1}, 0.1) def test_primitive_job_size_limit_backend_v1(self): """Test primitive respects backend's job size limit.""" backend = FakeNairobi() config = backend.configuration() config.max_experiments = 1 backend._configuration = config qc = QuantumCircuit(1) qc.measure_all() qc2 = QuantumCircuit(1) qc2.x(0) qc2.measure_all() sampler = BackendSampler(backend=backend) result = sampler.run([qc, qc2]).result() self.assertIsInstance(result, SamplerResult) self.assertEqual(len(result.quasi_dists), 2) self.assertDictAlmostEqual(result.quasi_dists[0], {0: 1}, 0.1) self.assertDictAlmostEqual(result.quasi_dists[1], {1: 1}, 0.1) @unittest.skipUnless(optionals.HAS_AER, "qiskit-aer is required to run this test") def test_circuit_with_dynamic_circuit(self): """Test BackendSampler with QuantumCircuit with a dynamic circuit""" from qiskit_aer import Aer qc = QuantumCircuit(2, 1) with qc.for_loop(range(5)): qc.h(0) qc.cx(0, 1) qc.measure(0, 0) qc.break_loop().c_if(0, True) backend = Aer.get_backend("aer_simulator") backend.set_options(seed_simulator=15) sampler = BackendSampler(backend, skip_transpilation=True) sampler.set_transpile_options(seed_transpiler=15) result = sampler.run(qc).result() self.assertDictAlmostEqual(result.quasi_dists[0], {0: 0.5029296875, 1: 0.4970703125}) def test_sequential_run(self): """Test sequential run.""" qc = QuantumCircuit(1) qc.measure_all() qc2 = QuantumCircuit(1) qc2.x(0) qc2.measure_all() sampler = BackendSampler(backend=FakeNairobi()) result = sampler.run([qc]).result() self.assertDictAlmostEqual(result.quasi_dists[0], {0: 1}, 0.1) result2 = sampler.run([qc2]).result() self.assertDictAlmostEqual(result2.quasi_dists[0], {1: 1}, 0.1) result3 = sampler.run([qc, qc2]).result() self.assertDictAlmostEqual(result3.quasi_dists[0], {0: 1}, 0.1) self.assertDictAlmostEqual(result3.quasi_dists[1], {1: 1}, 0.1) def test_outcome_bitstring_size(self): """Test that the result bitstrings are properly padded. E.g. measuring '0001' should not get truncated to '1'. """ qc = QuantumCircuit(4) qc.x(0) qc.measure_all() # We need a noise-free backend here (shot noise is fine) to ensure that # the only bit string measured is "0001". With device noise, it could happen that # strings with a leading 1 are measured and then the truncation cannot be tested. sampler = BackendSampler(backend=QasmSimulatorPy()) result = sampler.run(qc).result() probs = result.quasi_dists[0].binary_probabilities() self.assertIn("0001", probs.keys()) self.assertEqual(len(probs), 1) def test_bound_pass_manager(self): """Test bound pass manager.""" with self.subTest("Test single circuit"): dummy_pass = DummyTP() with patch.object(DummyTP, "run", wraps=dummy_pass.run) as mock_pass: bound_pass = PassManager(dummy_pass) sampler = BackendSampler(backend=FakeNairobi(), bound_pass_manager=bound_pass) _ = sampler.run(self._circuit[0]).result() self.assertEqual(mock_pass.call_count, 1) with self.subTest("Test circuit batch"): dummy_pass = DummyTP() with patch.object(DummyTP, "run", wraps=dummy_pass.run) as mock_pass: bound_pass = PassManager(dummy_pass) sampler = BackendSampler(backend=FakeNairobi(), bound_pass_manager=bound_pass) _ = sampler.run([self._circuit[0], self._circuit[0]]).result() self.assertEqual(mock_pass.call_count, 2) if __name__ == "__main__": unittest.main()
https://github.com/swe-train/qiskit__qiskit
swe-train
# 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. """Tests for Backend Sampler V2.""" from __future__ import annotations import unittest from test import QiskitTestCase, combine import numpy as np from ddt import ddt from numpy.typing import NDArray from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister from qiskit.circuit import Parameter from qiskit.circuit.library import RealAmplitudes, UnitaryGate from qiskit.primitives import PrimitiveResult, PubResult, StatevectorSampler from qiskit.primitives.backend_sampler_v2 import BackendSamplerV2 from qiskit.primitives.containers import BitArray from qiskit.primitives.containers.data_bin import DataBin from qiskit.primitives.containers.sampler_pub import SamplerPub from qiskit.providers import JobStatus from qiskit.providers.backend_compat import BackendV2Converter from qiskit.providers.basic_provider import BasicSimulator from qiskit.providers.fake_provider import Fake7QPulseV1, GenericBackendV2 from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager BACKENDS = [BasicSimulator(), Fake7QPulseV1(), BackendV2Converter(Fake7QPulseV1())] @ddt class TestBackendSamplerV2(QiskitTestCase): """Test for BackendSamplerV2""" def setUp(self): super().setUp() self._shots = 10000 self._seed = 123 self._options = {"default_shots": self._shots, "seed_simulator": self._seed} self._cases = [] hadamard = QuantumCircuit(1, 1, name="Hadamard") hadamard.h(0) hadamard.measure(0, 0) self._cases.append((hadamard, None, {0: 5000, 1: 5000})) # case 0 bell = QuantumCircuit(2, name="Bell") bell.h(0) bell.cx(0, 1) bell.measure_all() self._cases.append((bell, None, {0: 5000, 3: 5000})) # case 1 pqc = RealAmplitudes(num_qubits=2, reps=2) pqc.measure_all() self._cases.append((pqc, [0] * 6, {0: 10000})) # case 2 self._cases.append((pqc, [1] * 6, {0: 168, 1: 3389, 2: 470, 3: 5973})) # case 3 self._cases.append((pqc, [0, 1, 1, 2, 3, 5], {0: 1339, 1: 3534, 2: 912, 3: 4215})) # case 4 self._cases.append((pqc, [1, 2, 3, 4, 5, 6], {0: 634, 1: 291, 2: 6039, 3: 3036})) # case 5 pqc2 = RealAmplitudes(num_qubits=2, reps=3) pqc2.measure_all() self._cases.append( (pqc2, [0, 1, 2, 3, 4, 5, 6, 7], {0: 1898, 1: 6864, 2: 928, 3: 311}) ) # case 6 def _assert_allclose(self, bitarray: BitArray, target: NDArray | BitArray, rtol=1e-1, atol=5e2): self.assertEqual(bitarray.shape, target.shape) for idx in np.ndindex(bitarray.shape): int_counts = bitarray.get_int_counts(idx) target_counts = ( target.get_int_counts(idx) if isinstance(target, BitArray) else target[idx] ) max_key = max(max(int_counts.keys()), max(target_counts.keys())) ary = np.array([int_counts.get(i, 0) for i in range(max_key + 1)]) tgt = np.array([target_counts.get(i, 0) for i in range(max_key + 1)]) np.testing.assert_allclose(ary, tgt, rtol=rtol, atol=atol, err_msg=f"index: {idx}") @combine(backend=BACKENDS) def test_sampler_run(self, backend): """Test run().""" pm = generate_preset_pass_manager(optimization_level=0, backend=backend) with self.subTest("single"): bell, _, target = self._cases[1] bell = pm.run(bell) sampler = BackendSamplerV2(backend=backend, options=self._options) job = sampler.run([bell], shots=self._shots) result = job.result() self.assertIsInstance(result, PrimitiveResult) self.assertIsInstance(result.metadata, dict) self.assertEqual(len(result), 1) self.assertIsInstance(result[0], PubResult) self.assertIsInstance(result[0].data, DataBin) self.assertIsInstance(result[0].data.meas, BitArray) self._assert_allclose(result[0].data.meas, np.array(target)) with self.subTest("single with param"): pqc, param_vals, target = self._cases[2] sampler = BackendSamplerV2(backend=backend, options=self._options) pqc = pm.run(pqc) params = (param.name for param in pqc.parameters) job = sampler.run([(pqc, {params: param_vals})], shots=self._shots) result = job.result() self.assertIsInstance(result, PrimitiveResult) self.assertIsInstance(result.metadata, dict) self.assertEqual(len(result), 1) self.assertIsInstance(result[0], PubResult) self.assertIsInstance(result[0].data, DataBin) self.assertIsInstance(result[0].data.meas, BitArray) self._assert_allclose(result[0].data.meas, np.array(target)) with self.subTest("multiple"): pqc, param_vals, target = self._cases[2] sampler = BackendSamplerV2(backend=backend, options=self._options) pqc = pm.run(pqc) params = (param.name for param in pqc.parameters) job = sampler.run( [(pqc, {params: [param_vals, param_vals, param_vals]})], shots=self._shots ) result = job.result() self.assertIsInstance(result, PrimitiveResult) self.assertIsInstance(result.metadata, dict) self.assertEqual(len(result), 1) self.assertIsInstance(result[0], PubResult) self.assertIsInstance(result[0].data, DataBin) self.assertIsInstance(result[0].data.meas, BitArray) self._assert_allclose(result[0].data.meas, np.array([target, target, target])) @combine(backend=BACKENDS) def test_sampler_run_multiple_times(self, backend): """Test run() returns the same results if the same input is given.""" bell, _, _ = self._cases[1] sampler = BackendSamplerV2(backend=backend, options=self._options) pm = generate_preset_pass_manager(optimization_level=0, backend=backend) bell = pm.run(bell) result1 = sampler.run([bell], shots=self._shots).result() meas1 = result1[0].data.meas result2 = sampler.run([bell], shots=self._shots).result() meas2 = result2[0].data.meas self._assert_allclose(meas1, meas2, rtol=0) @combine(backend=BACKENDS) def test_sample_run_multiple_circuits(self, backend): """Test run() with multiple circuits.""" bell, _, target = self._cases[1] sampler = BackendSamplerV2(backend=backend, options=self._options) pm = generate_preset_pass_manager(optimization_level=0, backend=backend) bell = pm.run(bell) result = sampler.run([bell, bell, bell], shots=self._shots).result() self.assertEqual(len(result), 3) self._assert_allclose(result[0].data.meas, np.array(target)) self._assert_allclose(result[1].data.meas, np.array(target)) self._assert_allclose(result[2].data.meas, np.array(target)) @combine(backend=BACKENDS) def test_sampler_run_with_parameterized_circuits(self, backend): """Test run() with parameterized circuits.""" pqc1, param1, target1 = self._cases[4] pqc2, param2, target2 = self._cases[5] pqc3, param3, target3 = self._cases[6] pm = generate_preset_pass_manager(optimization_level=0, backend=backend) pqc1, pqc2, pqc3 = pm.run([pqc1, pqc2, pqc3]) sampler = BackendSamplerV2(backend=backend, options=self._options) result = sampler.run( [(pqc1, param1), (pqc2, param2), (pqc3, param3)], shots=self._shots ).result() self.assertEqual(len(result), 3) self._assert_allclose(result[0].data.meas, np.array(target1)) self._assert_allclose(result[1].data.meas, np.array(target2)) self._assert_allclose(result[2].data.meas, np.array(target3)) @combine(backend=BACKENDS) def test_run_1qubit(self, backend): """test for 1-qubit cases""" qc = QuantumCircuit(1) qc.measure_all() qc2 = QuantumCircuit(1) qc2.x(0) qc2.measure_all() pm = generate_preset_pass_manager(optimization_level=0, backend=backend) qc, qc2 = pm.run([qc, qc2]) sampler = BackendSamplerV2(backend=backend, options=self._options) result = sampler.run([qc, qc2], shots=self._shots).result() self.assertEqual(len(result), 2) for i in range(2): self._assert_allclose(result[i].data.meas, np.array({i: self._shots})) @combine(backend=BACKENDS) def test_run_2qubit(self, backend): """test for 2-qubit cases""" qc0 = QuantumCircuit(2) qc0.measure_all() qc1 = QuantumCircuit(2) qc1.x(0) qc1.measure_all() qc2 = QuantumCircuit(2) qc2.x(1) qc2.measure_all() qc3 = QuantumCircuit(2) qc3.x([0, 1]) qc3.measure_all() pm = generate_preset_pass_manager(optimization_level=0, backend=backend) qc0, qc1, qc2, qc3 = pm.run([qc0, qc1, qc2, qc3]) sampler = BackendSamplerV2(backend=backend, options=self._options) result = sampler.run([qc0, qc1, qc2, qc3], shots=self._shots).result() self.assertEqual(len(result), 4) for i in range(4): self._assert_allclose(result[i].data.meas, np.array({i: self._shots})) @combine(backend=BACKENDS) def test_run_single_circuit(self, backend): """Test for single circuit case.""" sampler = BackendSamplerV2(backend=backend, options=self._options) pm = generate_preset_pass_manager(optimization_level=0, backend=backend) with self.subTest("No parameter"): circuit, _, target = self._cases[1] circuit = pm.run(circuit) param_target = [ (None, np.array(target)), ({}, np.array(target)), ] for param, target in param_target: with self.subTest(f"{circuit.name} w/ {param}"): result = sampler.run([(circuit, param)], shots=self._shots).result() self.assertEqual(len(result), 1) self._assert_allclose(result[0].data.meas, target) with self.subTest("One parameter"): circuit = QuantumCircuit(1, 1, name="X gate") param = Parameter("x") circuit.ry(param, 0) circuit.measure(0, 0) circuit = pm.run(circuit) param_target = [ ({"x": np.pi}, np.array({1: self._shots})), ({param: np.pi}, np.array({1: self._shots})), ({"x": np.array(np.pi)}, np.array({1: self._shots})), ({param: np.array(np.pi)}, np.array({1: self._shots})), ({"x": [np.pi]}, np.array({1: self._shots})), ({param: [np.pi]}, np.array({1: self._shots})), ({"x": np.array([np.pi])}, np.array({1: self._shots})), ({param: np.array([np.pi])}, np.array({1: self._shots})), ] for param, target in param_target: with self.subTest(f"{circuit.name} w/ {param}"): result = sampler.run([(circuit, param)], shots=self._shots).result() self.assertEqual(len(result), 1) self._assert_allclose(result[0].data.c, target) with self.subTest("More than one parameter"): circuit, param, target = self._cases[3] circuit = pm.run(circuit) param_target = [ (param, np.array(target)), (tuple(param), np.array(target)), (np.array(param), np.array(target)), ((param,), np.array([target])), ([param], np.array([target])), (np.array([param]), np.array([target])), ] for param, target in param_target: with self.subTest(f"{circuit.name} w/ {param}"): result = sampler.run([(circuit, param)], shots=self._shots).result() self.assertEqual(len(result), 1) self._assert_allclose(result[0].data.meas, target) @combine(backend=BACKENDS) def test_run_reverse_meas_order(self, backend): """test for sampler with reverse measurement order""" x = Parameter("x") y = Parameter("y") qc = QuantumCircuit(3, 3) qc.rx(x, 0) qc.rx(y, 1) qc.x(2) qc.measure(0, 2) qc.measure(1, 1) qc.measure(2, 0) pm = generate_preset_pass_manager(optimization_level=0, backend=backend) qc = pm.run(qc) sampler = BackendSamplerV2(backend=backend) sampler.options.seed_simulator = self._seed result = sampler.run([(qc, [0, 0]), (qc, [np.pi / 2, 0])], shots=self._shots).result() self.assertEqual(len(result), 2) # qc({x: 0, y: 0}) self._assert_allclose(result[0].data.c, np.array({1: self._shots})) # qc({x: pi/2, y: 0}) self._assert_allclose(result[1].data.c, np.array({1: self._shots / 2, 5: self._shots / 2})) @combine(backend=BACKENDS) def test_run_errors(self, backend): """Test for errors with run method""" qc1 = QuantumCircuit(1) qc1.measure_all() qc2 = RealAmplitudes(num_qubits=1, reps=1) qc2.measure_all() pm = generate_preset_pass_manager(optimization_level=0, backend=backend) qc1, qc2 = pm.run([qc1, qc2]) sampler = BackendSamplerV2(backend=backend) with self.subTest("set parameter values to a non-parameterized circuit"): with self.assertRaises(ValueError): _ = sampler.run([(qc1, [1e2])]).result() with self.subTest("missing all parameter values for a parameterized circuit"): with self.assertRaises(ValueError): _ = sampler.run([qc2]).result() with self.assertRaises(ValueError): _ = sampler.run([(qc2, [])]).result() with self.assertRaises(ValueError): _ = sampler.run([(qc2, None)]).result() with self.subTest("missing some parameter values for a parameterized circuit"): with self.assertRaises(ValueError): _ = sampler.run([(qc2, [1e2])]).result() with self.subTest("too many parameter values for a parameterized circuit"): with self.assertRaises(ValueError): _ = sampler.run([(qc2, [1e2] * 100)]).result() with self.subTest("negative shots, run arg"): with self.assertRaises(ValueError): _ = sampler.run([qc1], shots=-1).result() with self.subTest("negative shots, pub-like"): with self.assertRaises(ValueError): _ = sampler.run([(qc1, None, -1)]).result() with self.subTest("negative shots, pub"): with self.assertRaises(ValueError): _ = sampler.run([SamplerPub(qc1, shots=-1)]).result() with self.subTest("zero shots, run arg"): with self.assertRaises(ValueError): _ = sampler.run([qc1], shots=0).result() with self.subTest("zero shots, pub-like"): with self.assertRaises(ValueError): _ = sampler.run([(qc1, None, 0)]).result() with self.subTest("zero shots, pub"): with self.assertRaises(ValueError): _ = sampler.run([SamplerPub(qc1, shots=0)]).result() with self.subTest("missing []"): with self.assertRaisesRegex(ValueError, "An invalid Sampler pub-like was given"): _ = sampler.run(qc1).result() with self.subTest("missing [] for pqc"): with self.assertRaisesRegex(ValueError, "Note that if you want to run a single pub,"): _ = sampler.run((qc2, [0, 1])).result() @combine(backend=BACKENDS) def test_run_empty_parameter(self, backend): """Test for empty parameter""" n = 5 qc = QuantumCircuit(n, n - 1) qc.measure(range(n - 1), range(n - 1)) pm = generate_preset_pass_manager(optimization_level=0, backend=backend) qc = pm.run(qc) sampler = BackendSamplerV2(backend=backend, options=self._options) with self.subTest("one circuit"): result = sampler.run([qc], shots=self._shots).result() self.assertEqual(len(result), 1) self._assert_allclose(result[0].data.c, np.array({0: self._shots})) with self.subTest("two circuits"): result = sampler.run([qc, qc], shots=self._shots).result() self.assertEqual(len(result), 2) for i in range(2): self._assert_allclose(result[i].data.c, np.array({0: self._shots})) @combine(backend=BACKENDS) def test_run_numpy_params(self, backend): """Test for numpy array as parameter values""" qc = RealAmplitudes(num_qubits=2, reps=2) qc.measure_all() pm = generate_preset_pass_manager(optimization_level=0, backend=backend) qc = pm.run(qc) k = 5 params_array = np.linspace(0, 1, k * qc.num_parameters).reshape((k, qc.num_parameters)) params_list = params_array.tolist() sampler = StatevectorSampler(seed=self._seed) target = sampler.run([(qc, params_list)], shots=self._shots).result() with self.subTest("ndarray"): sampler = BackendSamplerV2(backend=backend, options=self._options) result = sampler.run([(qc, params_array)], shots=self._shots).result() self.assertEqual(len(result), 1) self._assert_allclose(result[0].data.meas, target[0].data.meas) with self.subTest("split a list"): sampler = BackendSamplerV2(backend=backend, options=self._options) result = sampler.run( [(qc, params) for params in params_list], shots=self._shots ).result() self.assertEqual(len(result), k) for i in range(k): self._assert_allclose( result[i].data.meas, np.array(target[0].data.meas.get_int_counts(i)) ) @combine(backend=BACKENDS) def test_run_with_shots_option(self, backend): """test with shots option.""" bell, _, _ = self._cases[1] pm = generate_preset_pass_manager(optimization_level=0, backend=backend) bell = pm.run(bell) shots = 100 with self.subTest("run arg"): sampler = BackendSamplerV2(backend=backend, options=self._options) result = sampler.run([bell], shots=shots).result() self.assertEqual(len(result), 1) self.assertEqual(result[0].data.meas.num_shots, shots) self.assertEqual(sum(result[0].data.meas.get_counts().values()), shots) with self.subTest("default shots"): sampler = BackendSamplerV2(backend=backend, options=self._options) default_shots = sampler.options.default_shots result = sampler.run([bell]).result() self.assertEqual(len(result), 1) self.assertEqual(result[0].data.meas.num_shots, default_shots) self.assertEqual(sum(result[0].data.meas.get_counts().values()), default_shots) with self.subTest("setting default shots"): default_shots = 100 sampler = BackendSamplerV2(backend=backend, options=self._options) sampler.options.default_shots = default_shots self.assertEqual(sampler.options.default_shots, default_shots) result = sampler.run([bell]).result() self.assertEqual(len(result), 1) self.assertEqual(result[0].data.meas.num_shots, default_shots) self.assertEqual(sum(result[0].data.meas.get_counts().values()), default_shots) with self.subTest("pub-like"): sampler = BackendSamplerV2(backend=backend, options=self._options) result = sampler.run([(bell, None, shots)]).result() self.assertEqual(len(result), 1) self.assertEqual(result[0].data.meas.num_shots, shots) self.assertEqual(sum(result[0].data.meas.get_counts().values()), shots) with self.subTest("pub"): sampler = BackendSamplerV2(backend=backend, options=self._options) result = sampler.run([SamplerPub(bell, shots=shots)]).result() self.assertEqual(len(result), 1) self.assertEqual(result[0].data.meas.num_shots, shots) self.assertEqual(sum(result[0].data.meas.get_counts().values()), shots) with self.subTest("multiple pubs"): sampler = BackendSamplerV2(backend=backend, options=self._options) shots1 = 100 shots2 = 200 result = sampler.run( [ SamplerPub(bell, shots=shots1), SamplerPub(bell, shots=shots2), ], shots=self._shots, ).result() self.assertEqual(len(result), 2) self.assertEqual(result[0].data.meas.num_shots, shots1) self.assertEqual(sum(result[0].data.meas.get_counts().values()), shots1) self.assertEqual(result[1].data.meas.num_shots, shots2) self.assertEqual(sum(result[1].data.meas.get_counts().values()), shots2) @combine(backend=BACKENDS) def test_run_shots_result_size(self, backend): """test with shots option to validate the result size""" n = 7 # should be less than or equal to the number of qubits of backend qc = QuantumCircuit(n) qc.h(range(n)) qc.measure_all() pm = generate_preset_pass_manager(optimization_level=0, backend=backend) qc = pm.run(qc) sampler = BackendSamplerV2(backend=backend, options=self._options) result = sampler.run([qc], shots=self._shots).result() self.assertEqual(len(result), 1) self.assertLessEqual(result[0].data.meas.num_shots, self._shots) self.assertEqual(sum(result[0].data.meas.get_counts().values()), self._shots) @combine(backend=BACKENDS) def test_primitive_job_status_done(self, backend): """test primitive job's status""" bell, _, _ = self._cases[1] pm = generate_preset_pass_manager(optimization_level=0, backend=backend) bell = pm.run(bell) sampler = BackendSamplerV2(backend=backend, options=self._options) job = sampler.run([bell], shots=self._shots) _ = job.result() self.assertEqual(job.status(), JobStatus.DONE) @combine(backend=BACKENDS) def test_circuit_with_unitary(self, backend): """Test for circuit with unitary gate.""" pm = generate_preset_pass_manager(optimization_level=0, backend=backend) with self.subTest("identity"): gate = UnitaryGate(np.eye(2)) circuit = QuantumCircuit(1) circuit.append(gate, [0]) circuit.measure_all() circuit = pm.run(circuit) sampler = BackendSamplerV2(backend=backend, options=self._options) result = sampler.run([circuit], shots=self._shots).result() self.assertEqual(len(result), 1) self._assert_allclose(result[0].data.meas, np.array({0: self._shots})) with self.subTest("X"): gate = UnitaryGate([[0, 1], [1, 0]]) circuit = QuantumCircuit(1) circuit.append(gate, [0]) circuit.measure_all() circuit = pm.run(circuit) sampler = BackendSamplerV2(backend=backend, options=self._options) result = sampler.run([circuit], shots=self._shots).result() self.assertEqual(len(result), 1) self._assert_allclose(result[0].data.meas, np.array({1: self._shots})) @combine(backend=BACKENDS) def test_circuit_with_multiple_cregs(self, backend): """Test for circuit with multiple classical registers.""" pm = generate_preset_pass_manager(optimization_level=0, backend=backend) cases = [] # case 1 a = ClassicalRegister(1, "a") b = ClassicalRegister(2, "b") c = ClassicalRegister(3, "c") qc = QuantumCircuit(QuantumRegister(3), a, b, c) qc.h(range(3)) qc.measure([0, 1, 2, 2], [0, 2, 4, 5]) qc = pm.run(qc) target = {"a": {0: 5000, 1: 5000}, "b": {0: 5000, 2: 5000}, "c": {0: 5000, 6: 5000}} cases.append(("use all cregs", qc, target)) # case 2 a = ClassicalRegister(1, "a") b = ClassicalRegister(5, "b") c = ClassicalRegister(3, "c") qc = QuantumCircuit(QuantumRegister(3), a, b, c) qc.h(range(3)) qc.measure([0, 1, 2, 2], [0, 2, 4, 5]) qc = pm.run(qc) target = { "a": {0: 5000, 1: 5000}, "b": {0: 2500, 2: 2500, 24: 2500, 26: 2500}, "c": {0: 10000}, } cases.append(("use only a and b", qc, target)) # case 3 a = ClassicalRegister(1, "a") b = ClassicalRegister(2, "b") c = ClassicalRegister(3, "c") qc = QuantumCircuit(QuantumRegister(3), a, b, c) qc.h(range(3)) qc.measure(1, 5) qc = pm.run(qc) target = {"a": {0: 10000}, "b": {0: 10000}, "c": {0: 5000, 4: 5000}} cases.append(("use only c", qc, target)) # case 4 a = ClassicalRegister(1, "a") b = ClassicalRegister(2, "b") c = ClassicalRegister(3, "c") qc = QuantumCircuit(QuantumRegister(3), a, b, c) qc.h(range(3)) qc.measure([0, 1, 2], [5, 5, 5]) qc = pm.run(qc) target = {"a": {0: 10000}, "b": {0: 10000}, "c": {0: 5000, 4: 5000}} cases.append(("use only c multiple qubits", qc, target)) # case 5 a = ClassicalRegister(1, "a") b = ClassicalRegister(2, "b") c = ClassicalRegister(3, "c") qc = QuantumCircuit(QuantumRegister(3), a, b, c) qc.h(range(3)) qc = pm.run(qc) target = {"a": {0: 10000}, "b": {0: 10000}, "c": {0: 10000}} cases.append(("no measure", qc, target)) for title, qc, target in cases: with self.subTest(title): sampler = BackendSamplerV2(backend=backend, options=self._options) result = sampler.run([qc], shots=self._shots).result() self.assertEqual(len(result), 1) data = result[0].data self.assertEqual(len(data), 3) for creg in qc.cregs: self.assertTrue(hasattr(data, creg.name)) self._assert_allclose(getattr(data, creg.name), np.array(target[creg.name])) @combine(backend=BACKENDS) def test_circuit_with_aliased_cregs(self, backend): """Test for circuit with aliased classical registers.""" q = QuantumRegister(3, "q") c1 = ClassicalRegister(1, "c1") c2 = ClassicalRegister(1, "c2") qc = QuantumCircuit(q, c1, c2) qc.ry(np.pi / 4, 2) qc.cx(2, 1) qc.cx(0, 1) qc.h(0) qc.measure(0, c1) qc.measure(1, c2) qc.z(2).c_if(c1, 1) qc.x(2).c_if(c2, 1) qc2 = QuantumCircuit(5, 5) qc2.compose(qc, [0, 2, 3], [2, 4], inplace=True) cregs = [creg.name for creg in qc2.cregs] target = { cregs[0]: {0: 4255, 4: 4297, 16: 720, 20: 726}, cregs[1]: {0: 5000, 1: 5000}, cregs[2]: {0: 8500, 1: 1500}, } sampler = BackendSamplerV2(backend=backend, options=self._options) pm = generate_preset_pass_manager(optimization_level=0, backend=backend) qc2 = pm.run(qc2) result = sampler.run([qc2], shots=self._shots).result() self.assertEqual(len(result), 1) data = result[0].data self.assertEqual(len(data), 3) for creg_name, creg in target.items(): self.assertTrue(hasattr(data, creg_name)) self._assert_allclose(getattr(data, creg_name), np.array(creg)) @combine(backend=BACKENDS) def test_no_cregs(self, backend): """Test that the sampler works when there are no classical register in the circuit.""" qc = QuantumCircuit(2) sampler = BackendSamplerV2(backend=backend, options=self._options) with self.assertWarns(UserWarning): result = sampler.run([qc]).result() self.assertEqual(len(result), 1) self.assertEqual(len(result[0].data), 0) @combine(backend=BACKENDS) def test_empty_creg(self, backend): """Test that the sampler works if provided a classical register with no bits.""" # Test case for issue #12043 q = QuantumRegister(1, "q") c1 = ClassicalRegister(0, "c1") c2 = ClassicalRegister(1, "c2") qc = QuantumCircuit(q, c1, c2) qc.h(0) qc.measure(0, 0) sampler = BackendSamplerV2(backend=backend, options=self._options) result = sampler.run([qc], shots=self._shots).result() self.assertEqual(result[0].data.c1.array.shape, (self._shots, 0)) @combine(backend=BACKENDS) def test_diff_shots(self, backend): """Test of pubs with different shots""" pm = generate_preset_pass_manager(optimization_level=0, backend=backend) bell, _, target = self._cases[1] bell = pm.run(bell) sampler = BackendSamplerV2(backend=backend, options=self._options) shots2 = self._shots + 2 target2 = {k: v + 1 for k, v in target.items()} job = sampler.run([(bell, None, self._shots), (bell, None, shots2)]) result = job.result() self.assertEqual(len(result), 2) self.assertEqual(result[0].data.meas.num_shots, self._shots) self._assert_allclose(result[0].data.meas, np.array(target)) self.assertEqual(result[1].data.meas.num_shots, shots2) self._assert_allclose(result[1].data.meas, np.array(target2)) def test_job_size_limit_backend_v2(self): """Test BackendSamplerV2 respects backend's job size limit.""" class FakeBackendLimitedCircuits(GenericBackendV2): """Generic backend V2 with job size limit.""" @property def max_circuits(self): return 1 qc = QuantumCircuit(1) qc.measure_all() qc2 = QuantumCircuit(1) qc2.x(0) qc2.measure_all() sampler = BackendSamplerV2(backend=FakeBackendLimitedCircuits(num_qubits=5)) result = sampler.run([qc, qc2], shots=self._shots).result() self.assertIsInstance(result, PrimitiveResult) self.assertEqual(len(result), 2) self.assertIsInstance(result[0], PubResult) self.assertIsInstance(result[1], PubResult) self._assert_allclose(result[0].data.meas, np.array({0: self._shots})) self._assert_allclose(result[1].data.meas, np.array({1: self._shots})) def test_job_size_limit_backend_v1(self): """Test BackendSamplerV2 respects backend's job size limit.""" backend = Fake7QPulseV1() config = backend.configuration() config.max_experiments = 1 backend._configuration = config qc = QuantumCircuit(1) qc.measure_all() qc2 = QuantumCircuit(1) qc2.x(0) qc2.measure_all() sampler = BackendSamplerV2(backend=backend) result = sampler.run([qc, qc2], shots=self._shots).result() self.assertIsInstance(result, PrimitiveResult) self.assertEqual(len(result), 2) self.assertIsInstance(result[0], PubResult) self.assertIsInstance(result[1], PubResult) self._assert_allclose(result[0].data.meas, np.array({0: self._shots})) self._assert_allclose(result[1].data.meas, np.array({1: self._shots})) def test_iter_pub(self): """Test of an iterable of pubs""" backend = BasicSimulator() qc = QuantumCircuit(1) qc.measure_all() qc2 = QuantumCircuit(1) qc2.x(0) qc2.measure_all() sampler = BackendSamplerV2(backend=backend) result = sampler.run(iter([qc, qc2]), shots=self._shots).result() self.assertIsInstance(result, PrimitiveResult) self.assertEqual(len(result), 2) self.assertIsInstance(result[0], PubResult) self.assertIsInstance(result[1], PubResult) self._assert_allclose(result[0].data.meas, np.array({0: self._shots})) self._assert_allclose(result[1].data.meas, np.array({1: self._shots})) if __name__ == "__main__": unittest.main()
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2022, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for BasePrimitive.""" import json from ddt import data, ddt, unpack from numpy import array, float32, float64, int32, int64 from qiskit import QuantumCircuit, pulse, transpile from qiskit.circuit.random import random_circuit from qiskit.primitives.base.base_primitive import BasePrimitive from qiskit.primitives.utils import _circuit_key from qiskit.providers.fake_provider import FakeAlmaden from qiskit.test import QiskitTestCase @ddt class TestCircuitValidation(QiskitTestCase): """Test circuits validation logic.""" @data( (random_circuit(2, 2, seed=0), (random_circuit(2, 2, seed=0),)), ( [random_circuit(2, 2, seed=0), random_circuit(2, 2, seed=1)], (random_circuit(2, 2, seed=0), random_circuit(2, 2, seed=1)), ), ) @unpack def test_validate_circuits(self, circuits, expected): """Test circuits standardization.""" self.assertEqual(BasePrimitive._validate_circuits(circuits), expected) @data(None, "ERROR", True, 0, 1.0, 1j, [0.0]) def test_type_error(self, circuits): """Test type error if invalid input.""" with self.assertRaises(TypeError): BasePrimitive._validate_circuits(circuits) @data((), [], "") def test_value_error(self, circuits): """Test value error if no circuits are provided.""" with self.assertRaises(ValueError): BasePrimitive._validate_circuits(circuits) @ddt class TestParameterValuesValidation(QiskitTestCase): """Test parameter_values validation logic.""" @data( ((), ((),)), ([], ((),)), (0, ((0,),)), (1.2, ((1.2,),)), ((0,), ((0,),)), ([0], ((0,),)), ([1.2], ((1.2,),)), ((0, 1), ((0, 1),)), ([0, 1], ((0, 1),)), ([0, 1.2], ((0, 1.2),)), ([0.3, 1.2], ((0.3, 1.2),)), (((0, 1)), ((0, 1),)), (([0, 1]), ((0, 1),)), ([(0, 1)], ((0, 1),)), ([[0, 1]], ((0, 1),)), ([[0, 1.2]], ((0, 1.2),)), ([[0.3, 1.2]], ((0.3, 1.2),)), # Test for numpy dtypes (int32(5), ((float(int32(5)),),)), (int64(6), ((float(int64(6)),),)), (float32(3.2), ((float(float32(3.2)),),)), (float64(6.4), ((float(float64(6.4)),),)), ([int32(5), float32(3.2)], ((float(int32(5)), float(float32(3.2))),)), ) @unpack def test_validate_parameter_values(self, _parameter_values, expected): """Test parameter_values standardization.""" for parameter_values in [_parameter_values, array(_parameter_values)]: # Numpy self.assertEqual(BasePrimitive._validate_parameter_values(parameter_values), expected) self.assertEqual( BasePrimitive._validate_parameter_values(None, default=parameter_values), expected ) @data( "ERROR", ("E", "R", "R", "O", "R"), (["E", "R", "R"], ["O", "R"]), 1j, (1j,), ((1j,),), True, False, float("inf"), float("-inf"), float("nan"), ) def test_type_error(self, parameter_values): """Test type error if invalid input.""" with self.assertRaises(TypeError): BasePrimitive._validate_parameter_values(parameter_values) def test_value_error(self): """Test value error if no parameter_values or default are provided.""" with self.assertRaises(ValueError): BasePrimitive._validate_parameter_values(None) class TestCircuitKey(QiskitTestCase): """Tests for _circuit_key function""" def test_different_circuits(self): """Test collision of quantum circuits.""" with self.subTest("Ry circuit"): def test_func(n): qc = QuantumCircuit(1, 1, name="foo") qc.ry(n, 0) return qc keys = [_circuit_key(test_func(i)) for i in range(5)] self.assertEqual(len(keys), len(set(keys))) with self.subTest("pulse circuit"): def test_with_scheduling(n): custom_gate = pulse.Schedule(name="custom_x_gate") custom_gate.insert( 0, pulse.Play(pulse.Constant(160 * n, 0.1), pulse.DriveChannel(0)), inplace=True ) qc = QuantumCircuit(1) qc.x(0) qc.add_calibration("x", qubits=(0,), schedule=custom_gate) return transpile(qc, FakeAlmaden(), scheduling_method="alap") keys = [_circuit_key(test_with_scheduling(i)) for i in range(1, 5)] self.assertEqual(len(keys), len(set(keys))) def test_circuit_key_controlflow(self): """Test for a circuit with control flow.""" qc = QuantumCircuit(2, 1) with qc.for_loop(range(5)): qc.h(0) qc.cx(0, 1) qc.measure(0, 0) qc.break_loop().c_if(0, True) self.assertIsInstance(hash(_circuit_key(qc)), int) self.assertIsInstance(json.dumps(_circuit_key(qc)), str)
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2022, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for Sampler.""" import unittest import numpy as np from qiskit import QuantumCircuit from qiskit.circuit import Parameter from qiskit.circuit.library import RealAmplitudes from qiskit.exceptions import QiskitError from qiskit.extensions.unitary import UnitaryGate from qiskit.primitives import Sampler, SamplerResult from qiskit.providers import JobStatus, JobV1 from qiskit.test import QiskitTestCase class TestSampler(QiskitTestCase): """Test Sampler""" def setUp(self): super().setUp() hadamard = QuantumCircuit(1, 1, name="Hadamard") hadamard.h(0) hadamard.measure(0, 0) bell = QuantumCircuit(2, name="Bell") bell.h(0) bell.cx(0, 1) bell.measure_all() self._circuit = [hadamard, bell] self._target = [ {0: 0.5, 1: 0.5}, {0: 0.5, 3: 0.5, 1: 0, 2: 0}, ] self._pqc = RealAmplitudes(num_qubits=2, reps=2) self._pqc.measure_all() self._pqc2 = RealAmplitudes(num_qubits=2, reps=3) self._pqc2.measure_all() self._pqc_params = [[0.0] * 6, [1.0] * 6] self._pqc_target = [{0: 1}, {0: 0.0148, 1: 0.3449, 2: 0.0531, 3: 0.5872}] self._theta = [ [0, 1, 1, 2, 3, 5], [1, 2, 3, 4, 5, 6], [0, 1, 2, 3, 4, 5, 6, 7], ] def _generate_circuits_target(self, indices): if isinstance(indices, list): circuits = [self._circuit[j] for j in indices] target = [self._target[j] for j in indices] else: raise ValueError(f"invalid index {indices}") return circuits, target def _generate_params_target(self, indices): if isinstance(indices, int): params = self._pqc_params[indices] target = self._pqc_target[indices] elif isinstance(indices, list): params = [self._pqc_params[j] for j in indices] target = [self._pqc_target[j] for j in indices] else: raise ValueError(f"invalid index {indices}") return params, target def _compare_probs(self, prob, target): if not isinstance(prob, list): prob = [prob] if not isinstance(target, list): target = [target] self.assertEqual(len(prob), len(target)) for p, targ in zip(prob, target): for key, t_val in targ.items(): if key in p: self.assertAlmostEqual(p[key], t_val, places=1) else: self.assertAlmostEqual(t_val, 0, places=1) def test_sampler_run(self): """Test Sampler.run().""" bell = self._circuit[1] sampler = Sampler() job = sampler.run(circuits=[bell]) self.assertIsInstance(job, JobV1) result = job.result() self.assertIsInstance(result, SamplerResult) # print([q.binary_probabilities() for q in result.quasi_dists]) self._compare_probs(result.quasi_dists, self._target[1]) def test_sample_run_multiple_circuits(self): """Test Sampler.run() with multiple circuits.""" # executes three Bell circuits # Argument `parameters` is optional. bell = self._circuit[1] sampler = Sampler() result = sampler.run([bell, bell, bell]).result() # print([q.binary_probabilities() for q in result.quasi_dists]) self._compare_probs(result.quasi_dists[0], self._target[1]) self._compare_probs(result.quasi_dists[1], self._target[1]) self._compare_probs(result.quasi_dists[2], self._target[1]) def test_sampler_run_with_parameterized_circuits(self): """Test Sampler.run() with parameterized circuits.""" # parameterized circuit pqc = self._pqc pqc2 = self._pqc2 theta1, theta2, theta3 = self._theta sampler = Sampler() result = sampler.run([pqc, pqc, pqc2], [theta1, theta2, theta3]).result() # result of pqc(theta1) prob1 = { "00": 0.1309248462975777, "01": 0.3608720796028448, "10": 0.09324865232050054, "11": 0.41495442177907715, } self.assertDictAlmostEqual(result.quasi_dists[0].binary_probabilities(), prob1) # result of pqc(theta2) prob2 = { "00": 0.06282290651933871, "01": 0.02877144385576705, "10": 0.606654494132085, "11": 0.3017511554928094, } self.assertDictAlmostEqual(result.quasi_dists[1].binary_probabilities(), prob2) # result of pqc2(theta3) prob3 = { "00": 0.1880263994380416, "01": 0.6881971261189544, "10": 0.09326232720582443, "11": 0.030514147237179892, } self.assertDictAlmostEqual(result.quasi_dists[2].binary_probabilities(), prob3) def test_run_1qubit(self): """test for 1-qubit cases""" qc = QuantumCircuit(1) qc.measure_all() qc2 = QuantumCircuit(1) qc2.x(0) qc2.measure_all() sampler = Sampler() result = sampler.run([qc, qc2]).result() self.assertIsInstance(result, SamplerResult) self.assertEqual(len(result.quasi_dists), 2) for i in range(2): keys, values = zip(*sorted(result.quasi_dists[i].items())) self.assertTupleEqual(keys, (i,)) np.testing.assert_allclose(values, [1]) def test_run_2qubit(self): """test for 2-qubit cases""" qc0 = QuantumCircuit(2) qc0.measure_all() qc1 = QuantumCircuit(2) qc1.x(0) qc1.measure_all() qc2 = QuantumCircuit(2) qc2.x(1) qc2.measure_all() qc3 = QuantumCircuit(2) qc3.x([0, 1]) qc3.measure_all() sampler = Sampler() result = sampler.run([qc0, qc1, qc2, qc3]).result() self.assertIsInstance(result, SamplerResult) self.assertEqual(len(result.quasi_dists), 4) for i in range(4): keys, values = zip(*sorted(result.quasi_dists[i].items())) self.assertTupleEqual(keys, (i,)) np.testing.assert_allclose(values, [1]) def test_run_single_circuit(self): """Test for single circuit case.""" sampler = Sampler() with self.subTest("No parameter"): circuit = self._circuit[1] target = self._target[1] param_vals = [None, [], [[]], np.array([]), np.array([[]])] for val in param_vals: with self.subTest(f"{circuit.name} w/ {val}"): result = sampler.run(circuit, val).result() self._compare_probs(result.quasi_dists, target) self.assertEqual(len(result.metadata), 1) with self.subTest("One parameter"): circuit = QuantumCircuit(1, 1, name="X gate") param = Parameter("x") circuit.ry(param, 0) circuit.measure(0, 0) target = [{1: 1}] param_vals = [ [np.pi], [[np.pi]], np.array([np.pi]), np.array([[np.pi]]), [np.array([np.pi])], ] for val in param_vals: with self.subTest(f"{circuit.name} w/ {val}"): result = sampler.run(circuit, val).result() self._compare_probs(result.quasi_dists, target) self.assertEqual(len(result.metadata), 1) with self.subTest("More than one parameter"): circuit = self._pqc target = [self._pqc_target[0]] param_vals = [ self._pqc_params[0], [self._pqc_params[0]], np.array(self._pqc_params[0]), np.array([self._pqc_params[0]]), [np.array(self._pqc_params[0])], ] for val in param_vals: with self.subTest(f"{circuit.name} w/ {val}"): result = sampler.run(circuit, val).result() self._compare_probs(result.quasi_dists, target) self.assertEqual(len(result.metadata), 1) def test_run_reverse_meas_order(self): """test for sampler with reverse measurement order""" x = Parameter("x") y = Parameter("y") qc = QuantumCircuit(3, 3) qc.rx(x, 0) qc.rx(y, 1) qc.x(2) qc.measure(0, 2) qc.measure(1, 1) qc.measure(2, 0) sampler = Sampler() result = sampler.run([qc] * 2, [[0, 0], [np.pi / 2, 0]]).result() self.assertIsInstance(result, SamplerResult) self.assertEqual(len(result.quasi_dists), 2) # qc({x: 0, y: 0}) keys, values = zip(*sorted(result.quasi_dists[0].items())) self.assertTupleEqual(keys, (1,)) np.testing.assert_allclose(values, [1]) # qc({x: pi/2, y: 0}) keys, values = zip(*sorted(result.quasi_dists[1].items())) self.assertTupleEqual(keys, (1, 5)) np.testing.assert_allclose(values, [0.5, 0.5]) def test_run_errors(self): """Test for errors with run method""" qc1 = QuantumCircuit(1) qc1.measure_all() qc2 = RealAmplitudes(num_qubits=1, reps=1) qc2.measure_all() qc3 = QuantumCircuit(1) qc4 = QuantumCircuit(1, 1) sampler = Sampler() with self.subTest("set parameter values to a non-parameterized circuit"): with self.assertRaises(ValueError): _ = sampler.run([qc1], [[1e2]]) with self.subTest("missing all parameter values for a parameterized circuit"): with self.assertRaises(ValueError): _ = sampler.run([qc2], [[]]) with self.subTest("missing some parameter values for a parameterized circuit"): with self.assertRaises(ValueError): _ = sampler.run([qc2], [[1e2]]) with self.subTest("too many parameter values for a parameterized circuit"): with self.assertRaises(ValueError): _ = sampler.run([qc2], [[1e2]] * 100) with self.subTest("no classical bits"): with self.assertRaises(ValueError): _ = sampler.run([qc3], [[]]) with self.subTest("no measurement"): with self.assertRaises(QiskitError): # The following raises QiskitError because this check is located in # `Sampler._preprocess_circuit` _ = sampler.run([qc4], [[]]) def test_run_empty_parameter(self): """Test for empty parameter""" n = 5 qc = QuantumCircuit(n, n - 1) qc.measure(range(n - 1), range(n - 1)) sampler = Sampler() with self.subTest("one circuit"): result = sampler.run([qc], shots=1000).result() self.assertEqual(len(result.quasi_dists), 1) for q_d in result.quasi_dists: quasi_dist = {k: v for k, v in q_d.items() if v != 0.0} self.assertDictEqual(quasi_dist, {0: 1.0}) self.assertEqual(len(result.metadata), 1) with self.subTest("two circuits"): result = sampler.run([qc, qc], shots=1000).result() self.assertEqual(len(result.quasi_dists), 2) for q_d in result.quasi_dists: quasi_dist = {k: v for k, v in q_d.items() if v != 0.0} self.assertDictEqual(quasi_dist, {0: 1.0}) self.assertEqual(len(result.metadata), 2) def test_run_numpy_params(self): """Test for numpy array as parameter values""" qc = RealAmplitudes(num_qubits=2, reps=2) qc.measure_all() k = 5 params_array = np.random.rand(k, qc.num_parameters) params_list = params_array.tolist() params_list_array = list(params_array) sampler = Sampler() target = sampler.run([qc] * k, params_list).result() with self.subTest("ndarrary"): result = sampler.run([qc] * k, params_array).result() self.assertEqual(len(result.metadata), k) for i in range(k): self.assertDictEqual(result.quasi_dists[i], target.quasi_dists[i]) with self.subTest("list of ndarray"): result = sampler.run([qc] * k, params_list_array).result() self.assertEqual(len(result.metadata), k) for i in range(k): self.assertDictEqual(result.quasi_dists[i], target.quasi_dists[i]) def test_run_with_shots_option(self): """test with shots option.""" params, target = self._generate_params_target([1]) sampler = Sampler() result = sampler.run( circuits=[self._pqc], parameter_values=params, shots=1024, seed=15 ).result() self._compare_probs(result.quasi_dists, target) def test_run_with_shots_option_none(self): """test with shots=None option. Seed is ignored then.""" sampler = Sampler() result_42 = sampler.run( [self._pqc], parameter_values=[[0, 1, 1, 2, 3, 5]], shots=None, seed=42 ).result() result_15 = sampler.run( [self._pqc], parameter_values=[[0, 1, 1, 2, 3, 5]], shots=None, seed=15 ).result() self.assertDictAlmostEqual(result_42.quasi_dists, result_15.quasi_dists) def test_run_shots_result_size(self): """test with shots option to validate the result size""" n = 10 shots = 100 qc = QuantumCircuit(n) qc.h(range(n)) qc.measure_all() sampler = Sampler() result = sampler.run(qc, [], shots=shots, seed=42).result() self.assertEqual(len(result.quasi_dists), 1) self.assertLessEqual(len(result.quasi_dists[0]), shots) self.assertAlmostEqual(sum(result.quasi_dists[0].values()), 1.0) def test_primitive_job_status_done(self): """test primitive job's status""" bell = self._circuit[1] sampler = Sampler() job = sampler.run(circuits=[bell]) _ = job.result() self.assertEqual(job.status(), JobStatus.DONE) def test_options(self): """Test for options""" with self.subTest("init"): sampler = Sampler(options={"shots": 3000}) self.assertEqual(sampler.options.get("shots"), 3000) with self.subTest("set_options"): sampler.set_options(shots=1024, seed=15) self.assertEqual(sampler.options.get("shots"), 1024) self.assertEqual(sampler.options.get("seed"), 15) with self.subTest("run"): params, target = self._generate_params_target([1]) result = sampler.run([self._pqc], parameter_values=params).result() self._compare_probs(result.quasi_dists, target) self.assertEqual(result.quasi_dists[0].shots, 1024) def test_circuit_with_unitary(self): """Test for circuit with unitary gate.""" gate = UnitaryGate(np.eye(2)) circuit = QuantumCircuit(1) circuit.append(gate, [0]) circuit.measure_all() sampler = Sampler() sampler_result = sampler.run([circuit]).result() self.assertDictAlmostEqual(sampler_result.quasi_dists[0], {0: 1, 1: 0}) if __name__ == "__main__": unittest.main()
https://github.com/swe-train/qiskit__qiskit
swe-train
# 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. """Tests for Statevector Sampler.""" from __future__ import annotations import unittest import numpy as np from numpy.typing import NDArray from qiskit import ClassicalRegister, QiskitError, QuantumCircuit, QuantumRegister from qiskit.circuit import Parameter from qiskit.circuit.library import RealAmplitudes, UnitaryGate from qiskit.primitives import PrimitiveResult, PubResult from qiskit.primitives.containers import BitArray from qiskit.primitives.containers.data_bin import DataBin from qiskit.primitives.containers.sampler_pub import SamplerPub from qiskit.primitives.statevector_sampler import StatevectorSampler from qiskit.providers import JobStatus from test import QiskitTestCase # pylint: disable=wrong-import-order class TestStatevectorSampler(QiskitTestCase): """Test for StatevectorSampler""" def setUp(self): super().setUp() self._shots = 10000 self._seed = 123 self._cases = [] hadamard = QuantumCircuit(1, 1, name="Hadamard") hadamard.h(0) hadamard.measure(0, 0) self._cases.append((hadamard, None, {0: 5000, 1: 5000})) # case 0 bell = QuantumCircuit(2, name="Bell") bell.h(0) bell.cx(0, 1) bell.measure_all() self._cases.append((bell, None, {0: 5000, 3: 5000})) # case 1 pqc = RealAmplitudes(num_qubits=2, reps=2) pqc.measure_all() self._cases.append((pqc, [0] * 6, {0: 10000})) # case 2 self._cases.append((pqc, [1] * 6, {0: 168, 1: 3389, 2: 470, 3: 5973})) # case 3 self._cases.append((pqc, [0, 1, 1, 2, 3, 5], {0: 1339, 1: 3534, 2: 912, 3: 4215})) # case 4 self._cases.append((pqc, [1, 2, 3, 4, 5, 6], {0: 634, 1: 291, 2: 6039, 3: 3036})) # case 5 pqc2 = RealAmplitudes(num_qubits=2, reps=3) pqc2.measure_all() self._cases.append( (pqc2, [0, 1, 2, 3, 4, 5, 6, 7], {0: 1898, 1: 6864, 2: 928, 3: 311}) ) # case 6 def _assert_allclose(self, bitarray: BitArray, target: NDArray | BitArray, rtol=1e-1): self.assertEqual(bitarray.shape, target.shape) for idx in np.ndindex(bitarray.shape): int_counts = bitarray.get_int_counts(idx) target_counts = ( target.get_int_counts(idx) if isinstance(target, BitArray) else target[idx] ) max_key = max(max(int_counts.keys()), max(target_counts.keys())) ary = np.array([int_counts.get(i, 0) for i in range(max_key + 1)]) tgt = np.array([target_counts.get(i, 0) for i in range(max_key + 1)]) np.testing.assert_allclose(ary, tgt, rtol=rtol, err_msg=f"index: {idx}") def test_sampler_run(self): """Test run().""" with self.subTest("single"): bell, _, target = self._cases[1] sampler = StatevectorSampler(seed=self._seed) job = sampler.run([bell], shots=self._shots) result = job.result() self.assertIsInstance(result, PrimitiveResult) self.assertIsInstance(result.metadata, dict) self.assertEqual(len(result), 1) self.assertIsInstance(result[0], PubResult) self.assertIsInstance(result[0].data, DataBin) self.assertIsInstance(result[0].data.meas, BitArray) self._assert_allclose(result[0].data.meas, np.array(target)) with self.subTest("single with param"): pqc, param_vals, target = self._cases[2] sampler = StatevectorSampler(seed=self._seed) params = (param.name for param in pqc.parameters) job = sampler.run([(pqc, {params: param_vals})], shots=self._shots) result = job.result() self.assertIsInstance(result, PrimitiveResult) self.assertIsInstance(result.metadata, dict) self.assertEqual(len(result), 1) self.assertIsInstance(result[0], PubResult) self.assertIsInstance(result[0].data, DataBin) self.assertIsInstance(result[0].data.meas, BitArray) self._assert_allclose(result[0].data.meas, np.array(target)) with self.subTest("multiple"): pqc, param_vals, target = self._cases[2] sampler = StatevectorSampler(seed=self._seed) params = (param.name for param in pqc.parameters) job = sampler.run( [(pqc, {params: [param_vals, param_vals, param_vals]})], shots=self._shots ) result = job.result() self.assertIsInstance(result, PrimitiveResult) self.assertIsInstance(result.metadata, dict) self.assertEqual(len(result), 1) self.assertIsInstance(result[0], PubResult) self.assertIsInstance(result[0].data, DataBin) self.assertIsInstance(result[0].data.meas, BitArray) self._assert_allclose(result[0].data.meas, np.array([target, target, target])) def test_sampler_run_multiple_times(self): """Test run() returns the same results if the same input is given.""" bell, _, _ = self._cases[1] sampler = StatevectorSampler(seed=self._seed) result1 = sampler.run([bell], shots=self._shots).result() meas1 = result1[0].data.meas result2 = sampler.run([bell], shots=self._shots).result() meas2 = result2[0].data.meas self._assert_allclose(meas1, meas2, rtol=0) def test_sample_run_multiple_circuits(self): """Test run() with multiple circuits.""" bell, _, target = self._cases[1] sampler = StatevectorSampler(seed=self._seed) result = sampler.run([bell, bell, bell], shots=self._shots).result() self.assertEqual(len(result), 3) self._assert_allclose(result[0].data.meas, np.array(target)) self._assert_allclose(result[1].data.meas, np.array(target)) self._assert_allclose(result[2].data.meas, np.array(target)) def test_sampler_run_with_parameterized_circuits(self): """Test run() with parameterized circuits.""" pqc1, param1, target1 = self._cases[4] pqc2, param2, target2 = self._cases[5] pqc3, param3, target3 = self._cases[6] sampler = StatevectorSampler(seed=self._seed) result = sampler.run( [(pqc1, param1), (pqc2, param2), (pqc3, param3)], shots=self._shots ).result() self.assertEqual(len(result), 3) self._assert_allclose(result[0].data.meas, np.array(target1)) self._assert_allclose(result[1].data.meas, np.array(target2)) self._assert_allclose(result[2].data.meas, np.array(target3)) def test_run_1qubit(self): """test for 1-qubit cases""" qc = QuantumCircuit(1) qc.measure_all() qc2 = QuantumCircuit(1) qc2.x(0) qc2.measure_all() sampler = StatevectorSampler(seed=self._seed) result = sampler.run([qc, qc2], shots=self._shots).result() self.assertEqual(len(result), 2) for i in range(2): self._assert_allclose(result[i].data.meas, np.array({i: self._shots})) def test_run_2qubit(self): """test for 2-qubit cases""" qc0 = QuantumCircuit(2) qc0.measure_all() qc1 = QuantumCircuit(2) qc1.x(0) qc1.measure_all() qc2 = QuantumCircuit(2) qc2.x(1) qc2.measure_all() qc3 = QuantumCircuit(2) qc3.x([0, 1]) qc3.measure_all() sampler = StatevectorSampler(seed=self._seed) result = sampler.run([qc0, qc1, qc2, qc3], shots=self._shots).result() self.assertEqual(len(result), 4) for i in range(4): self._assert_allclose(result[i].data.meas, np.array({i: self._shots})) def test_run_single_circuit(self): """Test for single circuit case.""" with self.subTest("No parameter"): circuit, _, target = self._cases[1] param_target = [ (None, np.array(target)), ({}, np.array(target)), ] for param, target in param_target: with self.subTest(f"{circuit.name} w/ {param}"): sampler = StatevectorSampler(seed=self._seed) result = sampler.run([(circuit, param)], shots=self._shots).result() self.assertEqual(len(result), 1) self._assert_allclose(result[0].data.meas, target) with self.subTest("One parameter"): circuit = QuantumCircuit(1, 1, name="X gate") param = Parameter("x") circuit.ry(param, 0) circuit.measure(0, 0) param_target = [ ({"x": np.pi}, np.array({1: self._shots})), ({param: np.pi}, np.array({1: self._shots})), ({"x": np.array(np.pi)}, np.array({1: self._shots})), ({param: np.array(np.pi)}, np.array({1: self._shots})), ({"x": [np.pi]}, np.array({1: self._shots})), ({param: [np.pi]}, np.array({1: self._shots})), ({"x": np.array([np.pi])}, np.array({1: self._shots})), ({param: np.array([np.pi])}, np.array({1: self._shots})), ] for param, target in param_target: with self.subTest(f"{circuit.name} w/ {param}"): sampler = StatevectorSampler(seed=self._seed) result = sampler.run([(circuit, param)], shots=self._shots).result() self.assertEqual(len(result), 1) self._assert_allclose(result[0].data.c, target) with self.subTest("More than one parameter"): circuit, param, target = self._cases[3] param_target = [ (param, np.array(target)), (tuple(param), np.array(target)), (np.array(param), np.array(target)), ((param,), np.array([target])), ([param], np.array([target])), (np.array([param]), np.array([target])), ] for param, target in param_target: with self.subTest(f"{circuit.name} w/ {param}"): sampler = StatevectorSampler(seed=self._seed) result = sampler.run([(circuit, param)], shots=self._shots).result() self.assertEqual(len(result), 1) self._assert_allclose(result[0].data.meas, target) def test_run_reverse_meas_order(self): """test for sampler with reverse measurement order""" x = Parameter("x") y = Parameter("y") qc = QuantumCircuit(3, 3) qc.rx(x, 0) qc.rx(y, 1) qc.x(2) qc.measure(0, 2) qc.measure(1, 1) qc.measure(2, 0) sampler = StatevectorSampler(seed=self._seed) result = sampler.run([(qc, [0, 0]), (qc, [np.pi / 2, 0])], shots=self._shots).result() self.assertEqual(len(result), 2) # qc({x: 0, y: 0}) self._assert_allclose(result[0].data.c, np.array({1: self._shots})) # qc({x: pi/2, y: 0}) self._assert_allclose(result[1].data.c, np.array({1: self._shots / 2, 5: self._shots / 2})) def test_run_errors(self): """Test for errors with run method""" qc1 = QuantumCircuit(1) qc1.measure_all() qc2 = RealAmplitudes(num_qubits=1, reps=1) qc2.measure_all() qc3 = QuantumCircuit(1, 1) with qc3.for_loop(range(5)): qc3.h(0) sampler = StatevectorSampler() with self.subTest("set parameter values to a non-parameterized circuit"): with self.assertRaises(ValueError): _ = sampler.run([(qc1, [1e2])]).result() with self.subTest("missing all parameter values for a parameterized circuit"): with self.assertRaises(ValueError): _ = sampler.run([qc2]).result() with self.assertRaises(ValueError): _ = sampler.run([(qc2, [])]).result() with self.assertRaises(ValueError): _ = sampler.run([(qc2, None)]).result() with self.subTest("missing some parameter values for a parameterized circuit"): with self.assertRaises(ValueError): _ = sampler.run([(qc2, [1e2])]).result() with self.subTest("too many parameter values for a parameterized circuit"): with self.assertRaises(ValueError): _ = sampler.run([(qc2, [1e2] * 100)]).result() with self.subTest("with control flow"): with self.assertRaises(QiskitError): _ = sampler.run([qc3]).result() with self.subTest("negative shots, run arg"): with self.assertRaises(ValueError): _ = sampler.run([qc1], shots=-1).result() with self.subTest("negative shots, pub-like"): with self.assertRaises(ValueError): _ = sampler.run([(qc1, None, -1)]).result() with self.subTest("negative shots, pub"): with self.assertRaises(ValueError): _ = sampler.run([SamplerPub(qc1, shots=-1)]).result() with self.subTest("zero shots, run arg"): with self.assertRaises(ValueError): _ = sampler.run([qc1], shots=0).result() with self.subTest("zero shots, pub-like"): with self.assertRaises(ValueError): _ = sampler.run([(qc1, None, 0)]).result() with self.subTest("zero shots, pub"): with self.assertRaises(ValueError): _ = sampler.run([SamplerPub(qc1, shots=0)]).result() with self.subTest("missing []"): with self.assertRaisesRegex(ValueError, "An invalid Sampler pub-like was given"): _ = sampler.run(qc1).result() with self.subTest("missing [] for pqc"): with self.assertRaisesRegex(ValueError, "Note that if you want to run a single pub,"): _ = sampler.run((qc2, [0, 1])).result() def test_run_empty_parameter(self): """Test for empty parameter""" n = 5 qc = QuantumCircuit(n, n - 1) qc.measure(range(n - 1), range(n - 1)) sampler = StatevectorSampler(seed=self._seed) with self.subTest("one circuit"): result = sampler.run([qc], shots=self._shots).result() self.assertEqual(len(result), 1) self._assert_allclose(result[0].data.c, np.array({0: self._shots})) with self.subTest("two circuits"): result = sampler.run([qc, qc], shots=self._shots).result() self.assertEqual(len(result), 2) for i in range(2): self._assert_allclose(result[i].data.c, np.array({0: self._shots})) def test_run_numpy_params(self): """Test for numpy array as parameter values""" qc = RealAmplitudes(num_qubits=2, reps=2) qc.measure_all() k = 5 params_array = np.linspace(0, 1, k * qc.num_parameters).reshape((k, qc.num_parameters)) params_list = params_array.tolist() sampler = StatevectorSampler(seed=self._seed) target = sampler.run([(qc, params_list)], shots=self._shots).result() with self.subTest("ndarray"): sampler = StatevectorSampler(seed=self._seed) result = sampler.run([(qc, params_array)], shots=self._shots).result() self.assertEqual(len(result), 1) self._assert_allclose(result[0].data.meas, target[0].data.meas) with self.subTest("split a list"): sampler = StatevectorSampler(seed=self._seed) result = sampler.run( [(qc, params) for params in params_list], shots=self._shots ).result() self.assertEqual(len(result), k) for i in range(k): self._assert_allclose( result[i].data.meas, np.array(target[0].data.meas.get_int_counts(i)) ) def test_run_with_shots_option(self): """test with shots option.""" bell, _, _ = self._cases[1] shots = 100 with self.subTest("run arg"): sampler = StatevectorSampler(seed=self._seed) result = sampler.run([bell], shots=shots).result() self.assertEqual(len(result), 1) self.assertEqual(result[0].data.meas.num_shots, shots) self.assertEqual(sum(result[0].data.meas.get_counts().values()), shots) self.assertIn("shots", result[0].metadata) self.assertEqual(result[0].metadata["shots"], shots) with self.subTest("default shots"): sampler = StatevectorSampler(seed=self._seed) default_shots = sampler.default_shots result = sampler.run([bell]).result() self.assertEqual(len(result), 1) self.assertEqual(result[0].data.meas.num_shots, default_shots) self.assertEqual(sum(result[0].data.meas.get_counts().values()), default_shots) self.assertIn("shots", result[0].metadata) self.assertEqual(result[0].metadata["shots"], default_shots) with self.subTest("setting default shots"): default_shots = 100 sampler = StatevectorSampler(default_shots=default_shots, seed=self._seed) self.assertEqual(sampler.default_shots, default_shots) result = sampler.run([bell]).result() self.assertEqual(len(result), 1) self.assertEqual(result[0].data.meas.num_shots, default_shots) self.assertEqual(sum(result[0].data.meas.get_counts().values()), default_shots) self.assertIn("shots", result[0].metadata) self.assertEqual(result[0].metadata["shots"], default_shots) with self.subTest("pub-like"): sampler = StatevectorSampler(seed=self._seed) result = sampler.run([(bell, None, shots)]).result() self.assertEqual(len(result), 1) self.assertEqual(result[0].data.meas.num_shots, shots) self.assertEqual(sum(result[0].data.meas.get_counts().values()), shots) self.assertIn("shots", result[0].metadata) self.assertEqual(result[0].metadata["shots"], shots) with self.subTest("pub"): sampler = StatevectorSampler(seed=self._seed) result = sampler.run([SamplerPub(bell, shots=shots)]).result() self.assertEqual(len(result), 1) self.assertEqual(result[0].data.meas.num_shots, shots) self.assertEqual(sum(result[0].data.meas.get_counts().values()), shots) self.assertIn("shots", result[0].metadata) self.assertEqual(result[0].metadata["shots"], shots) with self.subTest("multiple pubs"): sampler = StatevectorSampler(seed=self._seed) shots1 = 100 shots2 = 200 result = sampler.run( [ SamplerPub(bell, shots=shots1), SamplerPub(bell, shots=shots2), ], shots=self._shots, ).result() self.assertEqual(len(result), 2) self.assertEqual(result[0].data.meas.num_shots, shots1) self.assertEqual(sum(result[0].data.meas.get_counts().values()), shots1) self.assertIn("shots", result[0].metadata) self.assertEqual(result[0].metadata["shots"], shots1) self.assertEqual(result[1].data.meas.num_shots, shots2) self.assertEqual(sum(result[1].data.meas.get_counts().values()), shots2) self.assertIn("shots", result[1].metadata) self.assertEqual(result[1].metadata["shots"], shots2) def test_run_shots_result_size(self): """test with shots option to validate the result size""" n = 10 qc = QuantumCircuit(n) qc.h(range(n)) qc.measure_all() sampler = StatevectorSampler(seed=self._seed) result = sampler.run([qc], shots=self._shots).result() self.assertEqual(len(result), 1) self.assertLessEqual(result[0].data.meas.num_shots, self._shots) self.assertEqual(sum(result[0].data.meas.get_counts().values()), self._shots) def test_primitive_job_status_done(self): """test primitive job's status""" bell, _, _ = self._cases[1] sampler = StatevectorSampler(seed=self._seed) job = sampler.run([bell], shots=self._shots) _ = job.result() self.assertEqual(job.status(), JobStatus.DONE) def test_seed(self): """Test for seed options""" with self.subTest("empty"): sampler = StatevectorSampler() self.assertIsNone(sampler.seed) with self.subTest("set int"): sampler = StatevectorSampler(seed=self._seed) self.assertEqual(sampler.seed, self._seed) with self.subTest("set generator"): sampler = StatevectorSampler(seed=np.random.default_rng(self._seed)) self.assertIsInstance(sampler.seed, np.random.Generator) def test_circuit_with_unitary(self): """Test for circuit with unitary gate.""" with self.subTest("identity"): gate = UnitaryGate(np.eye(2)) circuit = QuantumCircuit(1) circuit.append(gate, [0]) circuit.measure_all() sampler = StatevectorSampler(seed=self._seed) result = sampler.run([circuit], shots=self._shots).result() self.assertEqual(len(result), 1) self._assert_allclose(result[0].data.meas, np.array({0: self._shots})) with self.subTest("X"): gate = UnitaryGate([[0, 1], [1, 0]]) circuit = QuantumCircuit(1) circuit.append(gate, [0]) circuit.measure_all() sampler = StatevectorSampler(seed=self._seed) result = sampler.run([circuit], shots=self._shots).result() self.assertEqual(len(result), 1) self._assert_allclose(result[0].data.meas, np.array({1: self._shots})) def test_circuit_with_multiple_cregs(self): """Test for circuit with multiple classical registers.""" cases = [] # case 1 a = ClassicalRegister(1, "a") b = ClassicalRegister(2, "b") c = ClassicalRegister(3, "c") qc = QuantumCircuit(QuantumRegister(3), a, b, c) qc.h(range(3)) qc.measure([0, 1, 2, 2], [0, 2, 4, 5]) target = {"a": {0: 5000, 1: 5000}, "b": {0: 5000, 2: 5000}, "c": {0: 5000, 6: 5000}} cases.append(("use all cregs", qc, target)) # case 2 a = ClassicalRegister(1, "a") b = ClassicalRegister(5, "b") c = ClassicalRegister(3, "c") qc = QuantumCircuit(QuantumRegister(3), a, b, c) qc.h(range(3)) qc.measure([0, 1, 2, 2], [0, 2, 4, 5]) target = { "a": {0: 5000, 1: 5000}, "b": {0: 2500, 2: 2500, 24: 2500, 26: 2500}, "c": {0: 10000}, } cases.append(("use only a and b", qc, target)) # case 3 a = ClassicalRegister(1, "a") b = ClassicalRegister(2, "b") c = ClassicalRegister(3, "c") qc = QuantumCircuit(QuantumRegister(3), a, b, c) qc.h(range(3)) qc.measure(1, 5) target = {"a": {0: 10000}, "b": {0: 10000}, "c": {0: 5000, 4: 5000}} cases.append(("use only c", qc, target)) # case 4 a = ClassicalRegister(1, "a") b = ClassicalRegister(2, "b") c = ClassicalRegister(3, "c") qc = QuantumCircuit(QuantumRegister(3), a, b, c) qc.h(range(3)) qc.measure([0, 1, 2], [5, 5, 5]) target = {"a": {0: 10000}, "b": {0: 10000}, "c": {0: 5000, 4: 5000}} cases.append(("use only c multiple qubits", qc, target)) # case 5 a = ClassicalRegister(1, "a") b = ClassicalRegister(2, "b") c = ClassicalRegister(3, "c") qc = QuantumCircuit(QuantumRegister(3), a, b, c) qc.h(range(3)) target = {"a": {0: 10000}, "b": {0: 10000}, "c": {0: 10000}} cases.append(("no measure", qc, target)) for title, qc, target in cases: with self.subTest(title): sampler = StatevectorSampler(seed=self._seed) result = sampler.run([qc], shots=self._shots).result() self.assertEqual(len(result), 1) data = result[0].data self.assertEqual(len(data), 3) for creg in qc.cregs: self.assertTrue(hasattr(data, creg.name)) self._assert_allclose(getattr(data, creg.name), np.array(target[creg.name])) def test_circuit_with_aliased_cregs(self): """Test for circuit with aliased classical registers.""" q = QuantumRegister(3, "q") c1 = ClassicalRegister(1, "c1") c2 = ClassicalRegister(1, "c2") qc = QuantumCircuit(q, c1, c2) qc.ry(np.pi / 4, 2) qc.cx(2, 1) qc.cx(0, 1) qc.h(0) qc.measure(0, c1) qc.measure(1, c2) qc.z(2).c_if(c1, 1) qc.x(2).c_if(c2, 1) qc2 = QuantumCircuit(5, 5) qc2.compose(qc, [0, 2, 3], [2, 4], inplace=True) cregs = [creg.name for creg in qc2.cregs] target = { cregs[0]: {0: 4255, 4: 4297, 16: 720, 20: 726}, cregs[1]: {0: 5000, 1: 5000}, cregs[2]: {0: 8500, 1: 1500}, } sampler = StatevectorSampler(seed=self._seed) result = sampler.run([qc2], shots=self._shots).result() self.assertEqual(len(result), 1) data = result[0].data self.assertEqual(len(data), 3) for creg_name, creg in target.items(): self.assertTrue(hasattr(data, creg_name)) self._assert_allclose(getattr(data, creg_name), np.array(creg)) def test_no_cregs(self): """Test that the sampler works when there are no classical register in the circuit.""" qc = QuantumCircuit(2) sampler = StatevectorSampler() with self.assertWarns(UserWarning): result = sampler.run([qc]).result() self.assertEqual(len(result), 1) self.assertEqual(len(result[0].data), 0) def test_iter_pub(self): """Test of an iterable of pubs""" qc = QuantumCircuit(1) qc.measure_all() qc2 = QuantumCircuit(1) qc2.x(0) qc2.measure_all() sampler = StatevectorSampler() result = sampler.run(iter([qc, qc2]), shots=self._shots).result() self.assertIsInstance(result, PrimitiveResult) self.assertEqual(len(result), 2) self.assertIsInstance(result[0], PubResult) self.assertIsInstance(result[1], PubResult) self._assert_allclose(result[0].data.meas, np.array({0: self._shots})) self._assert_allclose(result[1].data.meas, np.array({1: self._shots})) if __name__ == "__main__": unittest.main()
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for visualization tools.""" import unittest import numpy as np from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.circuit import Qubit, Clbit from qiskit.visualization.circuit import _utils from qiskit.visualization import array_to_latex from qiskit.test import QiskitTestCase from qiskit.utils import optionals class TestVisualizationUtils(QiskitTestCase): """Tests for circuit drawer utilities.""" def setUp(self): super().setUp() self.qr1 = QuantumRegister(2, "qr1") self.qr2 = QuantumRegister(2, "qr2") self.cr1 = ClassicalRegister(2, "cr1") self.cr2 = ClassicalRegister(2, "cr2") self.circuit = QuantumCircuit(self.qr1, self.qr2, self.cr1, self.cr2) self.circuit.cx(self.qr2[0], self.qr2[1]) self.circuit.measure(self.qr2[0], self.cr2[0]) self.circuit.cx(self.qr2[1], self.qr2[0]) self.circuit.measure(self.qr2[1], self.cr2[1]) self.circuit.cx(self.qr1[0], self.qr1[1]) self.circuit.measure(self.qr1[0], self.cr1[0]) self.circuit.cx(self.qr1[1], self.qr1[0]) self.circuit.measure(self.qr1[1], self.cr1[1]) def test_get_layered_instructions(self): """_get_layered_instructions without reverse_bits""" (qregs, cregs, layered_ops) = _utils._get_layered_instructions(self.circuit) exp = [ [("cx", (self.qr2[0], self.qr2[1]), ()), ("cx", (self.qr1[0], self.qr1[1]), ())], [("measure", (self.qr2[0],), (self.cr2[0],))], [("measure", (self.qr1[0],), (self.cr1[0],))], [("cx", (self.qr2[1], self.qr2[0]), ()), ("cx", (self.qr1[1], self.qr1[0]), ())], [("measure", (self.qr2[1],), (self.cr2[1],))], [("measure", (self.qr1[1],), (self.cr1[1],))], ] self.assertEqual([self.qr1[0], self.qr1[1], self.qr2[0], self.qr2[1]], qregs) self.assertEqual([self.cr1[0], self.cr1[1], self.cr2[0], self.cr2[1]], cregs) self.assertEqual( exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops] ) def test_get_layered_instructions_reverse_bits(self): """_get_layered_instructions with reverse_bits=True""" (qregs, cregs, layered_ops) = _utils._get_layered_instructions( self.circuit, reverse_bits=True ) exp = [ [("cx", (self.qr2[0], self.qr2[1]), ()), ("cx", (self.qr1[0], self.qr1[1]), ())], [("measure", (self.qr2[0],), (self.cr2[0],))], [("measure", (self.qr1[0],), (self.cr1[0],)), ("cx", (self.qr2[1], self.qr2[0]), ())], [("cx", (self.qr1[1], self.qr1[0]), ())], [("measure", (self.qr2[1],), (self.cr2[1],))], [("measure", (self.qr1[1],), (self.cr1[1],))], ] self.assertEqual([self.qr2[1], self.qr2[0], self.qr1[1], self.qr1[0]], qregs) self.assertEqual([self.cr2[1], self.cr2[0], self.cr1[1], self.cr1[0]], cregs) self.assertEqual( exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops] ) def test_get_layered_instructions_remove_idle_wires(self): """_get_layered_instructions with idle_wires=False""" qr1 = QuantumRegister(3, "qr1") qr2 = QuantumRegister(3, "qr2") cr1 = ClassicalRegister(3, "cr1") cr2 = ClassicalRegister(3, "cr2") circuit = QuantumCircuit(qr1, qr2, cr1, cr2) circuit.cx(qr2[0], qr2[1]) circuit.measure(qr2[0], cr2[0]) circuit.cx(qr2[1], qr2[0]) circuit.measure(qr2[1], cr2[1]) circuit.cx(qr1[0], qr1[1]) circuit.measure(qr1[0], cr1[0]) circuit.cx(qr1[1], qr1[0]) circuit.measure(qr1[1], cr1[1]) (qregs, cregs, layered_ops) = _utils._get_layered_instructions(circuit, idle_wires=False) exp = [ [("cx", (qr2[0], qr2[1]), ()), ("cx", (qr1[0], qr1[1]), ())], [("measure", (qr2[0],), (cr2[0],))], [("measure", (qr1[0],), (cr1[0],))], [("cx", (qr2[1], qr2[0]), ()), ("cx", (qr1[1], qr1[0]), ())], [("measure", (qr2[1],), (cr2[1],))], [("measure", (qr1[1],), (cr1[1],))], ] self.assertEqual([qr1[0], qr1[1], qr2[0], qr2[1]], qregs) self.assertEqual([cr1[0], cr1[1], cr2[0], cr2[1]], cregs) self.assertEqual( exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops] ) def test_get_layered_instructions_left_justification_simple(self): """Test _get_layered_instructions left justification simple since #2802 q_0: |0>───────■── ┌───┐ │ q_1: |0>┤ H ├──┼── ├───┤ │ q_2: |0>┤ H ├──┼── └───┘┌─┴─┐ q_3: |0>─────┤ X ├ └───┘ """ qc = QuantumCircuit(4) qc.h(1) qc.h(2) qc.cx(0, 3) (_, _, layered_ops) = _utils._get_layered_instructions(qc, justify="left") l_exp = [ [ ("h", (Qubit(QuantumRegister(4, "q"), 1),), ()), ("h", (Qubit(QuantumRegister(4, "q"), 2),), ()), ], [("cx", (Qubit(QuantumRegister(4, "q"), 0), Qubit(QuantumRegister(4, "q"), 3)), ())], ] self.assertEqual( l_exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops] ) def test_get_layered_instructions_right_justification_simple(self): """Test _get_layered_instructions right justification simple since #2802 q_0: |0>──■─────── │ ┌───┐ q_1: |0>──┼──┤ H ├ │ ├───┤ q_2: |0>──┼──┤ H ├ ┌─┴─┐└───┘ q_3: |0>┤ X ├───── └───┘ """ qc = QuantumCircuit(4) qc.h(1) qc.h(2) qc.cx(0, 3) (_, _, layered_ops) = _utils._get_layered_instructions(qc, justify="right") r_exp = [ [("cx", (Qubit(QuantumRegister(4, "q"), 0), Qubit(QuantumRegister(4, "q"), 3)), ())], [ ("h", (Qubit(QuantumRegister(4, "q"), 1),), ()), ("h", (Qubit(QuantumRegister(4, "q"), 2),), ()), ], ] self.assertEqual( r_exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops] ) def test_get_layered_instructions_left_justification_less_simple(self): """Test _get_layered_instructions left justification less simple example since #2802 ┌────────────┐┌───┐┌────────────┐ ┌─┐┌────────────┐┌───┐┌────────────┐ q_0: |0>┤ U2(0,pi/1) ├┤ X ├┤ U2(0,pi/1) ├──────────────┤M├┤ U2(0,pi/1) ├┤ X ├┤ U2(0,pi/1) ├ ├────────────┤└─┬─┘├────────────┤┌────────────┐└╥┘└────────────┘└─┬─┘├────────────┤ q_1: |0>┤ U2(0,pi/1) ├──■──┤ U2(0,pi/1) ├┤ U2(0,pi/1) ├─╫─────────────────■──┤ U2(0,pi/1) ├ └────────────┘ └────────────┘└────────────┘ ║ └────────────┘ q_2: |0>────────────────────────────────────────────────╫────────────────────────────────── ║ q_3: |0>────────────────────────────────────────────────╫────────────────────────────────── ║ q_4: |0>────────────────────────────────────────────────╫────────────────────────────────── ║ c1_0: 0 ════════════════════════════════════════════════╩══════════════════════════════════ """ qasm = """ OPENQASM 2.0; include "qelib1.inc"; qreg q[5]; creg c1[1]; u2(0,3.14159265358979) q[0]; u2(0,3.14159265358979) q[1]; cx q[1],q[0]; u2(0,3.14159265358979) q[0]; u2(0,3.14159265358979) q[1]; u2(0,3.14159265358979) q[1]; measure q[0] -> c1[0]; u2(0,3.14159265358979) q[0]; cx q[1],q[0]; u2(0,3.14159265358979) q[0]; u2(0,3.14159265358979) q[1]; """ qc = QuantumCircuit.from_qasm_str(qasm) (_, _, layered_ops) = _utils._get_layered_instructions(qc, justify="left") l_exp = [ [ ("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()), ("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()), ], [("cx", (Qubit(QuantumRegister(5, "q"), 1), Qubit(QuantumRegister(5, "q"), 0)), ())], [ ("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()), ("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()), ], [("u2", (Qubit(QuantumRegister(5, "q"), 1),), ())], [ ( "measure", (Qubit(QuantumRegister(5, "q"), 0),), (Clbit(ClassicalRegister(1, "c1"), 0),), ) ], [("u2", (Qubit(QuantumRegister(5, "q"), 0),), ())], [("cx", (Qubit(QuantumRegister(5, "q"), 1), Qubit(QuantumRegister(5, "q"), 0)), ())], [ ("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()), ("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()), ], ] self.assertEqual( l_exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops] ) def test_get_layered_instructions_right_justification_less_simple(self): """Test _get_layered_instructions right justification less simple example since #2802 ┌────────────┐┌───┐┌────────────┐┌─┐┌────────────┐┌───┐┌────────────┐ q_0: |0>┤ U2(0,pi/1) ├┤ X ├┤ U2(0,pi/1) ├┤M├┤ U2(0,pi/1) ├┤ X ├┤ U2(0,pi/1) ├ ├────────────┤└─┬─┘├────────────┤└╥┘├────────────┤└─┬─┘├────────────┤ q_1: |0>┤ U2(0,pi/1) ├──■──┤ U2(0,pi/1) ├─╫─┤ U2(0,pi/1) ├──■──┤ U2(0,pi/1) ├ └────────────┘ └────────────┘ ║ └────────────┘ └────────────┘ q_2: |0>──────────────────────────────────╫────────────────────────────────── ║ q_3: |0>──────────────────────────────────╫────────────────────────────────── ║ q_4: |0>──────────────────────────────────╫────────────────────────────────── ║ c1_0: 0 ══════════════════════════════════╩══════════════════════════════════ """ qasm = """ OPENQASM 2.0; include "qelib1.inc"; qreg q[5]; creg c1[1]; u2(0,3.14159265358979) q[0]; u2(0,3.14159265358979) q[1]; cx q[1],q[0]; u2(0,3.14159265358979) q[0]; u2(0,3.14159265358979) q[1]; u2(0,3.14159265358979) q[1]; measure q[0] -> c1[0]; u2(0,3.14159265358979) q[0]; cx q[1],q[0]; u2(0,3.14159265358979) q[0]; u2(0,3.14159265358979) q[1]; """ qc = QuantumCircuit.from_qasm_str(qasm) (_, _, layered_ops) = _utils._get_layered_instructions(qc, justify="right") r_exp = [ [ ("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()), ("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()), ], [("cx", (Qubit(QuantumRegister(5, "q"), 1), Qubit(QuantumRegister(5, "q"), 0)), ())], [ ("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()), ("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()), ], [ ( "measure", (Qubit(QuantumRegister(5, "q"), 0),), (Clbit(ClassicalRegister(1, "c1"), 0),), ) ], [ ("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()), ("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()), ], [("cx", (Qubit(QuantumRegister(5, "q"), 1), Qubit(QuantumRegister(5, "q"), 0)), ())], [ ("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()), ("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()), ], ] self.assertEqual( r_exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops] ) def test_get_layered_instructions_op_with_cargs(self): """Test _get_layered_instructions op with cargs right of measure ┌───┐┌─┐ q_0: |0>┤ H ├┤M├───────────── └───┘└╥┘┌───────────┐ q_1: |0>──────╫─┤0 ├ ║ │ add_circ │ c_0: 0 ══════╩═╡0 ╞ └───────────┘ c_1: 0 ═════════════════════ """ qc = QuantumCircuit(2, 2) qc.h(0) qc.measure(0, 0) qc_2 = QuantumCircuit(1, 1, name="add_circ") qc_2.h(0).c_if(qc_2.cregs[0], 1) qc_2.measure(0, 0) qc.append(qc_2, [1], [0]) (_, _, layered_ops) = _utils._get_layered_instructions(qc) expected = [ [("h", (Qubit(QuantumRegister(2, "q"), 0),), ())], [ ( "measure", (Qubit(QuantumRegister(2, "q"), 0),), (Clbit(ClassicalRegister(2, "c"), 0),), ) ], [ ( "add_circ", (Qubit(QuantumRegister(2, "q"), 1),), (Clbit(ClassicalRegister(2, "c"), 0),), ) ], ] self.assertEqual( expected, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops] ) @unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc") def test_generate_latex_label_nomathmode(self): """Test generate latex label default.""" self.assertEqual("abc", _utils.generate_latex_label("abc")) @unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc") def test_generate_latex_label_nomathmode_utf8char(self): """Test generate latex label utf8 characters.""" self.assertEqual( "{\\ensuremath{\\iiint}}X{\\ensuremath{\\forall}}Y", _utils.generate_latex_label("∭X∀Y"), ) @unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc") def test_generate_latex_label_mathmode_utf8char(self): """Test generate latex label mathtext with utf8.""" self.assertEqual( "abc_{\\ensuremath{\\iiint}}X{\\ensuremath{\\forall}}Y", _utils.generate_latex_label("$abc_$∭X∀Y"), ) @unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc") def test_generate_latex_label_mathmode_underscore_outside(self): """Test generate latex label with underscore outside mathmode.""" self.assertEqual( "abc_{\\ensuremath{\\iiint}}X{\\ensuremath{\\forall}}Y", _utils.generate_latex_label("$abc$_∭X∀Y"), ) @unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc") def test_generate_latex_label_escaped_dollar_signs(self): """Test generate latex label with escaped dollarsign.""" self.assertEqual("${\\ensuremath{\\forall}}$", _utils.generate_latex_label(r"\$∀\$")) @unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc") def test_generate_latex_label_escaped_dollar_sign_in_mathmode(self): """Test generate latex label with escaped dollar sign in mathmode.""" self.assertEqual( "a$bc_{\\ensuremath{\\iiint}}X{\\ensuremath{\\forall}}Y", _utils.generate_latex_label(r"$a$bc$_∭X∀Y"), ) def test_array_to_latex(self): """Test array_to_latex produces correct latex string""" matrix = [ [np.sqrt(1 / 2), 1 / 16, 1 / np.sqrt(8) + 3j, -0.5 + 0.5j], [1 / 3 - 1 / 3j, np.sqrt(1 / 2) * 1j, 34.3210, -9 / 2], ] matrix = np.array(matrix) exp_str = ( "\\begin{bmatrix}\\frac{\\sqrt{2}}{2}&\\frac{1}{16}&" "\\frac{\\sqrt{2}}{4}+3i&-\\frac{1}{2}+\\frac{i}{2}\\\\" "\\frac{1}{3}+\\frac{i}{3}&\\frac{\\sqrt{2}i}{2}&34.321&-" "\\frac{9}{2}\\\\\\end{bmatrix}" ) result = array_to_latex(matrix, source=True).replace(" ", "").replace("\n", "") self.assertEqual(exp_str, result) if __name__ == "__main__": unittest.main(verbosity=2)
https://github.com/swe-train/qiskit__qiskit
swe-train
# 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. """Test ObservablesArray""" import itertools as it import ddt import numpy as np import qiskit.quantum_info as qi from qiskit.primitives.containers.observables_array import ObservablesArray from test import QiskitTestCase # pylint: disable=wrong-import-order @ddt.ddt class ObservablesArrayTestCase(QiskitTestCase): """Test the ObservablesArray class""" @ddt.data(0, 1, 2) def test_coerce_observable_str(self, num_qubits): """Test coerce_observable for allowed basis str input""" for chars in it.permutations(ObservablesArray.ALLOWED_BASIS, num_qubits): label = "".join(chars) obs = ObservablesArray.coerce_observable(label) self.assertEqual(obs, {label: 1}) def test_coerce_observable_custom_basis(self): """Test coerce_observable for custom al flowed basis""" class PauliArray(ObservablesArray): """Custom array allowing only Paulis, not projectors""" ALLOWED_BASIS = "IXYZ" with self.assertRaises(ValueError): PauliArray.coerce_observable("0101") for p in qi.pauli_basis(1): obs = PauliArray.coerce_observable(p) self.assertEqual(obs, {p.to_label(): 1}) @ddt.data("iXX", "012", "+/-") def test_coerce_observable_invalid_str(self, basis): """Test coerce_observable for Pauli input""" with self.assertRaises(ValueError): ObservablesArray.coerce_observable(basis) @ddt.data(1, 2, 3) def test_coerce_observable_pauli(self, num_qubits): """Test coerce_observable for Pauli input""" for p in qi.pauli_basis(num_qubits): obs = ObservablesArray.coerce_observable(p) self.assertEqual(obs, {p.to_label(): 1}) @ddt.data(0, 1, 2, 3) def test_coerce_observable_phased_pauli(self, phase): """Test coerce_observable for phased Pauli input""" pauli = qi.Pauli("IXYZ") pauli.phase = phase coeff = (-1j) ** phase if phase % 2: with self.assertRaises(ValueError): ObservablesArray.coerce_observable(pauli) else: obs = ObservablesArray.coerce_observable(pauli) self.assertIsInstance(obs, dict) self.assertEqual(list(obs.keys()), ["IXYZ"]) np.testing.assert_allclose( list(obs.values()), [coeff], err_msg=f"Wrong value for Pauli {pauli}" ) @ddt.data("+IXYZ", "-IXYZ", "iIXYZ", "+iIXYZ", "-IXYZ") def test_coerce_observable_phased_pauli_str(self, pauli): """Test coerce_observable for phased Pauli input""" pauli = qi.Pauli(pauli) coeff = (-1j) ** pauli.phase if pauli.phase % 2: with self.assertRaises(ValueError): ObservablesArray.coerce_observable(pauli) else: obs = ObservablesArray.coerce_observable(pauli) self.assertIsInstance(obs, dict) self.assertEqual(list(obs.keys()), ["IXYZ"]) np.testing.assert_allclose( list(obs.values()), [coeff], err_msg=f"Wrong value for Pauli {pauli}" ) def test_coerce_observable_signed_sparse_pauli_op(self): """Test coerce_observable for SparsePauliOp input with phase paulis""" op = qi.SparsePauliOp(["+I", "-X", "Y", "-Z"], [1, 2, 3, 4]) obs = ObservablesArray.coerce_observable(op) self.assertIsInstance(obs, dict) self.assertEqual(len(obs), 4) self.assertEqual(sorted(obs.keys()), sorted(["I", "X", "Y", "Z"])) np.testing.assert_allclose([obs[i] for i in ["I", "X", "Y", "Z"]], [1, -2, 3, -4]) def test_coerce_observable_zero_sparse_pauli_op(self): """Test coerce_observable for SparsePauliOp input with zero val coeffs""" op = qi.SparsePauliOp(["I", "X", "Y", "Z"], [0, 0, 0, 1]) obs = ObservablesArray.coerce_observable(op) self.assertIsInstance(obs, dict) self.assertEqual(len(obs), 1) self.assertEqual(sorted(obs.keys()), ["Z"]) self.assertEqual(obs["Z"], 1) def test_coerce_observable_duplicate_sparse_pauli_op(self): """Test coerce_observable for SparsePauliOp wiht duplicate paulis""" op = qi.SparsePauliOp(["XX", "-XX", "XX", "-XX"], [2, 1, 3, 2]) obs = ObservablesArray.coerce_observable(op) self.assertIsInstance(obs, dict) self.assertEqual(len(obs), 1) self.assertEqual(list(obs.keys()), ["XX"]) self.assertEqual(obs["XX"], 2) def test_coerce_observable_pauli_mapping(self): """Test coerce_observable for pauli-keyed Mapping input""" mapping = dict(zip(qi.pauli_basis(1), range(1, 5))) obs = ObservablesArray.coerce_observable(mapping) target = {key.to_label(): val for key, val in mapping.items()} self.assertEqual(obs, target) def test_coerce_0d(self): """Test the coerce() method with 0-d input.""" obs = ObservablesArray.coerce("X") self.assertEqual(obs.shape, ()) self.assertDictAlmostEqual(obs[()], {"X": 1}) obs = ObservablesArray.coerce({"I": 2}) self.assertEqual(obs.shape, ()) self.assertDictAlmostEqual(obs[()], {"I": 2}) obs = ObservablesArray.coerce(qi.SparsePauliOp(["X", "Y"], [1, 3])) self.assertEqual(obs.shape, ()) self.assertDictAlmostEqual(obs[()], {"X": 1, "Y": 3}) def test_format_invalid_mapping_qubits(self): """Test an error is raised when different qubits in mapping keys""" mapping = {"IX": 1, "XXX": 2} with self.assertRaises(ValueError): ObservablesArray.coerce_observable(mapping) def test_format_invalid_mapping_basis(self): """Test an error is raised when keys contain invalid characters""" mapping = {"XX": 1, "0Z": 2, "02": 3} with self.assertRaises(ValueError): ObservablesArray.coerce_observable(mapping) def test_init_nested_list_str(self): """Test init with nested lists of str""" obj = [["X", "Y", "Z"], ["0", "1", "+"]] obs = ObservablesArray(obj) self.assertEqual(obs.size, 6) self.assertEqual(obs.shape, (2, 3)) def test_init_nested_list_sparse_pauli_op(self): """Test init with nested lists of SparsePauliOp""" obj = [ [qi.SparsePauliOp(qi.random_pauli_list(2, 3, phase=False)) for _ in range(3)] for _ in range(5) ] obs = ObservablesArray(obj) self.assertEqual(obs.size, 15) self.assertEqual(obs.shape, (5, 3)) def test_init_single_sparse_pauli_op(self): """Test init with single SparsePauliOps""" obj = qi.SparsePauliOp(qi.random_pauli_list(2, 3, phase=False)) obs = ObservablesArray(obj) self.assertEqual(obs.size, 1) self.assertEqual(obs.shape, ()) def test_init_pauli_list(self): """Test init with PauliList""" obs = ObservablesArray(qi.pauli_basis(2)) self.assertEqual(obs.size, 16) self.assertEqual(obs.shape, (16,)) def test_init_nested_pauli_list(self): """Test init with nested PauliList""" obj = [qi.random_pauli_list(2, 3, phase=False) for _ in range(5)] obs = ObservablesArray(obj) self.assertEqual(obs.size, 15) self.assertEqual(obs.shape, (5, 3)) def test_init_ragged_array(self): """Test init with ragged input""" obj = [["X", "Y"], ["X", "Y", "Z"]] with self.assertRaises(ValueError): ObservablesArray(obj) def test_init_validate_false(self): """Test init validate kwarg""" obj = [["A", "B", "C"], ["D", "E", "F"]] obs = ObservablesArray(obj, validate=False) self.assertEqual(obs.shape, (2, 3)) self.assertEqual(obs.size, 6) for i in range(2): for j in range(3): self.assertEqual(obs[i, j], obj[i][j]) def test_init_validate_true(self): """Test init validate kwarg""" obj = [["A", "B", "C"], ["D", "E", "F"]] with self.assertRaises(ValueError): ObservablesArray(obj, validate=True) @ddt.data(0, 1, 2, 3) def test_size_and_shape_single(self, ndim): """Test size and shape method for size=1 array""" obs = {"XX": 1} for _ in range(ndim): obs = [obs] arr = ObservablesArray(obs, validate=False) self.assertEqual(arr.size, 1, msg="Incorrect ObservablesArray.size") self.assertEqual(arr.shape, (1,) * ndim, msg="Incorrect ObservablesArray.shape") @ddt.data(0, 1, 2, 3) def test_tolist_single(self, ndim): """Test tolist method for size=1 array""" obs = {"XX": 1} for _ in range(ndim): obs = [obs] arr = ObservablesArray(obs, validate=False) ls = arr.tolist() self.assertEqual(ls, obs) @ddt.data(0, 1, 2, 3) def test_array_single(self, ndim): """Test __array__ method for size=1 array""" obs = {"XX": 1} for _ in range(ndim): obs = [obs] arr = ObservablesArray(obs, validate=False) nparr = np.array(arr) self.assertEqual(nparr.dtype, object) self.assertEqual(nparr.shape, arr.shape) self.assertEqual(nparr.size, arr.size) self.assertTrue(np.all(nparr == np.array(obs))) @ddt.data(0, 1, 2, 3) def test_getitem_single(self, ndim): """Test __getitem__ method for size=1 array""" base_obs = {"XX": 1} obs = base_obs for _ in range(ndim): obs = [obs] arr = ObservablesArray(obs, validate=False) idx = ndim * (0,) item = arr[idx] self.assertEqual(item, base_obs) def test_tolist_1d(self): """Test tolist method""" obj = ["A", "B", "C", "D"] obs = ObservablesArray(obj, validate=False) self.assertEqual(obs.tolist(), obj) def test_tolist_2d(self): """Test tolist method""" obj = [["A", "B", "C"], ["D", "E", "F"]] obs = ObservablesArray(obj, validate=False) self.assertEqual(obs.tolist(), obj) def test_array_1d(self): """Test __array__ dunder method""" obj = np.array(["A", "B", "C", "D"], dtype=object) obs = ObservablesArray(obj, validate=False) self.assertTrue(np.all(np.array(obs) == obj)) def test_array_2d(self): """Test __array__ dunder method""" obj = np.array([["A", "B", "C"], ["D", "E", "F"]], dtype=object) obs = ObservablesArray(obj, validate=False) self.assertTrue(np.all(np.array(obs) == obj)) def test_getitem_1d(self): """Test __getitem__ for 1D array""" obj = np.array(["A", "B", "C", "D"], dtype=object) obs = ObservablesArray(obj, validate=False) for i in range(obj.size): self.assertEqual(obs[i], obj[i]) def test_getitem_2d(self): """Test __getitem__ for 2D array""" obj = np.array([["A", "B", "C"], ["D", "E", "F"]], dtype=object) obs = ObservablesArray(obj, validate=False) for i in range(obj.shape[0]): row = obs[i] self.assertIsInstance(row, ObservablesArray) self.assertEqual(row.shape, (3,)) self.assertTrue(np.all(np.array(row) == obj[i])) def test_ravel(self): """Test ravel method""" bases_flat = qi.pauli_basis(2).to_labels() bases = [bases_flat[4 * i : 4 * (i + 1)] for i in range(4)] obs = ObservablesArray(bases) flat = obs.ravel() self.assertEqual(flat.ndim, 1) self.assertEqual(flat.shape, (16,)) self.assertEqual(flat.size, 16) for ( i, label, ) in enumerate(bases_flat): self.assertEqual(flat[i], {label: 1}) def test_reshape(self): """Test reshape method""" bases = qi.pauli_basis(2) labels = np.array(bases.to_labels(), dtype=object) obs = ObservablesArray(qi.pauli_basis(2)) def various_formats(shape): # call reshape with a single argument yield [shape] yield [(-1,) + shape[1:]] yield [np.array(shape)] yield [list(shape)] yield [list(map(np.int64, shape))] yield [tuple(map(np.int64, shape))] # call reshape with multiple arguments yield shape yield np.array(shape) yield list(shape) yield list(map(np.int64, shape)) yield tuple(map(np.int64, shape)) for shape in [(16,), (4, 4), (2, 4, 2), (2, 2, 2, 2), (1, 8, 1, 2)]: with self.subTest(shape): for input_shape in various_formats(shape): obs_rs = obs.reshape(*input_shape) self.assertEqual(obs_rs.shape, shape) labels_rs = labels.reshape(shape) for idx in np.ndindex(shape): self.assertEqual( obs_rs[idx], {labels_rs[idx]: 1}, msg=f"failed for shape {shape} with input format {input_shape}", ) def test_validate(self): """Test the validate method""" ObservablesArray({"XX": 1}).validate() ObservablesArray([{"XX": 1}] * 5).validate() ObservablesArray([{"XX": 1}] * 15).reshape((3, 5)).validate() obs = ObservablesArray([{"XX": 1}, {"XYZ": 1}], validate=False) with self.assertRaisesRegex(ValueError, "number of qubits must be the same"): obs.validate()
https://github.com/swe-train/qiskit__qiskit
swe-train
# 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. """BasicProvider provider integration tests.""" import unittest from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, transpile from qiskit.result import Result from qiskit.providers.basic_provider import BasicProviderError, BasicSimulator from test import QiskitTestCase # pylint: disable=wrong-import-order class TestBasicProviderIntegration(QiskitTestCase): """Qiskit BasicProvider simulator integration tests.""" def setUp(self): super().setUp() qr = QuantumRegister(1) cr = ClassicalRegister(1) self._qc1 = QuantumCircuit(qr, cr, name="qc1") self._qc2 = QuantumCircuit(qr, cr, name="qc2") self._qc1.measure(qr[0], cr[0]) self.backend = BasicSimulator() self._result1 = self.backend.run(transpile(self._qc1)).result() def test_builtin_simulator_result_fields(self): """Test components of a result from a local simulator.""" self.assertEqual("basic_simulator", self._result1.backend_name) self.assertIsInstance(self._result1.job_id, str) self.assertEqual(self._result1.status, "COMPLETED") self.assertEqual(self._result1.results[0].status, "DONE") def test_basicprovider_execute(self): """Test Compiler and run.""" qubit_reg = QuantumRegister(2, name="q") clbit_reg = ClassicalRegister(2, name="c") qc = QuantumCircuit(qubit_reg, clbit_reg, name="bell") qc.h(qubit_reg[0]) qc.cx(qubit_reg[0], qubit_reg[1]) qc.measure(qubit_reg, clbit_reg) job = self.backend.run(qc) result = job.result() self.assertIsInstance(result, Result) def test_basicprovider_execute_two(self): """Test Compiler and run.""" qubit_reg = QuantumRegister(2, name="q") clbit_reg = ClassicalRegister(2, name="c") qc = QuantumCircuit(qubit_reg, clbit_reg, name="bell") qc.h(qubit_reg[0]) qc.cx(qubit_reg[0], qubit_reg[1]) qc.measure(qubit_reg, clbit_reg) qc_extra = QuantumCircuit(qubit_reg, clbit_reg, name="extra") qc_extra.measure(qubit_reg, clbit_reg) job = self.backend.run([qc, qc_extra]) result = job.result() self.assertIsInstance(result, Result) def test_basicprovider_num_qubits(self): """Test BasicProviderError is raised if num_qubits too large to simulate.""" qc = QuantumCircuit(50, 1) qc.x(0) qc.measure(0, 0) with self.assertRaises(BasicProviderError): self.backend.run(qc) if __name__ == "__main__": unittest.main(verbosity=2)
https://github.com/swe-train/qiskit__qiskit
swe-train
# 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. """Test basic simulator.""" import os import unittest import numpy as np from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister from qiskit.compiler import transpile, assemble from qiskit.providers.basic_provider import BasicSimulator from qiskit.qasm2 import dumps from test import QiskitTestCase # pylint: disable=wrong-import-order from . import BasicProviderBackendTestMixin class TestBasicSimulator(QiskitTestCase, BasicProviderBackendTestMixin): """Test the basic provider simulator.""" def setUp(self): super().setUp() self.backend = BasicSimulator() bell = QuantumCircuit(2, 2) bell.h(0) bell.cx(0, 1) bell.measure([0, 1], [0, 1]) self.circuit = bell self.seed = 88 self.backend = BasicSimulator() qasm_dir = os.path.join( os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), "qasm" ) qasm_filename = os.path.join(qasm_dir, "example.qasm") qcirc = QuantumCircuit.from_qasm_file(qasm_filename) qcirc.name = "test" self.transpiled_circuit = transpile(qcirc, backend=self.backend) self.qobj = assemble(self.transpiled_circuit, shots=1000, seed_simulator=self.seed) def test_basic_simulator_single_shot(self): """Test single shot run.""" shots = 1 result = self.backend.run( self.transpiled_circuit, shots=shots, seed_simulator=self.seed ).result() self.assertEqual(result.success, True) def test_measure_sampler_repeated_qubits(self): """Test measure sampler if qubits measured more than once.""" shots = 100 qr = QuantumRegister(2, "qr") cr = ClassicalRegister(4, "cr") circuit = QuantumCircuit(qr, cr) circuit.x(qr[1]) circuit.measure(qr[0], cr[0]) circuit.measure(qr[1], cr[1]) circuit.measure(qr[1], cr[2]) circuit.measure(qr[0], cr[3]) target = {"0110": shots} job = self.backend.run( transpile(circuit, self.backend), shots=shots, seed_simulator=self.seed ) result = job.result() counts = result.get_counts(0) self.assertEqual(counts, target) def test_measure_sampler_single_qubit(self): """Test measure sampler if single-qubit is measured.""" shots = 100 num_qubits = 5 qr = QuantumRegister(num_qubits, "qr") cr = ClassicalRegister(1, "cr") for qubit in range(num_qubits): circuit = QuantumCircuit(qr, cr) circuit.x(qr[qubit]) circuit.measure(qr[qubit], cr[0]) target = {"1": shots} job = self.backend.run( transpile(circuit, self.backend), shots=shots, seed_simulator=self.seed ) result = job.result() counts = result.get_counts(0) self.assertEqual(counts, target) def test_measure_sampler_partial_qubit(self): """Test measure sampler if single-qubit is measured.""" shots = 100 num_qubits = 5 qr = QuantumRegister(num_qubits, "qr") cr = ClassicalRegister(4, "cr") # ░ ░ ░ ┌─┐ ░ # qr_0: ──────░─────░─────░─┤M├─░──── # ┌───┐ ░ ░ ┌─┐ ░ └╥┘ ░ # qr_1: ┤ X ├─░─────░─┤M├─░──╫──░──── # └───┘ ░ ░ └╥┘ ░ ║ ░ # qr_2: ──────░─────░──╫──░──╫──░──── # ┌───┐ ░ ┌─┐ ░ ║ ░ ║ ░ ┌─┐ # qr_3: ┤ X ├─░─┤M├─░──╫──░──╫──░─┤M├ # └───┘ ░ └╥┘ ░ ║ ░ ║ ░ └╥┘ # qr_4: ──────░──╫──░──╫──░──╫──░──╫─ # ░ ║ ░ ║ ░ ║ ░ ║ # cr: 4/═════════╩═════╩═════╩═════╩═ # 1 0 2 3 circuit = QuantumCircuit(qr, cr) circuit.x(qr[3]) circuit.x(qr[1]) circuit.barrier(qr) circuit.measure(qr[3], cr[1]) circuit.barrier(qr) circuit.measure(qr[1], cr[0]) circuit.barrier(qr) circuit.measure(qr[0], cr[2]) circuit.barrier(qr) circuit.measure(qr[3], cr[3]) target = {"1011": shots} job = self.backend.run( transpile(circuit, self.backend), shots=shots, seed_simulator=self.seed ) result = job.result() counts = result.get_counts(0) self.assertEqual(counts, target) def test_basic_simulator(self): """Test data counts output for single circuit run against reference.""" result = self.backend.run( self.transpiled_circuit, shots=1000, seed_simulator=self.seed ).result() shots = 1024 threshold = 0.04 * shots counts = result.get_counts("test") target = { "100 100": shots / 8, "011 011": shots / 8, "101 101": shots / 8, "111 111": shots / 8, "000 000": shots / 8, "010 010": shots / 8, "110 110": shots / 8, "001 001": shots / 8, } self.assertDictAlmostEqual(counts, target, threshold) def test_if_statement(self): """Test if statements.""" shots = 100 qr = QuantumRegister(3, "qr") cr = ClassicalRegister(3, "cr") # ┌───┐┌─┐ ┌─┐ # qr_0: ┤ X ├┤M├──────────┤M├────── # ├───┤└╥┘┌─┐ └╥┘┌─┐ # qr_1: ┤ X ├─╫─┤M├────────╫─┤M├─── # └───┘ ║ └╥┘ ┌───┐ ║ └╥┘┌─┐ # qr_2: ──────╫──╫──┤ X ├──╫──╫─┤M├ # ║ ║ └─╥─┘ ║ ║ └╥┘ # ║ ║ ┌──╨──┐ ║ ║ ║ # cr: 3/══════╩══╩═╡ 0x3 ╞═╩══╩══╩═ # 0 1 └─────┘ 0 1 2 circuit_if_true = QuantumCircuit(qr, cr) circuit_if_true.x(qr[0]) circuit_if_true.x(qr[1]) circuit_if_true.measure(qr[0], cr[0]) circuit_if_true.measure(qr[1], cr[1]) circuit_if_true.x(qr[2]).c_if(cr, 0x3) circuit_if_true.measure(qr[0], cr[0]) circuit_if_true.measure(qr[1], cr[1]) circuit_if_true.measure(qr[2], cr[2]) # ┌───┐┌─┐ ┌─┐ # qr_0: ┤ X ├┤M├───────┤M├────── # └┬─┬┘└╥┘ └╥┘┌─┐ # qr_1: ─┤M├──╫─────────╫─┤M├─── # └╥┘ ║ ┌───┐ ║ └╥┘┌─┐ # qr_2: ──╫───╫──┤ X ├──╫──╫─┤M├ # ║ ║ └─╥─┘ ║ ║ └╥┘ # ║ ║ ┌──╨──┐ ║ ║ ║ # cr: 3/══╩═══╩═╡ 0x3 ╞═╩══╩══╩═ # 1 0 └─────┘ 0 1 2 circuit_if_false = QuantumCircuit(qr, cr) circuit_if_false.x(qr[0]) circuit_if_false.measure(qr[0], cr[0]) circuit_if_false.measure(qr[1], cr[1]) circuit_if_false.x(qr[2]).c_if(cr, 0x3) circuit_if_false.measure(qr[0], cr[0]) circuit_if_false.measure(qr[1], cr[1]) circuit_if_false.measure(qr[2], cr[2]) job = self.backend.run( transpile([circuit_if_true, circuit_if_false], self.backend), shots=shots, seed_simulator=self.seed, ) result = job.result() counts_if_true = result.get_counts(circuit_if_true) counts_if_false = result.get_counts(circuit_if_false) self.assertEqual(counts_if_true, {"111": 100}) self.assertEqual(counts_if_false, {"001": 100}) def test_bit_cif_crossaffect(self): """Test if bits in a classical register other than the single conditional bit affect the conditioned operation.""" # ┌───┐ ┌─┐ # q0_0: ────────┤ H ├──────────┤M├ # ┌───┐ └─╥─┘ ┌─┐ └╥┘ # q0_1: ┤ X ├─────╫──────┤M├────╫─ # ├───┤ ║ └╥┘┌─┐ ║ # q0_2: ┤ X ├─────╫───────╫─┤M├─╫─ # └───┘┌────╨─────┐ ║ └╥┘ ║ # c0: 3/═════╡ c0_0=0x1 ╞═╩══╩══╬═ # └──────────┘ 1 2 ║ # c1: 1/════════════════════════╩═ # 0 shots = 100 qr = QuantumRegister(3) cr = ClassicalRegister(3) cr1 = ClassicalRegister(1) circuit = QuantumCircuit(qr, cr, cr1) circuit.x([qr[1], qr[2]]) circuit.measure(qr[1], cr[1]) circuit.measure(qr[2], cr[2]) circuit.h(qr[0]).c_if(cr[0], True) circuit.measure(qr[0], cr1[0]) job = self.backend.run(circuit, shots=shots, seed_simulator=self.seed) result = job.result().get_counts() target = {"0 110": 100} self.assertEqual(result, target) def test_teleport(self): """Test teleportation as in tutorials""" # ┌─────────┐ ┌───┐ ░ ┌─┐ # qr_0: ┤ Ry(π/4) ├───────■──┤ H ├─░─┤M├──────────────────── # └──┬───┬──┘ ┌─┴─┐└───┘ ░ └╥┘┌─┐ # qr_1: ───┤ H ├─────■──┤ X ├──────░──╫─┤M├───────────────── # └───┘ ┌─┴─┐└───┘ ░ ║ └╥┘ ┌───┐ ┌───┐ ┌─┐ # qr_2: ───────────┤ X ├───────────░──╫──╫──┤ Z ├──┤ X ├─┤M├ # └───┘ ░ ║ ║ └─╥─┘ └─╥─┘ └╥┘ # ║ ║ ┌──╨──┐ ║ ║ # cr0: 1/═════════════════════════════╩══╬═╡ 0x1 ╞═══╬════╬═ # 0 ║ └─────┘┌──╨──┐ ║ # cr1: 1/════════════════════════════════╩════════╡ 0x1 ╞═╬═ # 0 └─────┘ ║ # cr2: 1/═════════════════════════════════════════════════╩═ # 0 self.log.info("test_teleport") pi = np.pi shots = 4000 qr = QuantumRegister(3, "qr") cr0 = ClassicalRegister(1, "cr0") cr1 = ClassicalRegister(1, "cr1") cr2 = ClassicalRegister(1, "cr2") circuit = QuantumCircuit(qr, cr0, cr1, cr2, name="teleport") circuit.h(qr[1]) circuit.cx(qr[1], qr[2]) circuit.ry(pi / 4, qr[0]) circuit.cx(qr[0], qr[1]) circuit.h(qr[0]) circuit.barrier(qr) circuit.measure(qr[0], cr0[0]) circuit.measure(qr[1], cr1[0]) circuit.z(qr[2]).c_if(cr0, 1) circuit.x(qr[2]).c_if(cr1, 1) circuit.measure(qr[2], cr2[0]) job = self.backend.run( transpile(circuit, self.backend), shots=shots, seed_simulator=self.seed ) results = job.result() data = results.get_counts("teleport") alice = { "00": data["0 0 0"] + data["1 0 0"], "01": data["0 1 0"] + data["1 1 0"], "10": data["0 0 1"] + data["1 0 1"], "11": data["0 1 1"] + data["1 1 1"], } bob = { "0": data["0 0 0"] + data["0 1 0"] + data["0 0 1"] + data["0 1 1"], "1": data["1 0 0"] + data["1 1 0"] + data["1 0 1"] + data["1 1 1"], } self.log.info("test_teleport: circuit:") self.log.info(dumps(circuit)) self.log.info("test_teleport: data %s", data) self.log.info("test_teleport: alice %s", alice) self.log.info("test_teleport: bob %s", bob) alice_ratio = 1 / np.tan(pi / 8) ** 2 bob_ratio = bob["0"] / float(bob["1"]) error = abs(alice_ratio - bob_ratio) / alice_ratio self.log.info("test_teleport: relative error = %s", error) self.assertLess(error, 0.05) def test_memory(self): """Test memory.""" # ┌───┐ ┌─┐ # qr_0: ┤ H ├──■─────┤M├─── # └───┘┌─┴─┐ └╥┘┌─┐ # qr_1: ─────┤ X ├────╫─┤M├ # └┬─┬┘ ║ └╥┘ # qr_2: ──────┤M├─────╫──╫─ # ┌───┐ └╥┘ ┌─┐ ║ ║ # qr_3: ┤ X ├──╫──┤M├─╫──╫─ # └───┘ ║ └╥┘ ║ ║ # cr0: 2/══════╬═══╬══╩══╩═ # ║ ║ 0 1 # ║ ║ # cr1: 2/══════╩═══╩═══════ # 0 1 qr = QuantumRegister(4, "qr") cr0 = ClassicalRegister(2, "cr0") cr1 = ClassicalRegister(2, "cr1") circ = QuantumCircuit(qr, cr0, cr1) circ.h(qr[0]) circ.cx(qr[0], qr[1]) circ.x(qr[3]) circ.measure(qr[0], cr0[0]) circ.measure(qr[1], cr0[1]) circ.measure(qr[2], cr1[0]) circ.measure(qr[3], cr1[1]) shots = 50 job = self.backend.run( transpile(circ, self.backend), shots=shots, seed_simulator=self.seed, memory=True ) result = job.result() memory = result.get_memory() self.assertEqual(len(memory), shots) for mem in memory: self.assertIn(mem, ["10 00", "10 11"]) def test_unitary(self): """Test unitary gate instruction""" max_qubits = 4 x_mat = np.array([[0, 1], [1, 0]]) # Test 1 to max_qubits for random n-qubit unitary gate for i in range(max_qubits): num_qubits = i + 1 # Apply X gate to all qubits multi_x = x_mat for _ in range(i): multi_x = np.kron(multi_x, x_mat) # Target counts shots = 1024 target_counts = {num_qubits * "1": shots} # Test circuit qr = QuantumRegister(num_qubits, "qr") cr = ClassicalRegister(num_qubits, "cr") circuit = QuantumCircuit(qr, cr) circuit.unitary(multi_x, qr) circuit.measure(qr, cr) job = self.backend.run(transpile(circuit, self.backend), shots=shots) result = job.result() counts = result.get_counts(0) self.assertEqual(counts, target_counts) if __name__ == "__main__": unittest.main()
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test executing multiple-register circuits on BasicAer.""" from qiskit import BasicAer, execute from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister from qiskit.quantum_info import Operator, Statevector, process_fidelity, state_fidelity from qiskit.test import QiskitTestCase class TestCircuitMultiRegs(QiskitTestCase): """QuantumCircuit Qasm tests.""" def test_circuit_multi(self): """Test circuit multi regs declared at start.""" qreg0 = QuantumRegister(2, "q0") creg0 = ClassicalRegister(2, "c0") qreg1 = QuantumRegister(2, "q1") creg1 = ClassicalRegister(2, "c1") circ = QuantumCircuit(qreg0, qreg1, creg0, creg1) circ.x(qreg0[1]) circ.x(qreg1[0]) meas = QuantumCircuit(qreg0, qreg1, creg0, creg1) meas.measure(qreg0, creg0) meas.measure(qreg1, creg1) qc = circ.compose(meas) backend_sim = BasicAer.get_backend("qasm_simulator") result = execute(qc, backend_sim, seed_transpiler=34342).result() counts = result.get_counts(qc) target = {"01 10": 1024} backend_sim = BasicAer.get_backend("statevector_simulator") result = execute(circ, backend_sim, seed_transpiler=3438).result() state = result.get_statevector(circ) backend_sim = BasicAer.get_backend("unitary_simulator") result = execute(circ, backend_sim, seed_transpiler=3438).result() unitary = Operator(result.get_unitary(circ)) self.assertEqual(counts, target) self.assertAlmostEqual(state_fidelity(Statevector.from_label("0110"), state), 1.0, places=7) self.assertAlmostEqual( process_fidelity(Operator.from_label("IXXI"), unitary), 1.0, places=7 )
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2024. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=missing-function-docstring, missing-module-docstring import unittest from qiskit import QuantumCircuit from qiskit.providers.basic_provider import BasicSimulator import qiskit.circuit.library.standard_gates as lib from test import QiskitTestCase # pylint: disable=wrong-import-order class TestStandardGates(QiskitTestCase): """Standard gates support in BasicSimulator, up to 3 qubits""" def setUp(self): super().setUp() self.seed = 43 self.shots = 1 self.circuit = QuantumCircuit(4) def test_barrier(self): self.circuit.barrier(0, 1) self.circuit.measure_all() result = ( BasicSimulator().run(self.circuit, shots=self.shots, seed_simulator=self.seed).result() ) self.assertEqual(result.success, True) def test_barrier_none(self): self.circuit.barrier() self.circuit.measure_all() result = ( BasicSimulator().run(self.circuit, shots=self.shots, seed_simulator=self.seed).result() ) self.assertEqual(result.success, True) def test_unitary(self): matrix = [[0, 0, 0, 1], [0, 0, 1, 0], [1, 0, 0, 0], [0, 1, 0, 0]] self.circuit.unitary(matrix, [0, 1]) self.circuit.measure_all() result = ( BasicSimulator().run(self.circuit, shots=self.shots, seed_simulator=self.seed).result() ) self.assertEqual(result.success, True) def test_u(self): self.circuit.u(0.5, 1.5, 1.5, 0) self.circuit.measure_all() result = ( BasicSimulator().run(self.circuit, shots=self.shots, seed_simulator=self.seed).result() ) self.assertEqual(result.success, True) def test_u1(self): self.circuit.append(lib.U1Gate(0.5), [1]) self.circuit.measure_all() result = ( BasicSimulator().run(self.circuit, shots=self.shots, seed_simulator=self.seed).result() ) self.assertEqual(result.success, True) def test_u2(self): self.circuit.append(lib.U2Gate(0.5, 0.5), [1]) self.circuit.measure_all() result = ( BasicSimulator().run(self.circuit, shots=self.shots, seed_simulator=self.seed).result() ) self.assertEqual(result.success, True) def test_u3(self): self.circuit.append(lib.U3Gate(0.5, 0.5, 0.5), [1]) self.circuit.measure_all() result = ( BasicSimulator().run(self.circuit, shots=self.shots, seed_simulator=self.seed).result() ) self.assertEqual(result.success, True) def test_ccx(self): self.circuit.ccx(0, 1, 2) self.circuit.measure_all() result = ( BasicSimulator().run(self.circuit, shots=self.shots, seed_simulator=self.seed).result() ) self.assertEqual(result.success, True) def test_ccz(self): self.circuit.ccz(0, 1, 2) self.circuit.measure_all() result = ( BasicSimulator().run(self.circuit, shots=self.shots, seed_simulator=self.seed).result() ) self.assertEqual(result.success, True) def test_ch(self): self.circuit.ch(0, 1) self.circuit.measure_all() result = ( BasicSimulator().run(self.circuit, shots=self.shots, seed_simulator=self.seed).result() ) self.assertEqual(result.success, True) def test_cp(self): self.circuit.cp(0, 0, 1) self.circuit.measure_all() result = ( BasicSimulator().run(self.circuit, shots=self.shots, seed_simulator=self.seed).result() ) self.assertEqual(result.success, True) def test_crx(self): self.circuit.crx(1, 0, 1) self.circuit.measure_all() result = ( BasicSimulator().run(self.circuit, shots=self.shots, seed_simulator=self.seed).result() ) self.assertEqual(result.success, True) def test_cry(self): self.circuit.cry(1, 0, 1) self.circuit.measure_all() result = ( BasicSimulator().run(self.circuit, shots=self.shots, seed_simulator=self.seed).result() ) self.assertEqual(result.success, True) def test_crz(self): self.circuit.crz(1, 0, 1) self.circuit.measure_all() result = ( BasicSimulator().run(self.circuit, shots=self.shots, seed_simulator=self.seed).result() ) self.assertEqual(result.success, True) def test_cswap(self): self.circuit.cswap(0, 1, 2) self.circuit.measure_all() result = ( BasicSimulator().run(self.circuit, shots=self.shots, seed_simulator=self.seed).result() ) self.assertEqual(result.success, True) def test_cu1(self): self.circuit.append(lib.CU1Gate(1), [1, 2]) self.circuit.measure_all() result = ( BasicSimulator().run(self.circuit, shots=self.shots, seed_simulator=self.seed).result() ) self.assertEqual(result.success, True) def test_cu3(self): self.circuit.append(lib.CU3Gate(1, 2, 3), [1, 2]) self.circuit.measure_all() result = ( BasicSimulator().run(self.circuit, shots=self.shots, seed_simulator=self.seed).result() ) self.assertEqual(result.success, True) def test_cx(self): self.circuit.cx(1, 2) self.circuit.measure_all() result = ( BasicSimulator().run(self.circuit, shots=self.shots, seed_simulator=self.seed).result() ) self.assertEqual(result.success, True) def test_ecr(self): self.circuit.ecr(1, 2) self.circuit.measure_all() result = ( BasicSimulator().run(self.circuit, shots=self.shots, seed_simulator=self.seed).result() ) self.assertEqual(result.success, True) def test_cy(self): self.circuit.cy(1, 2) self.circuit.measure_all() result = ( BasicSimulator().run(self.circuit, shots=self.shots, seed_simulator=self.seed).result() ) self.assertEqual(result.success, True) def test_cz(self): self.circuit.cz(1, 2) self.circuit.measure_all() result = ( BasicSimulator().run(self.circuit, shots=self.shots, seed_simulator=self.seed).result() ) self.assertEqual(result.success, True) def test_h(self): self.circuit.h(1) self.circuit.measure_all() result = ( BasicSimulator().run(self.circuit, shots=self.shots, seed_simulator=self.seed).result() ) self.assertEqual(result.success, True) def test_id(self): self.circuit.id(1) self.circuit.measure_all() result = ( BasicSimulator().run(self.circuit, shots=self.shots, seed_simulator=self.seed).result() ) self.assertEqual(result.success, True) def test_rx(self): self.circuit.rx(1, 1) self.circuit.measure_all() result = ( BasicSimulator().run(self.circuit, shots=self.shots, seed_simulator=self.seed).result() ) self.assertEqual(result.success, True) def test_ry(self): self.circuit.ry(1, 1) self.circuit.measure_all() result = ( BasicSimulator().run(self.circuit, shots=self.shots, seed_simulator=self.seed).result() ) self.assertEqual(result.success, True) def test_rz(self): self.circuit.rz(1, 1) self.circuit.measure_all() result = ( BasicSimulator().run(self.circuit, shots=self.shots, seed_simulator=self.seed).result() ) self.assertEqual(result.success, True) def test_rxx(self): self.circuit.rxx(1, 1, 0) self.circuit.measure_all() result = ( BasicSimulator().run(self.circuit, shots=self.shots, seed_simulator=self.seed).result() ) self.assertEqual(result.success, True) def test_rzx(self): self.circuit.rzx(1, 1, 0) self.circuit.measure_all() result = ( BasicSimulator().run(self.circuit, shots=self.shots, seed_simulator=self.seed).result() ) self.assertEqual(result.success, True) def test_ryy(self): self.circuit.ryy(1, 1, 0) self.circuit.measure_all() result = ( BasicSimulator().run(self.circuit, shots=self.shots, seed_simulator=self.seed).result() ) self.assertEqual(result.success, True) def test_rzz(self): self.circuit.rzz(1, 1, 2) self.circuit.measure_all() result = ( BasicSimulator().run(self.circuit, shots=self.shots, seed_simulator=self.seed).result() ) self.assertEqual(result.success, True) def test_s(self): self.circuit.s(1) self.circuit.measure_all() result = ( BasicSimulator().run(self.circuit, shots=self.shots, seed_simulator=self.seed).result() ) self.assertEqual(result.success, True) def test_sdg(self): self.circuit.sdg(1) self.circuit.measure_all() result = ( BasicSimulator().run(self.circuit, shots=self.shots, seed_simulator=self.seed).result() ) self.assertEqual(result.success, True) def test_sx(self): self.circuit.sx(1) self.circuit.measure_all() result = ( BasicSimulator().run(self.circuit, shots=self.shots, seed_simulator=self.seed).result() ) self.assertEqual(result.success, True) def test_sxdg(self): self.circuit.sxdg(1) self.circuit.measure_all() result = ( BasicSimulator().run(self.circuit, shots=self.shots, seed_simulator=self.seed).result() ) self.assertEqual(result.success, True) def test_swap(self): self.circuit.swap(1, 2) self.circuit.measure_all() result = ( BasicSimulator().run(self.circuit, shots=self.shots, seed_simulator=self.seed).result() ) self.assertEqual(result.success, True) def test_iswap(self): self.circuit.iswap(1, 0) self.circuit.measure_all() result = ( BasicSimulator().run(self.circuit, shots=self.shots, seed_simulator=self.seed).result() ) self.assertEqual(result.success, True) def test_p(self): self.circuit.p(1, 0) self.circuit.measure_all() result = ( BasicSimulator().run(self.circuit, shots=self.shots, seed_simulator=self.seed).result() ) self.assertEqual(result.success, True) def test_r(self): self.circuit.r(0.5, 0, 1) self.circuit.measure_all() result = ( BasicSimulator().run(self.circuit, shots=self.shots, seed_simulator=self.seed).result() ) self.assertEqual(result.success, True) def test_t(self): self.circuit.t(1) self.circuit.measure_all() result = ( BasicSimulator().run(self.circuit, shots=self.shots, seed_simulator=self.seed).result() ) self.assertEqual(result.success, True) def test_tdg(self): self.circuit.tdg(1) self.circuit.measure_all() result = ( BasicSimulator().run(self.circuit, shots=self.shots, seed_simulator=self.seed).result() ) self.assertEqual(result.success, True) def test_x(self): self.circuit.x(1) self.circuit.measure_all() result = ( BasicSimulator().run(self.circuit, shots=self.shots, seed_simulator=self.seed).result() ) self.assertEqual(result.success, True) def test_y(self): self.circuit.y(1) self.circuit.measure_all() result = ( BasicSimulator().run(self.circuit, shots=self.shots, seed_simulator=self.seed).result() ) self.assertEqual(result.success, True) def test_z(self): self.circuit.z(1) self.circuit.measure_all() result = ( BasicSimulator().run(self.circuit, shots=self.shots, seed_simulator=self.seed).result() ) self.assertEqual(result.success, True) def test_cs(self): self.circuit.cs(0, 1) self.circuit.measure_all() result = ( BasicSimulator().run(self.circuit, shots=self.shots, seed_simulator=self.seed).result() ) self.assertEqual(result.success, True) def test_csdg(self): self.circuit.csdg(0, 1) self.circuit.measure_all() result = ( BasicSimulator().run(self.circuit, shots=self.shots, seed_simulator=self.seed).result() ) self.assertEqual(result.success, True) def test_csx(self): self.circuit.csx(0, 1) self.circuit.measure_all() result = ( BasicSimulator().run(self.circuit, shots=self.shots, seed_simulator=self.seed).result() ) self.assertEqual(result.success, True) def test_cu(self): self.circuit.cu(0.5, 0.5, 0.5, 0.5, 0, 1) self.circuit.measure_all() result = ( BasicSimulator().run(self.circuit, shots=self.shots, seed_simulator=self.seed).result() ) self.assertEqual(result.success, True) def test_dcx(self): self.circuit.dcx(0, 1) self.circuit.measure_all() result = ( BasicSimulator().run(self.circuit, shots=self.shots, seed_simulator=self.seed).result() ) self.assertEqual(result.success, True) def test_delay(self): self.circuit.delay(0, 1) self.circuit.measure_all() result = ( BasicSimulator().run(self.circuit, shots=self.shots, seed_simulator=self.seed).result() ) self.assertEqual(result.success, True) def test_reset(self): self.circuit.reset(1) self.circuit.measure_all() result = ( BasicSimulator().run(self.circuit, shots=self.shots, seed_simulator=self.seed).result() ) self.assertEqual(result.success, True) def test_rcx(self): self.circuit.rccx(0, 1, 2) self.circuit.measure_all() result = ( BasicSimulator().run(self.circuit, shots=self.shots, seed_simulator=self.seed).result() ) self.assertEqual(result.success, True) def test_global_phase(self): qc = self.circuit qc.append(lib.GlobalPhaseGate(0.1), []) self.circuit.measure_all() result = ( BasicSimulator().run(self.circuit, shots=self.shots, seed_simulator=self.seed).result() ) self.assertEqual(result.success, True) def test_xx_minus_yy(self): self.circuit.append(lib.XXMinusYYGate(0.1, 0.2), [0, 1]) self.circuit.measure_all() result = ( BasicSimulator().run(self.circuit, shots=self.shots, seed_simulator=self.seed).result() ) self.assertEqual(result.success, True) def test_xx_plus_yy(self): self.circuit.append(lib.XXPlusYYGate(0.1, 0.2), [0, 1]) self.circuit.measure_all() result = ( BasicSimulator().run(self.circuit, shots=self.shots, seed_simulator=self.seed).result() ) self.assertEqual(result.success, True) class TestStandardGatesTarget(QiskitTestCase): """Standard gates, up to 3 qubits, as a target""" def test_target(self): target = BasicSimulator().target expected = { "cz", "u3", "p", "cswap", "z", "cu1", "ecr", "reset", "ch", "cy", "dcx", "crx", "sx", "unitary", "csdg", "rzz", "measure", "swap", "csx", "y", "s", "xx_plus_yy", "cs", "h", "t", "u", "rxx", "cu", "rzx", "ry", "rx", "cu3", "tdg", "u2", "xx_minus_yy", "global_phase", "u1", "id", "cx", "cp", "rz", "sxdg", "x", "ryy", "sdg", "ccz", "delay", "crz", "iswap", "ccx", "cry", "rccx", "r", } self.assertEqual(set(target.operation_names), expected) if __name__ == "__main__": unittest.main(verbosity=2)
https://github.com/swe-train/qiskit__qiskit
swe-train
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/swe-train/qiskit__qiskit
swe-train
# 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. """Test of generated fake backends.""" import math import unittest from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, schedule, transpile, assemble from qiskit.pulse import Schedule from qiskit.qobj import PulseQobj from qiskit.test import QiskitTestCase from qiskit.providers.fake_provider.utils.configurable_backend import ConfigurableFakeBackend from qiskit.providers.fake_provider import FakeAthens, FakePerth from qiskit.utils import optionals def get_test_circuit(): """Generates simple circuit for tests.""" desired_vector = [1 / math.sqrt(2), 0, 0, 1 / math.sqrt(2)] qr = QuantumRegister(2, "qr") cr = ClassicalRegister(2, "cr") qc = QuantumCircuit(qr, cr) qc.initialize(desired_vector, [qr[0], qr[1]]) qc.measure(qr[0], cr[0]) qc.measure(qr[1], cr[1]) return qc class GeneratedFakeBackendsTest(QiskitTestCase): """Generated fake backends test.""" def setUp(self) -> None: self.backend = ConfigurableFakeBackend("Tashkent", n_qubits=4) @unittest.skip("Skipped until qiskit-aer#741 is fixed and released") @unittest.skipUnless(optionals.HAS_AER, "qiskit-aer is required to run this test") def test_transpile_schedule_and_assemble(self): """Test transpile, schedule and assemble on generated backend.""" qc = get_test_circuit() circuit = transpile(qc, backend=self.backend) self.assertTrue(isinstance(circuit, QuantumCircuit)) self.assertEqual(circuit.num_qubits, 4) experiments = schedule(circuits=circuit, backend=self.backend) self.assertTrue(isinstance(experiments, Schedule)) self.assertGreater(experiments.duration, 0) qobj = assemble(experiments, backend=self.backend) self.assertTrue(isinstance(qobj, PulseQobj)) self.assertEqual(qobj.header.backend_name, "Tashkent") self.assertEqual(len(qobj.experiments), 1) job = self.backend.run(qobj) result = job.result() self.assertTrue(result.success) self.assertEqual(len(result.results), 1) class FakeBackendsTest(QiskitTestCase): """fake backends test.""" @unittest.skipUnless(optionals.HAS_AER, "qiskit-aer is required to run this test") def test_fake_backends_get_kwargs(self): """Fake backends honor kwargs passed.""" backend = FakeAthens() qc = QuantumCircuit(2) qc.x(range(0, 2)) qc.measure_all() trans_qc = transpile(qc, backend) raw_counts = backend.run(trans_qc, shots=1000).result().get_counts() self.assertEqual(sum(raw_counts.values()), 1000) @unittest.skipUnless(optionals.HAS_AER, "qiskit-aer is required to run this test") def test_fake_backend_v2_noise_model_always_present(self): """Test that FakeBackendV2 instances always run with noise.""" backend = FakePerth() qc = QuantumCircuit(1) qc.x(0) qc.measure_all() res = backend.run(qc, shots=1000).result().get_counts() # Assert noise was present and result wasn't ideal self.assertNotEqual(res, {"1": 1000})
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2023, 2024. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Test of GenericBackendV2 backend""" import math from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister, transpile from qiskit.providers.fake_provider import GenericBackendV2 from qiskit.transpiler import CouplingMap from qiskit.exceptions import QiskitError from test import QiskitTestCase # pylint: disable=wrong-import-order class TestGenericBackendV2(QiskitTestCase): """Test class for GenericBackendV2 backend""" def setUp(self): super().setUp() self.cmap = CouplingMap( [(0, 2), (0, 1), (1, 3), (2, 4), (2, 3), (3, 5), (4, 6), (4, 5), (5, 7), (6, 7)] ) def test_supported_basis_gates(self): """Test that target raises error if basis_gate not in ``supported_names``.""" with self.assertRaises(QiskitError): GenericBackendV2(num_qubits=8, basis_gates=["cx", "id", "rz", "sx", "zz"]) def test_operation_names(self): """Test that target basis gates include "delay", "measure" and "reset" even if not provided by user.""" target = GenericBackendV2(num_qubits=8) op_names = list(target.operation_names) op_names.sort() self.assertEqual(op_names, ["cx", "delay", "id", "measure", "reset", "rz", "sx", "x"]) target = GenericBackendV2(num_qubits=8, basis_gates=["ecr", "id", "rz", "sx", "x"]) op_names = list(target.operation_names) op_names.sort() self.assertEqual(op_names, ["delay", "ecr", "id", "measure", "reset", "rz", "sx", "x"]) def test_incompatible_coupling_map(self): """Test that the size of the coupling map must match num_qubits.""" with self.assertRaises(QiskitError): GenericBackendV2(num_qubits=5, coupling_map=self.cmap) def test_control_flow_operation_names(self): """Test that control flow instructions are added to the target if control_flow is True.""" target = GenericBackendV2( num_qubits=8, basis_gates=["ecr", "id", "rz", "sx", "x"], coupling_map=self.cmap, control_flow=True, ).target op_names = list(target.operation_names) op_names.sort() reference = [ "break", "continue", "delay", "ecr", "for_loop", "id", "if_else", "measure", "reset", "rz", "switch_case", "sx", "while_loop", "x", ] self.assertEqual(op_names, reference) def test_default_coupling_map(self): """Test that fully-connected coupling map is generated correctly.""" # fmt: off reference_cmap = [(0, 1), (1, 0), (0, 2), (2, 0), (0, 3), (3, 0), (0, 4), (4, 0), (1, 2), (2, 1), (1, 3), (3, 1), (1, 4), (4, 1), (2, 3), (3, 2), (2, 4), (4, 2), (3, 4), (4, 3)] # fmt: on self.assertEqual( list(GenericBackendV2(num_qubits=5).coupling_map.get_edges()), reference_cmap, ) def test_run(self): """Test run method, confirm correct noisy simulation if Aer is installed.""" qr = QuantumRegister(5) cr = ClassicalRegister(5) qc = QuantumCircuit(qr, cr) qc.h(qr[0]) for k in range(1, 4): qc.cx(qr[0], qr[k]) qc.measure(qr, cr) backend = GenericBackendV2(num_qubits=5, basis_gates=["cx", "id", "rz", "sx", "x"]) tqc = transpile(qc, backend=backend, optimization_level=3, seed_transpiler=42) result = backend.run(tqc, seed_simulator=42, shots=1000).result() counts = result.get_counts() self.assertTrue(math.isclose(counts["00000"], 500, rel_tol=0.1)) self.assertTrue(math.isclose(counts["01111"], 500, rel_tol=0.1)) def test_duration_defaults(self): """Test that the basis gates are assigned duration defaults within expected ranges.""" basis_gates = ["cx", "id", "rz", "sx", "x", "sdg", "rxx"] expected_durations = { "cx": (7.992e-08, 8.99988e-07), "id": (2.997e-08, 5.994e-08), "rz": (0.0, 0.0), "sx": (2.997e-08, 5.994e-08), "x": (2.997e-08, 5.994e-08), "measure": (6.99966e-07, 1.500054e-06), "sdg": (2.997e-08, 5.994e-08), "rxx": (7.992e-08, 8.99988e-07), } for _ in range(20): target = GenericBackendV2(num_qubits=2, basis_gates=basis_gates).target for inst in target: for qargs in target.qargs_for_operation_name(inst): duration = target[inst][qargs].duration if inst not in ["delay", "reset"]: self.assertGreaterEqual(duration, expected_durations[inst][0]) self.assertLessEqual(duration, expected_durations[inst][1])
https://github.com/swe-train/qiskit__qiskit
swe-train
# 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 """Test cases for the pulse schedule block.""" import re import unittest from typing import List, Any from qiskit import pulse, circuit from qiskit.pulse import transforms from qiskit.pulse.exceptions import PulseError from qiskit.test import QiskitTestCase from qiskit.providers.fake_provider import FakeOpenPulse2Q, FakeArmonk from qiskit.utils import has_aer class BaseTestBlock(QiskitTestCase): """ScheduleBlock tests.""" def setUp(self): super().setUp() self.backend = FakeOpenPulse2Q() self.test_waveform0 = pulse.Constant(100, 0.1) self.test_waveform1 = pulse.Constant(200, 0.1) self.d0 = pulse.DriveChannel(0) self.d1 = pulse.DriveChannel(1) self.left_context = transforms.AlignLeft() self.right_context = transforms.AlignRight() self.sequential_context = transforms.AlignSequential() self.equispaced_context = transforms.AlignEquispaced(duration=1000) def _align_func(j): return {1: 0.1, 2: 0.25, 3: 0.7, 4: 0.85}.get(j) self.func_context = transforms.AlignFunc(duration=1000, func=_align_func) def assertScheduleEqual(self, target, reference): """Check if two block are equal schedule representation.""" self.assertEqual(transforms.target_qobj_transform(target), reference) class TestTransformation(BaseTestBlock): """Test conversion of ScheduleBlock to Schedule.""" def test_left_alignment(self): """Test left alignment context.""" block = pulse.ScheduleBlock(alignment_context=self.left_context) block = block.append(pulse.Play(self.test_waveform0, self.d0)) block = block.append(pulse.Play(self.test_waveform1, self.d1)) ref_sched = pulse.Schedule() ref_sched = ref_sched.insert(0, pulse.Play(self.test_waveform0, self.d0)) ref_sched = ref_sched.insert(0, pulse.Play(self.test_waveform1, self.d1)) self.assertScheduleEqual(block, ref_sched) def test_right_alignment(self): """Test right alignment context.""" block = pulse.ScheduleBlock(alignment_context=self.right_context) block = block.append(pulse.Play(self.test_waveform0, self.d0)) block = block.append(pulse.Play(self.test_waveform1, self.d1)) ref_sched = pulse.Schedule() ref_sched = ref_sched.insert(100, pulse.Play(self.test_waveform0, self.d0)) ref_sched = ref_sched.insert(0, pulse.Play(self.test_waveform1, self.d1)) self.assertScheduleEqual(block, ref_sched) def test_sequential_alignment(self): """Test sequential alignment context.""" block = pulse.ScheduleBlock(alignment_context=self.sequential_context) block = block.append(pulse.Play(self.test_waveform0, self.d0)) block = block.append(pulse.Play(self.test_waveform1, self.d1)) ref_sched = pulse.Schedule() ref_sched = ref_sched.insert(0, pulse.Play(self.test_waveform0, self.d0)) ref_sched = ref_sched.insert(100, pulse.Play(self.test_waveform1, self.d1)) self.assertScheduleEqual(block, ref_sched) def test_equispace_alignment(self): """Test equispace alignment context.""" block = pulse.ScheduleBlock(alignment_context=self.equispaced_context) for _ in range(4): block = block.append(pulse.Play(self.test_waveform0, self.d0)) ref_sched = pulse.Schedule() ref_sched = ref_sched.insert(0, pulse.Play(self.test_waveform0, self.d0)) ref_sched = ref_sched.insert(300, pulse.Play(self.test_waveform0, self.d0)) ref_sched = ref_sched.insert(600, pulse.Play(self.test_waveform0, self.d0)) ref_sched = ref_sched.insert(900, pulse.Play(self.test_waveform0, self.d0)) self.assertScheduleEqual(block, ref_sched) def test_func_alignment(self): """Test func alignment context.""" block = pulse.ScheduleBlock(alignment_context=self.func_context) for _ in range(4): block = block.append(pulse.Play(self.test_waveform0, self.d0)) ref_sched = pulse.Schedule() ref_sched = ref_sched.insert(50, pulse.Play(self.test_waveform0, self.d0)) ref_sched = ref_sched.insert(200, pulse.Play(self.test_waveform0, self.d0)) ref_sched = ref_sched.insert(650, pulse.Play(self.test_waveform0, self.d0)) ref_sched = ref_sched.insert(800, pulse.Play(self.test_waveform0, self.d0)) self.assertScheduleEqual(block, ref_sched) def test_nested_alignment(self): """Test nested block scheduling.""" block_sub = pulse.ScheduleBlock(alignment_context=self.right_context) block_sub = block_sub.append(pulse.Play(self.test_waveform0, self.d0)) block_sub = block_sub.append(pulse.Play(self.test_waveform1, self.d1)) block_main = pulse.ScheduleBlock(alignment_context=self.sequential_context) block_main = block_main.append(block_sub) block_main = block_main.append(pulse.Delay(10, self.d0)) block_main = block_main.append(block_sub) ref_sched = pulse.Schedule() ref_sched = ref_sched.insert(0, pulse.Play(self.test_waveform1, self.d1)) ref_sched = ref_sched.insert(100, pulse.Play(self.test_waveform0, self.d0)) ref_sched = ref_sched.insert(200, pulse.Delay(10, self.d0)) ref_sched = ref_sched.insert(210, pulse.Play(self.test_waveform1, self.d1)) ref_sched = ref_sched.insert(310, pulse.Play(self.test_waveform0, self.d0)) self.assertScheduleEqual(block_main, ref_sched) class TestBlockOperation(BaseTestBlock): """Test fundamental operation on schedule block. Because ScheduleBlock adapts to the lazy scheduling, no uniitest for overlap constraints is necessary. Test scheme becomes simpler than the schedule. Some tests have dependency on schedule conversion. This operation should be tested in `test.python.pulse.test_block.TestTransformation`. """ def setUp(self): super().setUp() self.test_blocks = [ pulse.Play(self.test_waveform0, self.d0), pulse.Play(self.test_waveform1, self.d1), pulse.Delay(50, self.d0), pulse.Play(self.test_waveform1, self.d0), ] def test_append_an_instruction_to_empty_block(self): """Test append instructions to an empty block.""" block = pulse.ScheduleBlock() block = block.append(pulse.Play(self.test_waveform0, self.d0)) self.assertEqual(block.blocks[0], pulse.Play(self.test_waveform0, self.d0)) def test_append_an_instruction_to_empty_block_sugar(self): """Test append instructions to an empty block with syntax sugar.""" block = pulse.ScheduleBlock() block += pulse.Play(self.test_waveform0, self.d0) self.assertEqual(block.blocks[0], pulse.Play(self.test_waveform0, self.d0)) def test_append_an_instruction_to_empty_block_inplace(self): """Test append instructions to an empty block with inplace.""" block = pulse.ScheduleBlock() block.append(pulse.Play(self.test_waveform0, self.d0), inplace=True) self.assertEqual(block.blocks[0], pulse.Play(self.test_waveform0, self.d0)) def test_append_a_block_to_empty_block(self): """Test append another ScheduleBlock to empty block.""" block = pulse.ScheduleBlock() block.append(pulse.Play(self.test_waveform0, self.d0), inplace=True) block_main = pulse.ScheduleBlock() block_main = block_main.append(block) self.assertEqual(block_main.blocks[0], block) def test_append_an_instruction_to_block(self): """Test append instructions to a non-empty block.""" block = pulse.ScheduleBlock() block = block.append(pulse.Delay(100, self.d0)) block = block.append(pulse.Delay(100, self.d0)) self.assertEqual(len(block.blocks), 2) def test_append_an_instruction_to_block_inplace(self): """Test append instructions to a non-empty block with inplace.""" block = pulse.ScheduleBlock() block = block.append(pulse.Delay(100, self.d0)) block.append(pulse.Delay(100, self.d0), inplace=True) self.assertEqual(len(block.blocks), 2) def test_duration(self): """Test if correct duration is returned with implicit scheduling.""" block = pulse.ScheduleBlock() for inst in self.test_blocks: block.append(inst) self.assertEqual(block.duration, 350) def test_channels(self): """Test if all channels are returned.""" block = pulse.ScheduleBlock() for inst in self.test_blocks: block.append(inst) self.assertEqual(len(block.channels), 2) def test_instructions(self): """Test if all instructions are returned.""" block = pulse.ScheduleBlock() for inst in self.test_blocks: block.append(inst) self.assertEqual(block.blocks, tuple(self.test_blocks)) def test_channel_duraction(self): """Test if correct durations is calculated for each channel.""" block = pulse.ScheduleBlock() for inst in self.test_blocks: block.append(inst) self.assertEqual(block.ch_duration(self.d0), 350) self.assertEqual(block.ch_duration(self.d1), 200) def test_cannot_append_schedule(self): """Test schedule cannot be appended. Schedule should be input as Call instruction.""" block = pulse.ScheduleBlock() sched = pulse.Schedule() sched += pulse.Delay(10, self.d0) with self.assertRaises(PulseError): block.append(sched) def test_replace(self): """Test replacing specific instruction.""" block = pulse.ScheduleBlock() for inst in self.test_blocks: block.append(inst) replaced = pulse.Play(pulse.Constant(300, 0.1), self.d1) target = pulse.Delay(50, self.d0) block_replaced = block.replace(target, replaced, inplace=False) # original schedule is not destroyed self.assertListEqual(list(block.blocks), self.test_blocks) ref_sched = pulse.Schedule() ref_sched = ref_sched.insert(0, pulse.Play(self.test_waveform0, self.d0)) ref_sched = ref_sched.insert(0, pulse.Play(self.test_waveform1, self.d1)) ref_sched = ref_sched.insert(200, replaced) ref_sched = ref_sched.insert(100, pulse.Play(self.test_waveform1, self.d0)) self.assertScheduleEqual(block_replaced, ref_sched) def test_replace_inplace(self): """Test replacing specific instruction with inplace.""" block = pulse.ScheduleBlock() for inst in self.test_blocks: block.append(inst) replaced = pulse.Play(pulse.Constant(300, 0.1), self.d1) target = pulse.Delay(50, self.d0) block.replace(target, replaced, inplace=True) ref_sched = pulse.Schedule() ref_sched = ref_sched.insert(0, pulse.Play(self.test_waveform0, self.d0)) ref_sched = ref_sched.insert(0, pulse.Play(self.test_waveform1, self.d1)) ref_sched = ref_sched.insert(200, replaced) ref_sched = ref_sched.insert(100, pulse.Play(self.test_waveform1, self.d0)) self.assertScheduleEqual(block, ref_sched) def test_replace_block_by_instruction(self): """Test replacing block with instruction.""" sub_block1 = pulse.ScheduleBlock() sub_block1 = sub_block1.append(pulse.Delay(50, self.d0)) sub_block1 = sub_block1.append(pulse.Play(self.test_waveform0, self.d0)) sub_block2 = pulse.ScheduleBlock() sub_block2 = sub_block2.append(pulse.Delay(50, self.d0)) sub_block2 = sub_block2.append(pulse.Play(self.test_waveform1, self.d1)) main_block = pulse.ScheduleBlock() main_block = main_block.append(pulse.Delay(50, self.d0)) main_block = main_block.append(pulse.Play(self.test_waveform0, self.d0)) main_block = main_block.append(sub_block1) main_block = main_block.append(sub_block2) main_block = main_block.append(pulse.Play(self.test_waveform0, self.d1)) replaced = main_block.replace(sub_block1, pulse.Delay(100, self.d0)) ref_blocks = [ pulse.Delay(50, self.d0), pulse.Play(self.test_waveform0, self.d0), pulse.Delay(100, self.d0), sub_block2, pulse.Play(self.test_waveform0, self.d1), ] self.assertListEqual(list(replaced.blocks), ref_blocks) def test_replace_instruction_by_block(self): """Test replacing instruction with block.""" sub_block1 = pulse.ScheduleBlock() sub_block1 = sub_block1.append(pulse.Delay(50, self.d0)) sub_block1 = sub_block1.append(pulse.Play(self.test_waveform0, self.d0)) sub_block2 = pulse.ScheduleBlock() sub_block2 = sub_block2.append(pulse.Delay(50, self.d0)) sub_block2 = sub_block2.append(pulse.Play(self.test_waveform1, self.d1)) main_block = pulse.ScheduleBlock() main_block = main_block.append(pulse.Delay(50, self.d0)) main_block = main_block.append(pulse.Play(self.test_waveform0, self.d0)) main_block = main_block.append(pulse.Delay(100, self.d0)) main_block = main_block.append(sub_block2) main_block = main_block.append(pulse.Play(self.test_waveform0, self.d1)) replaced = main_block.replace(pulse.Delay(100, self.d0), sub_block1) ref_blocks = [ pulse.Delay(50, self.d0), pulse.Play(self.test_waveform0, self.d0), sub_block1, sub_block2, pulse.Play(self.test_waveform0, self.d1), ] self.assertListEqual(list(replaced.blocks), ref_blocks) def test_len(self): """Test __len__ method""" block = pulse.ScheduleBlock() self.assertEqual(len(block), 0) for j in range(1, 10): block = block.append(pulse.Delay(10, self.d0)) self.assertEqual(len(block), j) def test_inherit_from(self): """Test creating schedule with another schedule.""" ref_metadata = {"test": "value"} ref_name = "test" base_sched = pulse.ScheduleBlock(name=ref_name, metadata=ref_metadata) new_sched = pulse.ScheduleBlock.initialize_from(base_sched) self.assertEqual(new_sched.name, ref_name) self.assertDictEqual(new_sched.metadata, ref_metadata) @unittest.skipUnless(has_aer(), "qiskit-aer doesn't appear to be installed.") def test_execute_block(self): """Test executing a ScheduleBlock on a Pulse backend""" with pulse.build(name="test_block") as sched_block: pulse.play(pulse.Constant(160, 1.0), pulse.DriveChannel(0)) pulse.acquire(50, pulse.AcquireChannel(0), pulse.MemorySlot(0)) backend = FakeArmonk() # TODO: Rewrite test to simulate with qiskit-dynamics with self.assertWarns(DeprecationWarning): test_result = backend.run(sched_block).result() self.assertDictEqual(test_result.get_counts(), {"0": 1024}) class TestBlockEquality(BaseTestBlock): """Test equality of blocks. Equality of instruction ordering is compared on DAG representation. This should be tested for each transform. """ def test_different_channels(self): """Test equality is False if different channels.""" block1 = pulse.ScheduleBlock() block1 += pulse.Delay(10, self.d0) block2 = pulse.ScheduleBlock() block2 += pulse.Delay(10, self.d1) self.assertNotEqual(block1, block2) def test_different_transform(self): """Test equality is False if different transforms.""" block1 = pulse.ScheduleBlock(alignment_context=self.left_context) block1 += pulse.Delay(10, self.d0) block2 = pulse.ScheduleBlock(alignment_context=self.right_context) block2 += pulse.Delay(10, self.d0) self.assertNotEqual(block1, block2) def test_different_transform_opts(self): """Test equality is False if different transform options.""" context1 = transforms.AlignEquispaced(duration=100) context2 = transforms.AlignEquispaced(duration=500) block1 = pulse.ScheduleBlock(alignment_context=context1) block1 += pulse.Delay(10, self.d0) block2 = pulse.ScheduleBlock(alignment_context=context2) block2 += pulse.Delay(10, self.d0) self.assertNotEqual(block1, block2) def test_instruction_out_of_order_left(self): """Test equality is True if two blocks have instructions in different order.""" block1 = pulse.ScheduleBlock(alignment_context=self.left_context) block1 += pulse.Play(self.test_waveform0, self.d0) block1 += pulse.Play(self.test_waveform0, self.d1) block2 = pulse.ScheduleBlock(alignment_context=self.left_context) block2 += pulse.Play(self.test_waveform0, self.d1) block2 += pulse.Play(self.test_waveform0, self.d0) self.assertEqual(block1, block2) def test_instruction_in_order_left(self): """Test equality is True if two blocks have instructions in same order.""" block1 = pulse.ScheduleBlock(alignment_context=self.left_context) block1 += pulse.Play(self.test_waveform0, self.d0) block1 += pulse.Play(self.test_waveform0, self.d1) block2 = pulse.ScheduleBlock(alignment_context=self.left_context) block2 += pulse.Play(self.test_waveform0, self.d0) block2 += pulse.Play(self.test_waveform0, self.d1) self.assertEqual(block1, block2) def test_instruction_out_of_order_right(self): """Test equality is True if two blocks have instructions in different order.""" block1 = pulse.ScheduleBlock(alignment_context=self.right_context) block1 += pulse.Play(self.test_waveform0, self.d0) block1 += pulse.Play(self.test_waveform0, self.d1) block2 = pulse.ScheduleBlock(alignment_context=self.right_context) block2 += pulse.Play(self.test_waveform0, self.d1) block2 += pulse.Play(self.test_waveform0, self.d0) self.assertEqual(block1, block2) def test_instruction_in_order_right(self): """Test equality is True if two blocks have instructions in same order.""" block1 = pulse.ScheduleBlock(alignment_context=self.right_context) block1 += pulse.Play(self.test_waveform0, self.d0) block1 += pulse.Play(self.test_waveform0, self.d1) block2 = pulse.ScheduleBlock(alignment_context=self.right_context) block2 += pulse.Play(self.test_waveform0, self.d0) block2 += pulse.Play(self.test_waveform0, self.d1) self.assertEqual(block1, block2) def test_instruction_out_of_order_sequential(self): """Test equality is False if two blocks have instructions in different order.""" block1 = pulse.ScheduleBlock(alignment_context=self.sequential_context) block1 += pulse.Play(self.test_waveform0, self.d0) block1 += pulse.Play(self.test_waveform0, self.d1) block2 = pulse.ScheduleBlock(alignment_context=self.sequential_context) block2 += pulse.Play(self.test_waveform0, self.d1) block2 += pulse.Play(self.test_waveform0, self.d0) self.assertNotEqual(block1, block2) def test_instruction_out_of_order_sequential_more(self): """Test equality is False if three blocks have instructions in different order. This could detect a particular bug as discussed in this thread: https://github.com/Qiskit/qiskit-terra/pull/8005#discussion_r966191018 """ block1 = pulse.ScheduleBlock(alignment_context=self.sequential_context) block1 += pulse.Play(self.test_waveform0, self.d0) block1 += pulse.Play(self.test_waveform0, self.d0) block1 += pulse.Play(self.test_waveform0, self.d1) block2 = pulse.ScheduleBlock(alignment_context=self.sequential_context) block2 += pulse.Play(self.test_waveform0, self.d0) block2 += pulse.Play(self.test_waveform0, self.d1) block2 += pulse.Play(self.test_waveform0, self.d0) self.assertNotEqual(block1, block2) def test_instruction_in_order_sequential(self): """Test equality is True if two blocks have instructions in same order.""" block1 = pulse.ScheduleBlock(alignment_context=self.sequential_context) block1 += pulse.Play(self.test_waveform0, self.d0) block1 += pulse.Play(self.test_waveform0, self.d1) block2 = pulse.ScheduleBlock(alignment_context=self.sequential_context) block2 += pulse.Play(self.test_waveform0, self.d0) block2 += pulse.Play(self.test_waveform0, self.d1) self.assertEqual(block1, block2) def test_instruction_out_of_order_equispaced(self): """Test equality is False if two blocks have instructions in different order.""" block1 = pulse.ScheduleBlock(alignment_context=self.equispaced_context) block1 += pulse.Play(self.test_waveform0, self.d0) block1 += pulse.Play(self.test_waveform0, self.d1) block2 = pulse.ScheduleBlock(alignment_context=self.equispaced_context) block2 += pulse.Play(self.test_waveform0, self.d1) block2 += pulse.Play(self.test_waveform0, self.d0) self.assertNotEqual(block1, block2) def test_instruction_in_order_equispaced(self): """Test equality is True if two blocks have instructions in same order.""" block1 = pulse.ScheduleBlock(alignment_context=self.equispaced_context) block1 += pulse.Play(self.test_waveform0, self.d0) block1 += pulse.Play(self.test_waveform0, self.d1) block2 = pulse.ScheduleBlock(alignment_context=self.equispaced_context) block2 += pulse.Play(self.test_waveform0, self.d0) block2 += pulse.Play(self.test_waveform0, self.d1) self.assertEqual(block1, block2) def test_instruction_out_of_order_func(self): """Test equality is False if two blocks have instructions in different order.""" block1 = pulse.ScheduleBlock(alignment_context=self.func_context) block1 += pulse.Play(self.test_waveform0, self.d0) block1 += pulse.Play(self.test_waveform0, self.d1) block2 = pulse.ScheduleBlock(alignment_context=self.func_context) block2 += pulse.Play(self.test_waveform0, self.d1) block2 += pulse.Play(self.test_waveform0, self.d0) self.assertNotEqual(block1, block2) def test_instruction_in_order_func(self): """Test equality is True if two blocks have instructions in same order.""" block1 = pulse.ScheduleBlock(alignment_context=self.func_context) block1 += pulse.Play(self.test_waveform0, self.d0) block1 += pulse.Play(self.test_waveform0, self.d1) block2 = pulse.ScheduleBlock(alignment_context=self.func_context) block2 += pulse.Play(self.test_waveform0, self.d0) block2 += pulse.Play(self.test_waveform0, self.d1) self.assertEqual(block1, block2) def test_instrution_in_oder_but_different_node(self): """Test equality is False if two blocks have different instructions.""" block1 = pulse.ScheduleBlock(alignment_context=self.left_context) block1 += pulse.Play(self.test_waveform0, self.d0) block1 += pulse.Play(self.test_waveform1, self.d1) block2 = pulse.ScheduleBlock(alignment_context=self.left_context) block2 += pulse.Play(self.test_waveform0, self.d0) block2 += pulse.Play(self.test_waveform0, self.d1) self.assertNotEqual(block1, block2) def test_instruction_out_of_order_complex_equal(self): """Test complex schedule equality can be correctly evaluated.""" block1_a = pulse.ScheduleBlock(alignment_context=self.left_context) block1_a += pulse.Delay(10, self.d0) block1_a += pulse.Play(self.test_waveform1, self.d1) block1_a += pulse.Play(self.test_waveform0, self.d0) block1_b = pulse.ScheduleBlock(alignment_context=self.left_context) block1_b += pulse.Play(self.test_waveform1, self.d1) block1_b += pulse.Delay(10, self.d0) block1_b += pulse.Play(self.test_waveform0, self.d0) block2_a = pulse.ScheduleBlock(alignment_context=self.right_context) block2_a += block1_a block2_a += block1_b block2_a += block1_a block2_b = pulse.ScheduleBlock(alignment_context=self.right_context) block2_b += block1_a block2_b += block1_a block2_b += block1_b self.assertEqual(block2_a, block2_b) def test_instruction_out_of_order_complex_not_equal(self): """Test complex schedule equality can be correctly evaluated.""" block1_a = pulse.ScheduleBlock(alignment_context=self.left_context) block1_a += pulse.Play(self.test_waveform0, self.d0) block1_a += pulse.Play(self.test_waveform1, self.d1) block1_a += pulse.Delay(10, self.d0) block1_b = pulse.ScheduleBlock(alignment_context=self.left_context) block1_b += pulse.Play(self.test_waveform1, self.d1) block1_b += pulse.Delay(10, self.d0) block1_b += pulse.Play(self.test_waveform0, self.d0) block2_a = pulse.ScheduleBlock(alignment_context=self.right_context) block2_a += block1_a block2_a += block1_b block2_a += block1_a block2_b = pulse.ScheduleBlock(alignment_context=self.right_context) block2_b += block1_a block2_b += block1_a block2_b += block1_b self.assertNotEqual(block2_a, block2_b) class TestParametrizedBlockOperation(BaseTestBlock): """Test fundamental operation with parametrization.""" def setUp(self): super().setUp() self.amp0 = circuit.Parameter("amp0") self.amp1 = circuit.Parameter("amp1") self.dur0 = circuit.Parameter("dur0") self.dur1 = circuit.Parameter("dur1") self.test_par_waveform0 = pulse.Constant(self.dur0, self.amp0) self.test_par_waveform1 = pulse.Constant(self.dur1, self.amp1) def test_report_parameter_assignment(self): """Test duration assignment check.""" block = pulse.ScheduleBlock() block += pulse.Play(self.test_par_waveform0, self.d0) # check parameter evaluation mechanism self.assertTrue(block.is_parameterized()) self.assertFalse(block.is_schedulable()) # assign duration block = block.assign_parameters({self.dur0: 200}) self.assertTrue(block.is_parameterized()) self.assertTrue(block.is_schedulable()) def test_cannot_get_duration_if_not_assigned(self): """Test raise error when duration is not assigned.""" block = pulse.ScheduleBlock() block += pulse.Play(self.test_par_waveform0, self.d0) with self.assertRaises(PulseError): # pylint: disable=pointless-statement block.duration def test_get_assigend_duration(self): """Test duration is correctly evaluated.""" block = pulse.ScheduleBlock() block += pulse.Play(self.test_par_waveform0, self.d0) block += pulse.Play(self.test_waveform0, self.d0) block = block.assign_parameters({self.dur0: 300}) self.assertEqual(block.duration, 400) def test_nested_parametrized_instructions(self): """Test parameters of nested schedule can be assigned.""" test_waveform = pulse.Constant(100, self.amp0) param_sched = pulse.Schedule(pulse.Play(test_waveform, self.d0)) with self.assertWarns(DeprecationWarning): call_inst = pulse.instructions.Call(param_sched) sub_block = pulse.ScheduleBlock() sub_block += call_inst block = pulse.ScheduleBlock() block += sub_block self.assertTrue(block.is_parameterized()) # assign durations block = block.assign_parameters({self.amp0: 0.1}) self.assertFalse(block.is_parameterized()) def test_equality_of_parametrized_channels(self): """Test check equality of blocks involving parametrized channels.""" par_ch = circuit.Parameter("ch") block1 = pulse.ScheduleBlock(alignment_context=self.left_context) block1 += pulse.Play(self.test_waveform0, pulse.DriveChannel(par_ch)) block1 += pulse.Play(self.test_par_waveform0, self.d0) block2 = pulse.ScheduleBlock(alignment_context=self.left_context) block2 += pulse.Play(self.test_par_waveform0, self.d0) block2 += pulse.Play(self.test_waveform0, pulse.DriveChannel(par_ch)) self.assertEqual(block1, block2) block1_assigned = block1.assign_parameters({par_ch: 1}) block2_assigned = block2.assign_parameters({par_ch: 1}) self.assertEqual(block1_assigned, block2_assigned) def test_replace_parametrized_instruction(self): """Test parametrized instruction can updated with parameter table.""" block = pulse.ScheduleBlock() block += pulse.Play(self.test_par_waveform0, self.d0) block += pulse.Delay(100, self.d0) block += pulse.Play(self.test_waveform0, self.d0) replaced = block.replace( pulse.Play(self.test_par_waveform0, self.d0), pulse.Play(self.test_par_waveform1, self.d0), ) self.assertTrue(replaced.is_parameterized()) # check assign parameters replaced_assigned = replaced.assign_parameters({self.dur1: 100, self.amp1: 0.1}) self.assertFalse(replaced_assigned.is_parameterized()) def test_parametrized_context(self): """Test parametrize context parameter.""" duration = circuit.Parameter("dur") param_context = transforms.AlignEquispaced(duration=duration) block = pulse.ScheduleBlock(alignment_context=param_context) block += pulse.Delay(10, self.d0) block += pulse.Delay(10, self.d0) block += pulse.Delay(10, self.d0) block += pulse.Delay(10, self.d0) self.assertTrue(block.is_parameterized()) self.assertFalse(block.is_schedulable()) block.assign_parameters({duration: 100}, inplace=True) self.assertFalse(block.is_parameterized()) self.assertTrue(block.is_schedulable()) ref_sched = pulse.Schedule() ref_sched = ref_sched.insert(0, pulse.Delay(10, self.d0)) ref_sched = ref_sched.insert(30, pulse.Delay(10, self.d0)) ref_sched = ref_sched.insert(60, pulse.Delay(10, self.d0)) ref_sched = ref_sched.insert(90, pulse.Delay(10, self.d0)) self.assertScheduleEqual(block, ref_sched) class TestBlockFilter(BaseTestBlock): """Test ScheduleBlock filtering methods.""" def test_filter_channels(self): """Test filtering over channels.""" with pulse.build() as blk: pulse.play(self.test_waveform0, self.d0) pulse.delay(10, self.d0) pulse.play(self.test_waveform1, self.d1) filtered_blk = self._filter_and_test_consistency(blk, channels=[self.d0]) self.assertEqual(len(filtered_blk.channels), 1) self.assertTrue(self.d0 in filtered_blk.channels) with pulse.build() as ref_blk: pulse.play(self.test_waveform0, self.d0) pulse.delay(10, self.d0) self.assertEqual(filtered_blk, ref_blk) filtered_blk = self._filter_and_test_consistency(blk, channels=[self.d1]) self.assertEqual(len(filtered_blk.channels), 1) self.assertTrue(self.d1 in filtered_blk.channels) with pulse.build() as ref_blk: pulse.play(self.test_waveform1, self.d1) self.assertEqual(filtered_blk, ref_blk) filtered_blk = self._filter_and_test_consistency(blk, channels=[self.d0, self.d1]) self.assertEqual(len(filtered_blk.channels), 2) for ch in [self.d0, self.d1]: self.assertTrue(ch in filtered_blk.channels) self.assertEqual(filtered_blk, blk) def test_filter_channels_nested_block(self): """Test filtering over channels in a nested block.""" with pulse.build() as blk: with pulse.align_sequential(): pulse.play(self.test_waveform0, self.d0) pulse.delay(5, self.d0) with pulse.build(self.backend) as cx_blk: pulse.cx(0, 1) pulse.call(cx_blk) for ch in [self.d0, self.d1, pulse.ControlChannel(0)]: filtered_blk = self._filter_and_test_consistency(blk, channels=[ch]) self.assertEqual(len(filtered_blk.channels), 1) self.assertTrue(ch in filtered_blk.channels) def test_filter_inst_types(self): """Test filtering on instruction types.""" with pulse.build() as blk: pulse.acquire(5, pulse.AcquireChannel(0), pulse.MemorySlot(0)) with pulse.build() as blk_internal: pulse.play(self.test_waveform1, self.d1) pulse.call(blk_internal) pulse.reference(name="dummy_reference") pulse.delay(10, self.d0) pulse.play(self.test_waveform0, self.d0) pulse.barrier(self.d0, self.d1, pulse.AcquireChannel(0), pulse.MemorySlot(0)) pulse.set_frequency(10, self.d0) pulse.shift_frequency(5, self.d1) pulse.set_phase(3.14 / 4.0, self.d0) pulse.shift_phase(-3.14 / 2.0, self.d1) pulse.snapshot(label="dummy_snapshot") # test filtering Acquire filtered_blk = self._filter_and_test_consistency(blk, instruction_types=[pulse.Acquire]) self.assertEqual(len(filtered_blk.blocks), 1) self.assertIsInstance(filtered_blk.blocks[0], pulse.Acquire) self.assertEqual(len(filtered_blk.channels), 2) # test filtering Reference filtered_blk = self._filter_and_test_consistency( blk, instruction_types=[pulse.instructions.Reference] ) self.assertEqual(len(filtered_blk.blocks), 1) self.assertIsInstance(filtered_blk.blocks[0], pulse.instructions.Reference) # test filtering Delay filtered_blk = self._filter_and_test_consistency(blk, instruction_types=[pulse.Delay]) self.assertEqual(len(filtered_blk.blocks), 1) self.assertIsInstance(filtered_blk.blocks[0], pulse.Delay) self.assertEqual(len(filtered_blk.channels), 1) # test filtering Play filtered_blk = self._filter_and_test_consistency(blk, instruction_types=[pulse.Play]) self.assertEqual(len(filtered_blk.blocks), 2) self.assertIsInstance(filtered_blk.blocks[0].blocks[0], pulse.Play) self.assertIsInstance(filtered_blk.blocks[1], pulse.Play) self.assertEqual(len(filtered_blk.channels), 2) # test filtering RelativeBarrier filtered_blk = self._filter_and_test_consistency( blk, instruction_types=[pulse.instructions.RelativeBarrier] ) self.assertEqual(len(filtered_blk.blocks), 1) self.assertIsInstance(filtered_blk.blocks[0], pulse.instructions.RelativeBarrier) self.assertEqual(len(filtered_blk.channels), 4) # test filtering SetFrequency filtered_blk = self._filter_and_test_consistency( blk, instruction_types=[pulse.SetFrequency] ) self.assertEqual(len(filtered_blk.blocks), 1) self.assertIsInstance(filtered_blk.blocks[0], pulse.SetFrequency) self.assertEqual(len(filtered_blk.channels), 1) # test filtering ShiftFrequency filtered_blk = self._filter_and_test_consistency( blk, instruction_types=[pulse.ShiftFrequency] ) self.assertEqual(len(filtered_blk.blocks), 1) self.assertIsInstance(filtered_blk.blocks[0], pulse.ShiftFrequency) self.assertEqual(len(filtered_blk.channels), 1) # test filtering SetPhase filtered_blk = self._filter_and_test_consistency(blk, instruction_types=[pulse.SetPhase]) self.assertEqual(len(filtered_blk.blocks), 1) self.assertIsInstance(filtered_blk.blocks[0], pulse.SetPhase) self.assertEqual(len(filtered_blk.channels), 1) # test filtering ShiftPhase filtered_blk = self._filter_and_test_consistency(blk, instruction_types=[pulse.ShiftPhase]) self.assertEqual(len(filtered_blk.blocks), 1) self.assertIsInstance(filtered_blk.blocks[0], pulse.ShiftPhase) self.assertEqual(len(filtered_blk.channels), 1) # test filtering SnapShot filtered_blk = self._filter_and_test_consistency(blk, instruction_types=[pulse.Snapshot]) self.assertEqual(len(filtered_blk.blocks), 1) self.assertIsInstance(filtered_blk.blocks[0], pulse.Snapshot) self.assertEqual(len(filtered_blk.channels), 1) def test_filter_functionals(self): """Test functional filtering.""" with pulse.build() as blk: pulse.play(self.test_waveform0, self.d0, "play0") pulse.delay(10, self.d0, "delay0") with pulse.build() as blk_internal: pulse.play(self.test_waveform1, self.d1, "play1") pulse.call(blk_internal) pulse.play(self.test_waveform1, self.d1) def filter_with_inst_name(inst: pulse.Instruction) -> bool: try: if isinstance(inst.name, str): match_obj = re.search(pattern="play", string=inst.name) if match_obj is not None: return True except AttributeError: pass return False filtered_blk = self._filter_and_test_consistency(blk, filter_with_inst_name) self.assertEqual(len(filtered_blk.blocks), 2) self.assertIsInstance(filtered_blk.blocks[0], pulse.Play) self.assertIsInstance(filtered_blk.blocks[1].blocks[0], pulse.Play) self.assertEqual(len(filtered_blk.channels), 2) def test_filter_multiple(self): """Test filter composition.""" with pulse.build() as blk: pulse.play(pulse.Constant(100, 0.1, name="play0"), self.d0) pulse.delay(10, self.d0, "delay0") with pulse.build(name="internal_blk") as blk_internal: pulse.play(pulse.Constant(50, 0.1, name="play1"), self.d0) pulse.call(blk_internal) pulse.barrier(self.d0, self.d1) pulse.play(pulse.Constant(100, 0.1, name="play2"), self.d1) def filter_with_pulse_name(inst: pulse.Instruction) -> bool: try: if isinstance(inst.pulse.name, str): match_obj = re.search(pattern="play", string=inst.pulse.name) if match_obj is not None: return True except AttributeError: pass return False filtered_blk = self._filter_and_test_consistency( blk, filter_with_pulse_name, channels=[self.d1], instruction_types=[pulse.Play] ) self.assertEqual(len(filtered_blk.blocks), 1) self.assertIsInstance(filtered_blk.blocks[0], pulse.Play) self.assertEqual(len(filtered_blk.channels), 1) def _filter_and_test_consistency( self, sched_blk: pulse.ScheduleBlock, *args: Any, **kwargs: Any ) -> pulse.ScheduleBlock: """ Returns sched_blk.filter(*args, **kwargs), including a test that sched_blk.filter | sched_blk.exclude == sched_blk in terms of instructions. """ filtered = sched_blk.filter(*args, **kwargs) excluded = sched_blk.exclude(*args, **kwargs) def list_instructions(blk: pulse.ScheduleBlock) -> List[pulse.Instruction]: insts = [] for element in blk.blocks: if isinstance(element, pulse.ScheduleBlock): inner_insts = list_instructions(element) if len(inner_insts) != 0: insts.extend(inner_insts) elif isinstance(element, pulse.Instruction): insts.append(element) return insts sum_insts = list_instructions(filtered) + list_instructions(excluded) ref_insts = list_instructions(sched_blk) self.assertEqual(len(sum_insts), len(ref_insts)) self.assertTrue(all(inst in ref_insts for inst in sum_insts)) return filtered
https://github.com/swe-train/qiskit__qiskit
swe-train
# 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. """Test pulse builder context utilities.""" from math import pi import numpy as np from qiskit import circuit, compiler, pulse from qiskit.pulse import builder, exceptions, macros from qiskit.pulse.instructions import directives from qiskit.pulse.transforms import target_qobj_transform from qiskit.test import QiskitTestCase from qiskit.providers.fake_provider import FakeOpenPulse2Q from qiskit.providers.fake_provider.utils.configurable_backend import ( ConfigurableFakeBackend as ConfigurableBackend, ) from qiskit.pulse import library, instructions class TestBuilder(QiskitTestCase): """Test the pulse builder context.""" def setUp(self): super().setUp() self.backend = FakeOpenPulse2Q() self.configuration = self.backend.configuration() self.defaults = self.backend.defaults() self.inst_map = self.defaults.instruction_schedule_map def assertScheduleEqual(self, program, target): """Assert an error when two pulse programs are not equal. .. note:: Two programs are converted into standard execution format then compared. """ self.assertEqual(target_qobj_transform(program), target_qobj_transform(target)) class TestBuilderBase(TestBuilder): """Test builder base.""" def test_schedule_supplied(self): """Test that schedule is used if it is supplied to the builder.""" d0 = pulse.DriveChannel(0) with pulse.build(name="reference") as reference: with pulse.align_sequential(): pulse.delay(10, d0) with pulse.build(schedule=reference) as schedule: pass self.assertScheduleEqual(schedule, reference) self.assertEqual(schedule.name, "reference") def test_default_alignment_left(self): """Test default left alignment setting.""" d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(0) with pulse.build(default_alignment="left") as schedule: pulse.delay(10, d0) pulse.delay(20, d1) with pulse.build(self.backend) as reference: with pulse.align_left(): pulse.delay(10, d0) pulse.delay(20, d1) self.assertScheduleEqual(schedule, reference) def test_default_alignment_right(self): """Test default right alignment setting.""" d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(0) with pulse.build(default_alignment="right") as schedule: pulse.delay(10, d0) pulse.delay(20, d1) with pulse.build() as reference: with pulse.align_right(): pulse.delay(10, d0) pulse.delay(20, d1) self.assertScheduleEqual(schedule, reference) def test_default_alignment_sequential(self): """Test default sequential alignment setting.""" d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(0) with pulse.build(default_alignment="sequential") as schedule: pulse.delay(10, d0) pulse.delay(20, d1) with pulse.build() as reference: with pulse.align_sequential(): pulse.delay(10, d0) pulse.delay(20, d1) self.assertScheduleEqual(schedule, reference) class TestContexts(TestBuilder): """Test builder contexts.""" def test_align_sequential(self): """Test the sequential alignment context.""" d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) with pulse.build() as schedule: with pulse.align_sequential(): pulse.delay(3, d0) pulse.delay(5, d1) pulse.delay(7, d0) reference = pulse.Schedule() # d0 reference.insert(0, instructions.Delay(3, d0), inplace=True) reference.insert(8, instructions.Delay(7, d0), inplace=True) # d1 reference.insert(3, instructions.Delay(5, d1), inplace=True) self.assertScheduleEqual(schedule, reference) def test_align_left(self): """Test the left alignment context.""" d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) d2 = pulse.DriveChannel(2) with pulse.build() as schedule: with pulse.align_left(): pulse.delay(11, d2) pulse.delay(3, d0) with pulse.align_left(): pulse.delay(5, d1) pulse.delay(7, d0) reference = pulse.Schedule() # d0 reference.insert(0, instructions.Delay(3, d0), inplace=True) reference.insert(3, instructions.Delay(7, d0), inplace=True) # d1 reference.insert(3, instructions.Delay(5, d1), inplace=True) # d2 reference.insert(0, instructions.Delay(11, d2), inplace=True) self.assertScheduleEqual(schedule, reference) def test_align_right(self): """Test the right alignment context.""" d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) d2 = pulse.DriveChannel(2) with pulse.build() as schedule: with pulse.align_right(): with pulse.align_right(): pulse.delay(11, d2) pulse.delay(3, d0) pulse.delay(13, d0) pulse.delay(5, d1) reference = pulse.Schedule() # d0 reference.insert(8, instructions.Delay(3, d0), inplace=True) reference.insert(11, instructions.Delay(13, d0), inplace=True) # d1 reference.insert(19, instructions.Delay(5, d1), inplace=True) # d2 reference.insert(0, instructions.Delay(11, d2), inplace=True) self.assertScheduleEqual(schedule, reference) def test_transpiler_settings(self): """Test the transpiler settings context. Tests that two cx gates are optimized away with higher optimization level. """ twice_cx_qc = circuit.QuantumCircuit(2) twice_cx_qc.cx(0, 1) twice_cx_qc.cx(0, 1) with pulse.build(self.backend) as schedule: with pulse.transpiler_settings(optimization_level=0): builder.call(twice_cx_qc) self.assertNotEqual(len(schedule.instructions), 0) with pulse.build(self.backend) as schedule: with pulse.transpiler_settings(optimization_level=3): builder.call(twice_cx_qc) self.assertEqual(len(schedule.instructions), 0) def test_scheduler_settings(self): """Test the circuit scheduler settings context.""" inst_map = pulse.InstructionScheduleMap() d0 = pulse.DriveChannel(0) test_x_sched = pulse.Schedule() test_x_sched += instructions.Delay(10, d0) inst_map.add("x", (0,), test_x_sched) ref_sched = pulse.Schedule() with self.assertWarns(DeprecationWarning): ref_sched += pulse.instructions.Call(test_x_sched) x_qc = circuit.QuantumCircuit(2) x_qc.x(0) with pulse.build(backend=self.backend) as schedule: with pulse.transpiler_settings(basis_gates=["x"]): with pulse.circuit_scheduler_settings(inst_map=inst_map): builder.call(x_qc) self.assertScheduleEqual(schedule, ref_sched) def test_phase_offset(self): """Test the phase offset context.""" d0 = pulse.DriveChannel(0) with pulse.build() as schedule: with pulse.phase_offset(3.14, d0): pulse.delay(10, d0) reference = pulse.Schedule() reference += instructions.ShiftPhase(3.14, d0) reference += instructions.Delay(10, d0) reference += instructions.ShiftPhase(-3.14, d0) self.assertScheduleEqual(schedule, reference) def test_frequency_offset(self): """Test the frequency offset context.""" d0 = pulse.DriveChannel(0) with pulse.build() as schedule: with pulse.frequency_offset(1e9, d0): pulse.delay(10, d0) reference = pulse.Schedule() reference += instructions.ShiftFrequency(1e9, d0) reference += instructions.Delay(10, d0) reference += instructions.ShiftFrequency(-1e9, d0) self.assertScheduleEqual(schedule, reference) def test_phase_compensated_frequency_offset(self): """Test that the phase offset context properly compensates for phase accumulation.""" d0 = pulse.DriveChannel(0) with pulse.build(self.backend) as schedule: with pulse.frequency_offset(1e9, d0, compensate_phase=True): pulse.delay(10, d0) reference = pulse.Schedule() reference += instructions.ShiftFrequency(1e9, d0) reference += instructions.Delay(10, d0) reference += instructions.ShiftPhase( -2 * np.pi * ((1e9 * 10 * self.configuration.dt) % 1), d0 ) reference += instructions.ShiftFrequency(-1e9, d0) self.assertScheduleEqual(schedule, reference) class TestChannels(TestBuilder): """Test builder channels.""" def test_drive_channel(self): """Text context builder drive channel.""" with pulse.build(self.backend): self.assertEqual(pulse.drive_channel(0), pulse.DriveChannel(0)) def test_measure_channel(self): """Text context builder measure channel.""" with pulse.build(self.backend): self.assertEqual(pulse.measure_channel(0), pulse.MeasureChannel(0)) def test_acquire_channel(self): """Text context builder acquire channel.""" with pulse.build(self.backend): self.assertEqual(pulse.acquire_channel(0), pulse.AcquireChannel(0)) def test_control_channel(self): """Text context builder control channel.""" with pulse.build(self.backend): self.assertEqual(pulse.control_channels(0, 1)[0], pulse.ControlChannel(0)) class TestInstructions(TestBuilder): """Test builder instructions.""" def test_delay(self): """Test delay instruction.""" d0 = pulse.DriveChannel(0) with pulse.build() as schedule: pulse.delay(10, d0) reference = pulse.Schedule() reference += instructions.Delay(10, d0) self.assertScheduleEqual(schedule, reference) def test_play_parametric_pulse(self): """Test play instruction with parametric pulse.""" d0 = pulse.DriveChannel(0) test_pulse = library.Constant(10, 1.0) with pulse.build() as schedule: pulse.play(test_pulse, d0) reference = pulse.Schedule() reference += instructions.Play(test_pulse, d0) self.assertScheduleEqual(schedule, reference) def test_play_sample_pulse(self): """Test play instruction with sample pulse.""" d0 = pulse.DriveChannel(0) test_pulse = library.Waveform([0.0, 0.0]) with pulse.build() as schedule: pulse.play(test_pulse, d0) reference = pulse.Schedule() reference += instructions.Play(test_pulse, d0) self.assertScheduleEqual(schedule, reference) def test_play_array_pulse(self): """Test play instruction on an array directly.""" d0 = pulse.DriveChannel(0) test_array = np.array([0.0, 0.0], dtype=np.complex_) with pulse.build() as schedule: pulse.play(test_array, d0) reference = pulse.Schedule() test_pulse = pulse.Waveform(test_array) reference += instructions.Play(test_pulse, d0) self.assertScheduleEqual(schedule, reference) def test_play_name_argument(self): """Test name argument for play instruction.""" d0 = pulse.DriveChannel(0) test_pulse = library.Constant(10, 1.0) with pulse.build() as schedule: pulse.play(test_pulse, channel=d0, name="new_name") self.assertEqual(schedule.instructions[0][1].name, "new_name") def test_acquire_memory_slot(self): """Test acquire instruction into memory slot.""" acquire0 = pulse.AcquireChannel(0) mem0 = pulse.MemorySlot(0) with pulse.build() as schedule: pulse.acquire(10, acquire0, mem0) reference = pulse.Schedule() reference += pulse.Acquire(10, acquire0, mem_slot=mem0) self.assertScheduleEqual(schedule, reference) def test_acquire_register_slot(self): """Test acquire instruction into register slot.""" acquire0 = pulse.AcquireChannel(0) reg0 = pulse.RegisterSlot(0) with pulse.build() as schedule: pulse.acquire(10, acquire0, reg0) reference = pulse.Schedule() reference += pulse.Acquire(10, acquire0, reg_slot=reg0) self.assertScheduleEqual(schedule, reference) def test_acquire_qubit(self): """Test acquire instruction on qubit.""" acquire0 = pulse.AcquireChannel(0) mem0 = pulse.MemorySlot(0) with pulse.build() as schedule: pulse.acquire(10, 0, mem0) reference = pulse.Schedule() reference += pulse.Acquire(10, acquire0, mem_slot=mem0) self.assertScheduleEqual(schedule, reference) def test_instruction_name_argument(self): """Test setting the name of an instruction.""" d0 = pulse.DriveChannel(0) for instruction_method in [ pulse.delay, pulse.set_frequency, pulse.set_phase, pulse.shift_frequency, pulse.shift_phase, ]: with pulse.build() as schedule: instruction_method(0, d0, name="instruction_name") self.assertEqual(schedule.instructions[0][1].name, "instruction_name") def test_set_frequency(self): """Test set frequency instruction.""" d0 = pulse.DriveChannel(0) with pulse.build() as schedule: pulse.set_frequency(1e9, d0) reference = pulse.Schedule() reference += instructions.SetFrequency(1e9, d0) self.assertScheduleEqual(schedule, reference) def test_shift_frequency(self): """Test shift frequency instruction.""" d0 = pulse.DriveChannel(0) with pulse.build() as schedule: pulse.shift_frequency(0.1e9, d0) reference = pulse.Schedule() reference += instructions.ShiftFrequency(0.1e9, d0) self.assertScheduleEqual(schedule, reference) def test_set_phase(self): """Test set phase instruction.""" d0 = pulse.DriveChannel(0) with pulse.build() as schedule: pulse.set_phase(3.14, d0) reference = pulse.Schedule() reference += instructions.SetPhase(3.14, d0) self.assertScheduleEqual(schedule, reference) def test_shift_phase(self): """Test shift phase instruction.""" d0 = pulse.DriveChannel(0) with pulse.build() as schedule: pulse.shift_phase(3.14, d0) reference = pulse.Schedule() reference += instructions.ShiftPhase(3.14, d0) self.assertScheduleEqual(schedule, reference) def test_snapshot(self): """Test snapshot instruction.""" with pulse.build() as schedule: pulse.snapshot("test", "state") reference = pulse.Schedule() reference += instructions.Snapshot("test", "state") self.assertScheduleEqual(schedule, reference) class TestDirectives(TestBuilder): """Test builder directives.""" def test_barrier_with_align_right(self): """Test barrier directive with right alignment context.""" d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) d2 = pulse.DriveChannel(2) with pulse.build() as schedule: with pulse.align_right(): pulse.delay(3, d0) pulse.barrier(d0, d1, d2) pulse.delay(11, d2) with pulse.align_right(): pulse.delay(5, d1) pulse.delay(7, d0) reference = pulse.Schedule() # d0 reference.insert(0, instructions.Delay(3, d0), inplace=True) reference.insert(7, instructions.Delay(7, d0), inplace=True) # d1 reference.insert(9, instructions.Delay(5, d1), inplace=True) # d2 reference.insert(3, instructions.Delay(11, d2), inplace=True) self.assertScheduleEqual(schedule, reference) def test_barrier_with_align_left(self): """Test barrier directive with left alignment context.""" d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) d2 = pulse.DriveChannel(2) with pulse.build() as schedule: with pulse.align_left(): pulse.delay(3, d0) pulse.barrier(d0, d1, d2) pulse.delay(11, d2) with pulse.align_left(): pulse.delay(5, d1) pulse.delay(7, d0) reference = pulse.Schedule() # d0 reference.insert(0, instructions.Delay(3, d0), inplace=True) reference.insert(3, instructions.Delay(7, d0), inplace=True) # d1 reference.insert(3, instructions.Delay(5, d1), inplace=True) # d2 reference.insert(3, instructions.Delay(11, d2), inplace=True) self.assertScheduleEqual(schedule, reference) def test_barrier_on_qubits(self): """Test barrier directive on qubits.""" with pulse.build(self.backend) as schedule: pulse.barrier(0, 1) reference = pulse.ScheduleBlock() reference += directives.RelativeBarrier( pulse.DriveChannel(0), pulse.DriveChannel(1), pulse.MeasureChannel(0), pulse.MeasureChannel(1), pulse.ControlChannel(0), pulse.ControlChannel(1), pulse.AcquireChannel(0), pulse.AcquireChannel(1), ) self.assertEqual(schedule, reference) def test_trivial_barrier(self): """Test that trivial barrier is not added.""" with pulse.build() as schedule: pulse.barrier(pulse.DriveChannel(0)) self.assertEqual(schedule, pulse.ScheduleBlock()) class TestUtilities(TestBuilder): """Test builder utilities.""" def test_active_backend(self): """Test getting active builder backend.""" with pulse.build(self.backend): self.assertEqual(pulse.active_backend(), self.backend) def test_append_schedule(self): """Test appending a schedule to the active builder.""" d0 = pulse.DriveChannel(0) reference = pulse.Schedule() reference += instructions.Delay(10, d0) with pulse.build() as schedule: builder.call(reference) self.assertScheduleEqual(schedule, reference) def test_append_instruction(self): """Test appending an instruction to the active builder.""" d0 = pulse.DriveChannel(0) instruction = instructions.Delay(10, d0) with pulse.build() as schedule: builder.append_instruction(instruction) self.assertScheduleEqual(schedule, (0, instruction)) def test_qubit_channels(self): """Test getting the qubit channels of the active builder's backend.""" with pulse.build(self.backend): qubit_channels = pulse.qubit_channels(0) self.assertEqual( qubit_channels, { pulse.DriveChannel(0), pulse.MeasureChannel(0), pulse.AcquireChannel(0), pulse.ControlChannel(0), pulse.ControlChannel(1), }, ) def test_active_transpiler_settings(self): """Test setting settings of active builder's transpiler.""" with pulse.build(self.backend): self.assertFalse(pulse.active_transpiler_settings()) with pulse.transpiler_settings(test_setting=1): self.assertEqual(pulse.active_transpiler_settings()["test_setting"], 1) def test_active_circuit_scheduler_settings(self): """Test setting settings of active builder's circuit scheduler.""" with pulse.build(self.backend): self.assertFalse(pulse.active_circuit_scheduler_settings()) with pulse.circuit_scheduler_settings(test_setting=1): self.assertEqual(pulse.active_circuit_scheduler_settings()["test_setting"], 1) def test_num_qubits(self): """Test builder utility to get number of qubits.""" with pulse.build(self.backend): self.assertEqual(pulse.num_qubits(), 2) def test_samples_to_seconds(self): """Test samples to time""" config = self.backend.configuration() config.dt = 0.1 with pulse.build(self.backend): time = pulse.samples_to_seconds(100) self.assertTrue(isinstance(time, float)) self.assertEqual(pulse.samples_to_seconds(100), 10) def test_samples_to_seconds_array(self): """Test samples to time (array format).""" config = self.backend.configuration() config.dt = 0.1 with pulse.build(self.backend): samples = np.array([100, 200, 300]) times = pulse.samples_to_seconds(samples) self.assertTrue(np.issubdtype(times.dtype, np.floating)) np.testing.assert_allclose(times, np.array([10, 20, 30])) def test_seconds_to_samples(self): """Test time to samples""" config = self.backend.configuration() config.dt = 0.1 with pulse.build(self.backend): samples = pulse.seconds_to_samples(10) self.assertTrue(isinstance(samples, int)) self.assertEqual(pulse.seconds_to_samples(10), 100) def test_seconds_to_samples_array(self): """Test time to samples (array format).""" config = self.backend.configuration() config.dt = 0.1 with pulse.build(self.backend): times = np.array([10, 20, 30]) samples = pulse.seconds_to_samples(times) self.assertTrue(np.issubdtype(samples.dtype, np.integer)) np.testing.assert_allclose(pulse.seconds_to_samples(times), np.array([100, 200, 300])) class TestMacros(TestBuilder): """Test builder macros.""" def test_macro(self): """Test builder macro decorator.""" @pulse.macro def nested(a): pulse.play(pulse.Gaussian(100, a, 20), pulse.drive_channel(0)) return a * 2 @pulse.macro def test(): pulse.play(pulse.Constant(100, 1.0), pulse.drive_channel(0)) output = nested(0.5) return output with pulse.build(self.backend) as schedule: output = test() self.assertEqual(output, 0.5 * 2) reference = pulse.Schedule() reference += pulse.Play(pulse.Constant(100, 1.0), pulse.DriveChannel(0)) reference += pulse.Play(pulse.Gaussian(100, 0.5, 20), pulse.DriveChannel(0)) self.assertScheduleEqual(schedule, reference) def test_measure(self): """Test utility function - measure.""" with pulse.build(self.backend) as schedule: reg = pulse.measure(0) self.assertEqual(reg, pulse.MemorySlot(0)) reference = macros.measure( qubits=[0], inst_map=self.inst_map, meas_map=self.configuration.meas_map ) self.assertScheduleEqual(schedule, reference) def test_measure_multi_qubits(self): """Test utility function - measure with multi qubits.""" with pulse.build(self.backend) as schedule: regs = pulse.measure([0, 1]) self.assertListEqual(regs, [pulse.MemorySlot(0), pulse.MemorySlot(1)]) reference = macros.measure( qubits=[0, 1], inst_map=self.inst_map, meas_map=self.configuration.meas_map ) self.assertScheduleEqual(schedule, reference) def test_measure_all(self): """Test utility function - measure.""" with pulse.build(self.backend) as schedule: regs = pulse.measure_all() self.assertEqual(regs, [pulse.MemorySlot(0), pulse.MemorySlot(1)]) reference = macros.measure_all(self.backend) self.assertScheduleEqual(schedule, reference) backend_100q = ConfigurableBackend("100q", 100) with pulse.build(backend_100q) as schedule: regs = pulse.measure_all() reference = backend_100q.defaults().instruction_schedule_map.get( "measure", list(range(100)) ) self.assertScheduleEqual(schedule, reference) def test_delay_qubit(self): """Test delaying on a qubit macro.""" with pulse.build(self.backend) as schedule: pulse.delay_qubits(10, 0) d0 = pulse.DriveChannel(0) m0 = pulse.MeasureChannel(0) a0 = pulse.AcquireChannel(0) u0 = pulse.ControlChannel(0) u1 = pulse.ControlChannel(1) reference = pulse.Schedule() reference += instructions.Delay(10, d0) reference += instructions.Delay(10, m0) reference += instructions.Delay(10, a0) reference += instructions.Delay(10, u0) reference += instructions.Delay(10, u1) self.assertScheduleEqual(schedule, reference) def test_delay_qubits(self): """Test delaying on multiple qubits to make sure we don't insert delays twice.""" with pulse.build(self.backend) as schedule: pulse.delay_qubits(10, 0, 1) d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) m0 = pulse.MeasureChannel(0) m1 = pulse.MeasureChannel(1) a0 = pulse.AcquireChannel(0) a1 = pulse.AcquireChannel(1) u0 = pulse.ControlChannel(0) u1 = pulse.ControlChannel(1) reference = pulse.Schedule() reference += instructions.Delay(10, d0) reference += instructions.Delay(10, d1) reference += instructions.Delay(10, m0) reference += instructions.Delay(10, m1) reference += instructions.Delay(10, a0) reference += instructions.Delay(10, a1) reference += instructions.Delay(10, u0) reference += instructions.Delay(10, u1) self.assertScheduleEqual(schedule, reference) class TestGates(TestBuilder): """Test builder gates.""" def test_cx(self): """Test cx gate.""" with pulse.build(self.backend) as schedule: pulse.cx(0, 1) reference_qc = circuit.QuantumCircuit(2) reference_qc.cx(0, 1) reference = compiler.schedule(reference_qc, self.backend) self.assertScheduleEqual(schedule, reference) def test_u1(self): """Test u1 gate.""" with pulse.build(self.backend) as schedule: with pulse.transpiler_settings(layout_method="trivial"): pulse.u1(np.pi / 2, 0) reference_qc = circuit.QuantumCircuit(1) reference_qc.append(circuit.library.U1Gate(np.pi / 2), [0]) reference = compiler.schedule(reference_qc, self.backend) self.assertScheduleEqual(schedule, reference) def test_u2(self): """Test u2 gate.""" with pulse.build(self.backend) as schedule: pulse.u2(np.pi / 2, 0, 0) reference_qc = circuit.QuantumCircuit(1) reference_qc.append(circuit.library.U2Gate(np.pi / 2, 0), [0]) reference = compiler.schedule(reference_qc, self.backend) self.assertScheduleEqual(schedule, reference) def test_u3(self): """Test u3 gate.""" with pulse.build(self.backend) as schedule: pulse.u3(np.pi / 8, np.pi / 16, np.pi / 4, 0) reference_qc = circuit.QuantumCircuit(1) reference_qc.append(circuit.library.U3Gate(np.pi / 8, np.pi / 16, np.pi / 4), [0]) reference = compiler.schedule(reference_qc, self.backend) self.assertScheduleEqual(schedule, reference) def test_x(self): """Test x gate.""" with pulse.build(self.backend) as schedule: pulse.x(0) reference_qc = circuit.QuantumCircuit(1) reference_qc.x(0) reference_qc = compiler.transpile(reference_qc, self.backend) reference = compiler.schedule(reference_qc, self.backend) self.assertScheduleEqual(schedule, reference) def test_lazy_evaluation_with_transpiler(self): """Test that the two cx gates are optimizied away by the transpiler.""" with pulse.build(self.backend) as schedule: pulse.cx(0, 1) pulse.cx(0, 1) reference_qc = circuit.QuantumCircuit(2) reference = compiler.schedule(reference_qc, self.backend) self.assertScheduleEqual(schedule, reference) def test_measure(self): """Test pulse measurement macro against circuit measurement and ensure agreement.""" with pulse.build(self.backend) as schedule: with pulse.align_sequential(): pulse.x(0) pulse.measure(0) reference_qc = circuit.QuantumCircuit(1, 1) reference_qc.x(0) reference_qc.measure(0, 0) reference_qc = compiler.transpile(reference_qc, self.backend) reference = compiler.schedule(reference_qc, self.backend) self.assertScheduleEqual(schedule, reference) def test_backend_require(self): """Test that a backend is required to use a gate.""" with self.assertRaises(exceptions.BackendNotSet): with pulse.build(): pulse.x(0) class TestBuilderComposition(TestBuilder): """Test more sophisticated composite builder examples.""" def test_complex_build(self): """Test a general program build with nested contexts, circuits and macros.""" d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) d2 = pulse.DriveChannel(2) delay_dur = 30 short_dur = 20 long_dur = 49 with pulse.build(self.backend) as schedule: with pulse.align_sequential(): pulse.delay(delay_dur, d0) pulse.u2(0, pi / 2, 1) with pulse.align_right(): pulse.play(library.Constant(short_dur, 0.1), d1) pulse.play(library.Constant(long_dur, 0.1), d2) pulse.u2(0, pi / 2, 1) with pulse.align_left(): pulse.u2(0, pi / 2, 0) pulse.u2(0, pi / 2, 1) pulse.u2(0, pi / 2, 0) pulse.measure(0) # prepare and schedule circuits that will be used. single_u2_qc = circuit.QuantumCircuit(2) single_u2_qc.append(circuit.library.U2Gate(0, pi / 2), [1]) single_u2_qc = compiler.transpile(single_u2_qc, self.backend) single_u2_sched = compiler.schedule(single_u2_qc, self.backend) # sequential context sequential_reference = pulse.Schedule() sequential_reference += instructions.Delay(delay_dur, d0) sequential_reference.insert(delay_dur, single_u2_sched, inplace=True) # align right align_right_reference = pulse.Schedule() align_right_reference += pulse.Play(library.Constant(long_dur, 0.1), d2) align_right_reference.insert( long_dur - single_u2_sched.duration, single_u2_sched, inplace=True ) align_right_reference.insert( long_dur - single_u2_sched.duration - short_dur, pulse.Play(library.Constant(short_dur, 0.1), d1), inplace=True, ) # align left triple_u2_qc = circuit.QuantumCircuit(2) triple_u2_qc.append(circuit.library.U2Gate(0, pi / 2), [0]) triple_u2_qc.append(circuit.library.U2Gate(0, pi / 2), [1]) triple_u2_qc.append(circuit.library.U2Gate(0, pi / 2), [0]) triple_u2_qc = compiler.transpile(triple_u2_qc, self.backend) align_left_reference = compiler.schedule(triple_u2_qc, self.backend, method="alap") # measurement measure_reference = macros.measure( qubits=[0], inst_map=self.inst_map, meas_map=self.configuration.meas_map ) reference = pulse.Schedule() reference += sequential_reference # Insert so that the long pulse on d2 occurs as early as possible # without an overval on d1. insert_time = reference.ch_stop_time(d1) - align_right_reference.ch_start_time(d1) reference.insert(insert_time, align_right_reference, inplace=True) reference.insert(reference.ch_stop_time(d0, d1), align_left_reference, inplace=True) reference += measure_reference self.assertScheduleEqual(schedule, reference) class TestSubroutineCall(TestBuilder): """Test for calling subroutine.""" def test_call(self): """Test calling schedule instruction.""" d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) reference = pulse.Schedule() reference = reference.insert(10, instructions.Delay(10, d0)) reference += instructions.Delay(20, d1) ref_sched = pulse.Schedule() with self.assertWarns(DeprecationWarning): ref_sched += pulse.instructions.Call(reference) with pulse.build() as schedule: with pulse.align_right(): builder.call(reference) self.assertScheduleEqual(schedule, ref_sched) with pulse.build() as schedule: with pulse.align_right(): pulse.call(reference) self.assertScheduleEqual(schedule, ref_sched) def test_call_circuit(self): """Test calling circuit instruction.""" inst_map = self.inst_map reference = inst_map.get("u1", (0,), 0.0) ref_sched = pulse.Schedule() with self.assertWarns(DeprecationWarning): ref_sched += pulse.instructions.Call(reference) u1_qc = circuit.QuantumCircuit(2) u1_qc.append(circuit.library.U1Gate(0.0), [0]) transpiler_settings = {"optimization_level": 0} with pulse.build(self.backend, default_transpiler_settings=transpiler_settings) as schedule: with pulse.align_right(): builder.call(u1_qc) self.assertScheduleEqual(schedule, ref_sched) def test_call_circuit_with_cregs(self): """Test calling of circuit wiht classical registers.""" qc = circuit.QuantumCircuit(2, 2) qc.h(0) qc.cx(0, 1) qc.measure([0, 1], [0, 1]) with pulse.build(self.backend) as schedule: pulse.call(qc) reference_qc = compiler.transpile(qc, self.backend) reference = compiler.schedule(reference_qc, self.backend) ref_sched = pulse.Schedule() with self.assertWarns(DeprecationWarning): ref_sched += pulse.instructions.Call(reference) self.assertScheduleEqual(schedule, ref_sched) def test_call_gate_and_circuit(self): """Test calling circuit with gates.""" h_control = circuit.QuantumCircuit(2) h_control.h(0) with pulse.build(self.backend) as schedule: with pulse.align_sequential(): # this is circuit, a subroutine stored as Call instruction pulse.call(h_control) # this is instruction, not subroutine pulse.cx(0, 1) # this is macro, not subroutine pulse.measure([0, 1]) # subroutine h_reference = compiler.schedule(compiler.transpile(h_control, self.backend), self.backend) # gate cx_circ = circuit.QuantumCircuit(2) cx_circ.cx(0, 1) cx_reference = compiler.schedule(compiler.transpile(cx_circ, self.backend), self.backend) # measurement measure_reference = macros.measure( qubits=[0, 1], inst_map=self.inst_map, meas_map=self.configuration.meas_map ) reference = pulse.Schedule() with self.assertWarns(DeprecationWarning): reference += pulse.instructions.Call(h_reference) reference += cx_reference reference += measure_reference << reference.duration self.assertScheduleEqual(schedule, reference) def test_subroutine_not_transpiled(self): """Test called circuit is frozen as a subroutine.""" subprogram = circuit.QuantumCircuit(1) subprogram.x(0) transpiler_settings = {"optimization_level": 2} with pulse.build(self.backend, default_transpiler_settings=transpiler_settings) as schedule: pulse.call(subprogram) pulse.call(subprogram) self.assertNotEqual(len(target_qobj_transform(schedule).instructions), 0) def test_subroutine_not_transformed(self): """Test called schedule is not transformed.""" d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) subprogram = pulse.Schedule() subprogram.insert(0, pulse.Delay(30, d0), inplace=True) subprogram.insert(10, pulse.Delay(10, d1), inplace=True) with pulse.build() as target: with pulse.align_right(): pulse.delay(10, d1) pulse.call(subprogram) reference = pulse.Schedule() reference.insert(0, pulse.Delay(10, d1), inplace=True) reference.insert(10, pulse.Delay(30, d0), inplace=True) reference.insert(20, pulse.Delay(10, d1), inplace=True) self.assertScheduleEqual(target, reference) def test_deepcopying_subroutine(self): """Test if deepcopying the schedule can copy inline subroutine.""" from copy import deepcopy with pulse.build() as subroutine: pulse.delay(10, pulse.DriveChannel(0)) with pulse.build() as main_prog: pulse.call(subroutine) copied_prog = deepcopy(main_prog) main_call = main_prog.instructions[0] copy_call = copied_prog.instructions[0] self.assertNotEqual(id(main_call), id(copy_call)) def test_call_with_parameters(self): """Test call subroutine with parameters.""" amp = circuit.Parameter("amp") with pulse.build() as subroutine: pulse.play(pulse.Gaussian(160, amp, 40), pulse.DriveChannel(0)) with pulse.build() as main_prog: pulse.call(subroutine, amp=0.1) pulse.call(subroutine, amp=0.3) self.assertEqual(main_prog.is_parameterized(), False) assigned_sched = target_qobj_transform(main_prog) play_0 = assigned_sched.instructions[0][1] play_1 = assigned_sched.instructions[1][1] self.assertEqual(play_0.pulse.amp, 0.1) self.assertEqual(play_1.pulse.amp, 0.3) def test_call_partly_with_parameters(self): """Test multiple calls partly with parameters then assign.""" amp = circuit.Parameter("amp") with pulse.build() as subroutine: pulse.play(pulse.Gaussian(160, amp, 40), pulse.DriveChannel(0)) with pulse.build() as main_prog: pulse.call(subroutine, amp=0.1) pulse.call(subroutine) self.assertEqual(main_prog.is_parameterized(), True) main_prog.assign_parameters({amp: 0.5}) self.assertEqual(main_prog.is_parameterized(), False) assigned_sched = target_qobj_transform(main_prog) play_0 = assigned_sched.instructions[0][1] play_1 = assigned_sched.instructions[1][1] self.assertEqual(play_0.pulse.amp, 0.1) self.assertEqual(play_1.pulse.amp, 0.5) def test_call_with_not_existing_parameter(self): """Test call subroutine with parameter not defined.""" amp = circuit.Parameter("amp1") with pulse.build() as subroutine: pulse.play(pulse.Gaussian(160, amp, 40), pulse.DriveChannel(0)) with self.assertRaises(exceptions.PulseError): with pulse.build(): pulse.call(subroutine, amp=0.1) def test_call_with_common_parameter(self): """Test call subroutine with parameter that is defined multiple times.""" amp = circuit.Parameter("amp") with pulse.build() as subroutine: pulse.play(pulse.Gaussian(160, amp, 40), pulse.DriveChannel(0)) pulse.play(pulse.Gaussian(320, amp, 80), pulse.DriveChannel(0)) with pulse.build() as main_prog: pulse.call(subroutine, amp=0.1) assigned_sched = target_qobj_transform(main_prog) play_0 = assigned_sched.instructions[0][1] play_1 = assigned_sched.instructions[1][1] self.assertEqual(play_0.pulse.amp, 0.1) self.assertEqual(play_1.pulse.amp, 0.1) def test_call_with_parameter_name_collision(self): """Test call subroutine with duplicated parameter names.""" amp1 = circuit.Parameter("amp") amp2 = circuit.Parameter("amp") sigma = circuit.Parameter("sigma") with pulse.build() as subroutine: pulse.play(pulse.Gaussian(160, amp1, sigma), pulse.DriveChannel(0)) pulse.play(pulse.Gaussian(160, amp2, sigma), pulse.DriveChannel(0)) with pulse.build() as main_prog: pulse.call(subroutine, value_dict={amp1: 0.1, amp2: 0.2}, sigma=40) assigned_sched = target_qobj_transform(main_prog) play_0 = assigned_sched.instructions[0][1] play_1 = assigned_sched.instructions[1][1] self.assertEqual(play_0.pulse.amp, 0.1) self.assertEqual(play_0.pulse.sigma, 40) self.assertEqual(play_1.pulse.amp, 0.2) self.assertEqual(play_1.pulse.sigma, 40) def test_call_subroutine_with_parametrized_duration(self): """Test call subroutine containing a parametrized duration.""" dur = circuit.Parameter("dur") with pulse.build() as subroutine: pulse.play(pulse.Constant(dur, 0.1), pulse.DriveChannel(0)) pulse.play(pulse.Constant(dur, 0.2), pulse.DriveChannel(0)) with pulse.build() as main: pulse.call(subroutine) self.assertEqual(len(main.blocks), 1)
https://github.com/swe-train/qiskit__qiskit
swe-train
# 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. """Test pulse builder with backendV2 context utilities.""" import numpy as np from qiskit import circuit, pulse from qiskit.pulse import builder, macros from qiskit.pulse.instructions import directives from qiskit.pulse.transforms import target_qobj_transform from qiskit.providers.fake_provider import FakeMumbaiV2 from qiskit.pulse import instructions from qiskit.test import QiskitTestCase class TestBuilderV2(QiskitTestCase): """Test the pulse builder context with backendV2.""" def setUp(self): super().setUp() self.backend = FakeMumbaiV2() def assertScheduleEqual(self, program, target): """Assert an error when two pulse programs are not equal. .. note:: Two programs are converted into standard execution format then compared. """ self.assertEqual(target_qobj_transform(program), target_qobj_transform(target)) class TestContextsV2(TestBuilderV2): """Test builder contexts.""" def test_transpiler_settings(self): """Test the transpiler settings context. Tests that two cx gates are optimized away with higher optimization level. """ twice_cx_qc = circuit.QuantumCircuit(2) twice_cx_qc.cx(0, 1) twice_cx_qc.cx(0, 1) with pulse.build(self.backend) as schedule: with pulse.transpiler_settings(optimization_level=0): builder.call(twice_cx_qc) self.assertNotEqual(len(schedule.instructions), 0) with pulse.build(self.backend) as schedule: with pulse.transpiler_settings(optimization_level=3): builder.call(twice_cx_qc) self.assertEqual(len(schedule.instructions), 0) def test_scheduler_settings(self): """Test the circuit scheduler settings context.""" inst_map = pulse.InstructionScheduleMap() d0 = pulse.DriveChannel(0) test_x_sched = pulse.Schedule() test_x_sched += instructions.Delay(10, d0) inst_map.add("x", (0,), test_x_sched) ref_sched = pulse.Schedule() ref_sched += pulse.instructions.Call(test_x_sched) x_qc = circuit.QuantumCircuit(2) x_qc.x(0) with pulse.build(backend=self.backend) as schedule: with pulse.transpiler_settings(basis_gates=["x"]): with pulse.circuit_scheduler_settings(inst_map=inst_map): builder.call(x_qc) self.assertScheduleEqual(schedule, ref_sched) def test_phase_compensated_frequency_offset(self): """Test that the phase offset context properly compensates for phase accumulation with backendV2.""" d0 = pulse.DriveChannel(0) with pulse.build(self.backend) as schedule: with pulse.frequency_offset(1e9, d0, compensate_phase=True): pulse.delay(10, d0) reference = pulse.Schedule() reference += instructions.ShiftFrequency(1e9, d0) reference += instructions.Delay(10, d0) reference += instructions.ShiftPhase( -2 * np.pi * ((1e9 * 10 * self.backend.target.dt) % 1), d0 ) reference += instructions.ShiftFrequency(-1e9, d0) self.assertScheduleEqual(schedule, reference) class TestChannelsV2(TestBuilderV2): """Test builder channels.""" def test_drive_channel(self): """Text context builder drive channel.""" with pulse.build(self.backend): self.assertEqual(pulse.drive_channel(0), pulse.DriveChannel(0)) def test_measure_channel(self): """Text context builder measure channel.""" with pulse.build(self.backend): self.assertEqual(pulse.measure_channel(0), pulse.MeasureChannel(0)) def test_acquire_channel(self): """Text context builder acquire channel.""" with pulse.build(self.backend): self.assertEqual(pulse.acquire_channel(0), pulse.AcquireChannel(0)) def test_control_channel(self): """Text context builder control channel.""" with pulse.build(self.backend): self.assertEqual(pulse.control_channels(0, 1)[0], pulse.ControlChannel(0)) class TestDirectivesV2(TestBuilderV2): """Test builder directives.""" def test_barrier_on_qubits(self): """Test barrier directive on qubits with backendV2. A part of qubits map of Mumbai 0 -- 1 -- 4 -- | | 2 """ with pulse.build(self.backend) as schedule: pulse.barrier(0, 1) reference = pulse.ScheduleBlock() reference += directives.RelativeBarrier( pulse.DriveChannel(0), pulse.DriveChannel(1), pulse.MeasureChannel(0), pulse.MeasureChannel(1), pulse.ControlChannel(0), pulse.ControlChannel(1), pulse.ControlChannel(2), pulse.ControlChannel(3), pulse.ControlChannel(4), pulse.ControlChannel(8), pulse.AcquireChannel(0), pulse.AcquireChannel(1), ) self.assertEqual(schedule, reference) class TestUtilitiesV2(TestBuilderV2): """Test builder utilities.""" def test_active_backend(self): """Test getting active builder backend.""" with pulse.build(self.backend): self.assertEqual(pulse.active_backend(), self.backend) def test_qubit_channels(self): """Test getting the qubit channels of the active builder's backend.""" with pulse.build(self.backend): qubit_channels = pulse.qubit_channels(0) self.assertEqual( qubit_channels, { pulse.DriveChannel(0), pulse.MeasureChannel(0), pulse.AcquireChannel(0), pulse.ControlChannel(0), pulse.ControlChannel(1), }, ) def test_active_transpiler_settings(self): """Test setting settings of active builder's transpiler.""" with pulse.build(self.backend): self.assertFalse(pulse.active_transpiler_settings()) with pulse.transpiler_settings(test_setting=1): self.assertEqual(pulse.active_transpiler_settings()["test_setting"], 1) def test_active_circuit_scheduler_settings(self): """Test setting settings of active builder's circuit scheduler.""" with pulse.build(self.backend): self.assertFalse(pulse.active_circuit_scheduler_settings()) with pulse.circuit_scheduler_settings(test_setting=1): self.assertEqual(pulse.active_circuit_scheduler_settings()["test_setting"], 1) def test_num_qubits(self): """Test builder utility to get number of qubits with backendV2.""" with pulse.build(self.backend): self.assertEqual(pulse.num_qubits(), 27) def test_samples_to_seconds(self): """Test samples to time with backendV2""" target = self.backend.target target.dt = 0.1 with pulse.build(self.backend): time = pulse.samples_to_seconds(100) self.assertTrue(isinstance(time, float)) self.assertEqual(pulse.samples_to_seconds(100), 10) def test_samples_to_seconds_array(self): """Test samples to time (array format) with backendV2.""" target = self.backend.target target.dt = 0.1 with pulse.build(self.backend): samples = np.array([100, 200, 300]) times = pulse.samples_to_seconds(samples) self.assertTrue(np.issubdtype(times.dtype, np.floating)) np.testing.assert_allclose(times, np.array([10, 20, 30])) def test_seconds_to_samples(self): """Test time to samples with backendV2""" target = self.backend.target target.dt = 0.1 with pulse.build(self.backend): samples = pulse.seconds_to_samples(10) self.assertTrue(isinstance(samples, int)) self.assertEqual(pulse.seconds_to_samples(10), 100) def test_seconds_to_samples_array(self): """Test time to samples (array format) with backendV2.""" target = self.backend.target target.dt = 0.1 with pulse.build(self.backend): times = np.array([10, 20, 30]) samples = pulse.seconds_to_samples(times) self.assertTrue(np.issubdtype(samples.dtype, np.integer)) np.testing.assert_allclose(pulse.seconds_to_samples(times), np.array([100, 200, 300])) class TestMacrosV2(TestBuilderV2): """Test builder macros with backendV2.""" def test_macro(self): """Test builder macro decorator.""" @pulse.macro def nested(a): pulse.play(pulse.Gaussian(100, a, 20), pulse.drive_channel(0)) return a * 2 @pulse.macro def test(): pulse.play(pulse.Constant(100, 1.0), pulse.drive_channel(0)) output = nested(0.5) return output with pulse.build(self.backend) as schedule: output = test() self.assertEqual(output, 0.5 * 2) reference = pulse.Schedule() reference += pulse.Play(pulse.Constant(100, 1.0), pulse.DriveChannel(0)) reference += pulse.Play(pulse.Gaussian(100, 0.5, 20), pulse.DriveChannel(0)) self.assertScheduleEqual(schedule, reference) def test_measure(self): """Test utility function - measure with backendV2.""" with pulse.build(self.backend) as schedule: reg = pulse.measure(0) self.assertEqual(reg, pulse.MemorySlot(0)) reference = macros.measure(qubits=[0], backend=self.backend, meas_map=self.backend.meas_map) self.assertScheduleEqual(schedule, reference) def test_measure_multi_qubits(self): """Test utility function - measure with multi qubits with backendV2.""" with pulse.build(self.backend) as schedule: regs = pulse.measure([0, 1]) self.assertListEqual(regs, [pulse.MemorySlot(0), pulse.MemorySlot(1)]) reference = macros.measure( qubits=[0, 1], backend=self.backend, meas_map=self.backend.meas_map ) self.assertScheduleEqual(schedule, reference) def test_measure_all(self): """Test utility function - measure with backendV2..""" with pulse.build(self.backend) as schedule: regs = pulse.measure_all() self.assertEqual(regs, [pulse.MemorySlot(i) for i in range(self.backend.num_qubits)]) reference = macros.measure_all(self.backend) self.assertScheduleEqual(schedule, reference) def test_delay_qubit(self): """Test delaying on a qubit macro.""" with pulse.build(self.backend) as schedule: pulse.delay_qubits(10, 0) d0 = pulse.DriveChannel(0) m0 = pulse.MeasureChannel(0) a0 = pulse.AcquireChannel(0) u0 = pulse.ControlChannel(0) u1 = pulse.ControlChannel(1) reference = pulse.Schedule() reference += instructions.Delay(10, d0) reference += instructions.Delay(10, m0) reference += instructions.Delay(10, a0) reference += instructions.Delay(10, u0) reference += instructions.Delay(10, u1) self.assertScheduleEqual(schedule, reference) def test_delay_qubits(self): """Test delaying on multiple qubits with backendV2 to make sure we don't insert delays twice.""" with pulse.build(self.backend) as schedule: pulse.delay_qubits(10, 0, 1) d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) m0 = pulse.MeasureChannel(0) m1 = pulse.MeasureChannel(1) a0 = pulse.AcquireChannel(0) a1 = pulse.AcquireChannel(1) u0 = pulse.ControlChannel(0) u1 = pulse.ControlChannel(1) u2 = pulse.ControlChannel(2) u3 = pulse.ControlChannel(3) u4 = pulse.ControlChannel(4) u8 = pulse.ControlChannel(8) reference = pulse.Schedule() reference += instructions.Delay(10, d0) reference += instructions.Delay(10, d1) reference += instructions.Delay(10, m0) reference += instructions.Delay(10, m1) reference += instructions.Delay(10, a0) reference += instructions.Delay(10, a1) reference += instructions.Delay(10, u0) reference += instructions.Delay(10, u1) reference += instructions.Delay(10, u2) reference += instructions.Delay(10, u3) reference += instructions.Delay(10, u4) reference += instructions.Delay(10, u8) self.assertScheduleEqual(schedule, reference)
https://github.com/swe-train/qiskit__qiskit
swe-train
# 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. """Unit tests for pulse instructions.""" import numpy as np from qiskit import pulse, circuit from qiskit.pulse import channels, configuration, instructions, library, exceptions from qiskit.pulse.transforms import inline_subroutines, target_qobj_transform from qiskit.test import QiskitTestCase class TestAcquire(QiskitTestCase): """Acquisition tests.""" def test_can_construct_valid_acquire_command(self): """Test if valid acquire command can be constructed.""" kernel_opts = {"start_window": 0, "stop_window": 10} kernel = configuration.Kernel(name="boxcar", **kernel_opts) discriminator_opts = { "neighborhoods": [{"qubits": 1, "channels": 1}], "cal": "coloring", "resample": False, } discriminator = configuration.Discriminator( name="linear_discriminator", **discriminator_opts ) acq = instructions.Acquire( 10, channels.AcquireChannel(0), channels.MemorySlot(0), kernel=kernel, discriminator=discriminator, name="acquire", ) self.assertEqual(acq.duration, 10) self.assertEqual(acq.discriminator.name, "linear_discriminator") self.assertEqual(acq.discriminator.params, discriminator_opts) self.assertEqual(acq.kernel.name, "boxcar") self.assertEqual(acq.kernel.params, kernel_opts) self.assertIsInstance(acq.id, int) self.assertEqual(acq.name, "acquire") self.assertEqual( acq.operands, ( 10, channels.AcquireChannel(0), channels.MemorySlot(0), None, kernel, discriminator, ), ) def test_instructions_hash(self): """Test hashing for acquire instruction.""" acq_1 = instructions.Acquire( 10, channels.AcquireChannel(0), channels.MemorySlot(0), name="acquire", ) acq_2 = instructions.Acquire( 10, channels.AcquireChannel(0), channels.MemorySlot(0), name="acquire", ) hash_1 = hash(acq_1) hash_2 = hash(acq_2) self.assertEqual(hash_1, hash_2) class TestDelay(QiskitTestCase): """Delay tests.""" def test_delay(self): """Test delay.""" delay = instructions.Delay(10, channels.DriveChannel(0), name="test_name") self.assertIsInstance(delay.id, int) self.assertEqual(delay.name, "test_name") self.assertEqual(delay.duration, 10) self.assertIsInstance(delay.duration, int) self.assertEqual(delay.operands, (10, channels.DriveChannel(0))) self.assertEqual(delay, instructions.Delay(10, channels.DriveChannel(0))) self.assertNotEqual(delay, instructions.Delay(11, channels.DriveChannel(1))) self.assertEqual(repr(delay), "Delay(10, DriveChannel(0), name='test_name')") # Test numpy int for duration delay = instructions.Delay(np.int32(10), channels.DriveChannel(0), name="test_name2") self.assertEqual(delay.duration, 10) self.assertIsInstance(delay.duration, np.integer) def test_operator_delay(self): """Test Operator(delay).""" from qiskit.circuit import QuantumCircuit from qiskit.quantum_info import Operator circ = QuantumCircuit(1) circ.delay(10) op_delay = Operator(circ) expected = QuantumCircuit(1) expected.i(0) op_identity = Operator(expected) self.assertEqual(op_delay, op_identity) class TestSetFrequency(QiskitTestCase): """Set frequency tests.""" def test_freq(self): """Test set frequency basic functionality.""" set_freq = instructions.SetFrequency(4.5e9, channels.DriveChannel(1), name="test") self.assertIsInstance(set_freq.id, int) self.assertEqual(set_freq.duration, 0) self.assertEqual(set_freq.frequency, 4.5e9) self.assertEqual(set_freq.operands, (4.5e9, channels.DriveChannel(1))) self.assertEqual( set_freq, instructions.SetFrequency(4.5e9, channels.DriveChannel(1), name="test") ) self.assertNotEqual( set_freq, instructions.SetFrequency(4.5e8, channels.DriveChannel(1), name="test") ) self.assertEqual(repr(set_freq), "SetFrequency(4500000000.0, DriveChannel(1), name='test')") def test_freq_non_pulse_channel(self): """Test set frequency constructor with illegal channel""" with self.assertRaises(exceptions.PulseError): instructions.SetFrequency(4.5e9, channels.RegisterSlot(1), name="test") def test_parameter_expression(self): """Test getting all parameters assigned by expression.""" p1 = circuit.Parameter("P1") p2 = circuit.Parameter("P2") expr = p1 + p2 instr = instructions.SetFrequency(expr, channel=channels.DriveChannel(0)) self.assertSetEqual(instr.parameters, {p1, p2}) class TestShiftFrequency(QiskitTestCase): """Shift frequency tests.""" def test_shift_freq(self): """Test shift frequency basic functionality.""" shift_freq = instructions.ShiftFrequency(4.5e9, channels.DriveChannel(1), name="test") self.assertIsInstance(shift_freq.id, int) self.assertEqual(shift_freq.duration, 0) self.assertEqual(shift_freq.frequency, 4.5e9) self.assertEqual(shift_freq.operands, (4.5e9, channels.DriveChannel(1))) self.assertEqual( shift_freq, instructions.ShiftFrequency(4.5e9, channels.DriveChannel(1), name="test") ) self.assertNotEqual( shift_freq, instructions.ShiftFrequency(4.5e8, channels.DriveChannel(1), name="test") ) self.assertEqual( repr(shift_freq), "ShiftFrequency(4500000000.0, DriveChannel(1), name='test')" ) def test_freq_non_pulse_channel(self): """Test shift frequency constructor with illegal channel""" with self.assertRaises(exceptions.PulseError): instructions.ShiftFrequency(4.5e9, channels.RegisterSlot(1), name="test") def test_parameter_expression(self): """Test getting all parameters assigned by expression.""" p1 = circuit.Parameter("P1") p2 = circuit.Parameter("P2") expr = p1 + p2 instr = instructions.ShiftFrequency(expr, channel=channels.DriveChannel(0)) self.assertSetEqual(instr.parameters, {p1, p2}) class TestSetPhase(QiskitTestCase): """Test the instruction construction.""" def test_default(self): """Test basic SetPhase.""" set_phase = instructions.SetPhase(1.57, channels.DriveChannel(0)) self.assertIsInstance(set_phase.id, int) self.assertEqual(set_phase.name, None) self.assertEqual(set_phase.duration, 0) self.assertEqual(set_phase.phase, 1.57) self.assertEqual(set_phase.operands, (1.57, channels.DriveChannel(0))) self.assertEqual( set_phase, instructions.SetPhase(1.57, channels.DriveChannel(0), name="test") ) self.assertNotEqual( set_phase, instructions.SetPhase(1.57j, channels.DriveChannel(0), name="test") ) self.assertEqual(repr(set_phase), "SetPhase(1.57, DriveChannel(0))") def test_set_phase_non_pulse_channel(self): """Test shift phase constructor with illegal channel""" with self.assertRaises(exceptions.PulseError): instructions.SetPhase(1.57, channels.RegisterSlot(1), name="test") def test_parameter_expression(self): """Test getting all parameters assigned by expression.""" p1 = circuit.Parameter("P1") p2 = circuit.Parameter("P2") expr = p1 + p2 instr = instructions.SetPhase(expr, channel=channels.DriveChannel(0)) self.assertSetEqual(instr.parameters, {p1, p2}) class TestShiftPhase(QiskitTestCase): """Test the instruction construction.""" def test_default(self): """Test basic ShiftPhase.""" shift_phase = instructions.ShiftPhase(1.57, channels.DriveChannel(0)) self.assertIsInstance(shift_phase.id, int) self.assertEqual(shift_phase.name, None) self.assertEqual(shift_phase.duration, 0) self.assertEqual(shift_phase.phase, 1.57) self.assertEqual(shift_phase.operands, (1.57, channels.DriveChannel(0))) self.assertEqual( shift_phase, instructions.ShiftPhase(1.57, channels.DriveChannel(0), name="test") ) self.assertNotEqual( shift_phase, instructions.ShiftPhase(1.57j, channels.DriveChannel(0), name="test") ) self.assertEqual(repr(shift_phase), "ShiftPhase(1.57, DriveChannel(0))") def test_shift_phase_non_pulse_channel(self): """Test shift phase constructor with illegal channel""" with self.assertRaises(exceptions.PulseError): instructions.ShiftPhase(1.57, channels.RegisterSlot(1), name="test") def test_parameter_expression(self): """Test getting all parameters assigned by expression.""" p1 = circuit.Parameter("P1") p2 = circuit.Parameter("P2") expr = p1 + p2 instr = instructions.ShiftPhase(expr, channel=channels.DriveChannel(0)) self.assertSetEqual(instr.parameters, {p1, p2}) class TestSnapshot(QiskitTestCase): """Snapshot tests.""" def test_default(self): """Test default snapshot.""" snapshot = instructions.Snapshot(label="test_name", snapshot_type="state") self.assertIsInstance(snapshot.id, int) self.assertEqual(snapshot.name, "test_name") self.assertEqual(snapshot.type, "state") self.assertEqual(snapshot.duration, 0) self.assertNotEqual(snapshot, instructions.Delay(10, channels.DriveChannel(0))) self.assertEqual(repr(snapshot), "Snapshot(test_name, state, name='test_name')") class TestPlay(QiskitTestCase): """Play tests.""" def setUp(self): """Setup play tests.""" super().setUp() self.duration = 4 self.pulse_op = library.Waveform([1.0] * self.duration, name="test") def test_play(self): """Test basic play instruction.""" play = instructions.Play(self.pulse_op, channels.DriveChannel(1)) self.assertIsInstance(play.id, int) self.assertEqual(play.name, self.pulse_op.name) self.assertEqual(play.duration, self.duration) self.assertEqual( repr(play), "Play(Waveform(array([1.+0.j, 1.+0.j, 1.+0.j, 1.+0.j]), name='test')," " DriveChannel(1), name='test')", ) def test_play_non_pulse_ch_raises(self): """Test that play instruction on non-pulse channel raises a pulse error.""" with self.assertRaises(exceptions.PulseError): instructions.Play(self.pulse_op, channels.AcquireChannel(0)) class TestDirectives(QiskitTestCase): """Test pulse directives.""" def test_relative_barrier(self): """Test the relative barrier directive.""" a0 = channels.AcquireChannel(0) d0 = channels.DriveChannel(0) m0 = channels.MeasureChannel(0) u0 = channels.ControlChannel(0) mem0 = channels.MemorySlot(0) reg0 = channels.RegisterSlot(0) chans = (a0, d0, m0, u0, mem0, reg0) name = "barrier" barrier = instructions.RelativeBarrier(*chans, name=name) self.assertEqual(barrier.name, name) self.assertEqual(barrier.duration, 0) self.assertEqual(barrier.channels, chans) self.assertEqual(barrier.operands, chans) class TestCall(QiskitTestCase): """Test call instruction.""" def setUp(self): super().setUp() with pulse.build() as _subroutine: pulse.delay(10, pulse.DriveChannel(0)) self.subroutine = _subroutine self.param1 = circuit.Parameter("amp1") self.param2 = circuit.Parameter("amp2") with pulse.build() as _function: pulse.play(pulse.Gaussian(160, self.param1, 40), pulse.DriveChannel(0)) pulse.play(pulse.Gaussian(160, self.param2, 40), pulse.DriveChannel(0)) pulse.play(pulse.Gaussian(160, self.param1, 40), pulse.DriveChannel(0)) self.function = _function def test_call(self): """Test basic call instruction.""" with self.assertWarns(DeprecationWarning): call = instructions.Call(subroutine=self.subroutine) self.assertEqual(call.duration, 10) self.assertEqual(call.subroutine, self.subroutine) def test_parameterized_call(self): """Test call instruction with parameterized subroutine.""" with self.assertWarns(DeprecationWarning): call = instructions.Call(subroutine=self.function) self.assertTrue(call.is_parameterized()) self.assertEqual(len(call.parameters), 2) def test_assign_parameters_to_call(self): """Test create schedule by calling subroutine and assign parameters to it.""" init_dict = {self.param1: 0.1, self.param2: 0.5} with pulse.build() as test_sched: pulse.call(self.function) test_sched = test_sched.assign_parameters(value_dict=init_dict) test_sched = inline_subroutines(test_sched) with pulse.build() as ref_sched: pulse.play(pulse.Gaussian(160, 0.1, 40), pulse.DriveChannel(0)) pulse.play(pulse.Gaussian(160, 0.5, 40), pulse.DriveChannel(0)) pulse.play(pulse.Gaussian(160, 0.1, 40), pulse.DriveChannel(0)) self.assertEqual(target_qobj_transform(test_sched), target_qobj_transform(ref_sched)) def test_call_initialize_with_parameter(self): """Test call instruction with parameterized subroutine with initial dict.""" init_dict = {self.param1: 0.1, self.param2: 0.5} with self.assertWarns(DeprecationWarning): call = instructions.Call(subroutine=self.function, value_dict=init_dict) with pulse.build() as ref_sched: pulse.play(pulse.Gaussian(160, 0.1, 40), pulse.DriveChannel(0)) pulse.play(pulse.Gaussian(160, 0.5, 40), pulse.DriveChannel(0)) pulse.play(pulse.Gaussian(160, 0.1, 40), pulse.DriveChannel(0)) self.assertEqual( target_qobj_transform(call.assigned_subroutine()), target_qobj_transform(ref_sched) ) def test_call_subroutine_with_different_parameters(self): """Test call subroutines with different parameters in the same schedule.""" init_dict1 = {self.param1: 0.1, self.param2: 0.5} init_dict2 = {self.param1: 0.3, self.param2: 0.7} with pulse.build() as test_sched: pulse.call(self.function, value_dict=init_dict1) pulse.call(self.function, value_dict=init_dict2) with pulse.build() as ref_sched: pulse.play(pulse.Gaussian(160, 0.1, 40), pulse.DriveChannel(0)) pulse.play(pulse.Gaussian(160, 0.5, 40), pulse.DriveChannel(0)) pulse.play(pulse.Gaussian(160, 0.1, 40), pulse.DriveChannel(0)) pulse.play(pulse.Gaussian(160, 0.3, 40), pulse.DriveChannel(0)) pulse.play(pulse.Gaussian(160, 0.7, 40), pulse.DriveChannel(0)) pulse.play(pulse.Gaussian(160, 0.3, 40), pulse.DriveChannel(0)) self.assertEqual(target_qobj_transform(test_sched), target_qobj_transform(ref_sched))
https://github.com/swe-train/qiskit__qiskit
swe-train
# 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 """Test cases for parameter manager.""" from copy import deepcopy import numpy as np from qiskit import pulse from qiskit.circuit import Parameter from qiskit.pulse.exceptions import PulseError, UnassignedDurationError from qiskit.pulse.parameter_manager import ParameterGetter, ParameterSetter from qiskit.pulse.transforms import AlignEquispaced, AlignLeft, inline_subroutines from qiskit.test import QiskitTestCase class ParameterTestBase(QiskitTestCase): """A base class for parameter manager unittest, providing test schedule.""" def setUp(self): """Just some useful, reusable Parameters, constants, schedules.""" super().setUp() self.amp1_1 = Parameter("amp1_1") self.amp1_2 = Parameter("amp1_2") self.amp2 = Parameter("amp2") self.amp3 = Parameter("amp3") self.dur1 = Parameter("dur1") self.dur2 = Parameter("dur2") self.dur3 = Parameter("dur3") self.parametric_waveform1 = pulse.Gaussian( duration=self.dur1, amp=self.amp1_1 + self.amp1_2, sigma=self.dur1 / 4 ) self.parametric_waveform2 = pulse.Gaussian( duration=self.dur2, amp=self.amp2, sigma=self.dur2 / 5 ) self.parametric_waveform3 = pulse.Gaussian( duration=self.dur3, amp=self.amp3, sigma=self.dur3 / 6 ) self.ch1 = Parameter("ch1") self.ch2 = Parameter("ch2") self.ch3 = Parameter("ch3") self.d1 = pulse.DriveChannel(self.ch1) self.d2 = pulse.DriveChannel(self.ch2) self.d3 = pulse.DriveChannel(self.ch3) self.phi1 = Parameter("phi1") self.phi2 = Parameter("phi2") self.phi3 = Parameter("phi3") self.meas_dur = Parameter("meas_dur") self.mem1 = Parameter("s1") self.reg1 = Parameter("m1") self.context_dur = Parameter("context_dur") # schedule under test subroutine = pulse.ScheduleBlock(alignment_context=AlignLeft()) subroutine += pulse.ShiftPhase(self.phi1, self.d1) subroutine += pulse.Play(self.parametric_waveform1, self.d1) sched = pulse.Schedule() sched += pulse.ShiftPhase(self.phi3, self.d3) long_schedule = pulse.ScheduleBlock( alignment_context=AlignEquispaced(self.context_dur), name="long_schedule" ) long_schedule += subroutine long_schedule += pulse.ShiftPhase(self.phi2, self.d2) long_schedule += pulse.Play(self.parametric_waveform2, self.d2) with self.assertWarns(DeprecationWarning): long_schedule += pulse.Call(sched) long_schedule += pulse.Play(self.parametric_waveform3, self.d3) long_schedule += pulse.Acquire( self.meas_dur, pulse.AcquireChannel(self.ch1), mem_slot=pulse.MemorySlot(self.mem1), reg_slot=pulse.RegisterSlot(self.reg1), ) self.test_sched = long_schedule class TestParameterGetter(ParameterTestBase): """Test getting parameters.""" def test_get_parameter_from_channel(self): """Test get parameters from channel.""" test_obj = pulse.DriveChannel(self.ch1 + self.ch2) visitor = ParameterGetter() visitor.visit(test_obj) ref_params = {self.ch1, self.ch2} self.assertSetEqual(visitor.parameters, ref_params) def test_get_parameter_from_pulse(self): """Test get parameters from pulse instruction.""" test_obj = self.parametric_waveform1 visitor = ParameterGetter() visitor.visit(test_obj) ref_params = {self.amp1_1, self.amp1_2, self.dur1} self.assertSetEqual(visitor.parameters, ref_params) def test_get_parameter_from_acquire(self): """Test get parameters from acquire instruction.""" test_obj = pulse.Acquire(16000, pulse.AcquireChannel(self.ch1), pulse.MemorySlot(self.ch1)) visitor = ParameterGetter() visitor.visit(test_obj) ref_params = {self.ch1} self.assertSetEqual(visitor.parameters, ref_params) def test_get_parameter_from_inst(self): """Test get parameters from instruction.""" test_obj = pulse.ShiftPhase(self.phi1 + self.phi2, pulse.DriveChannel(0)) visitor = ParameterGetter() visitor.visit(test_obj) ref_params = {self.phi1, self.phi2} self.assertSetEqual(visitor.parameters, ref_params) def test_get_parameter_from_call(self): """Test get parameters from instruction.""" sched = pulse.Schedule() sched += pulse.ShiftPhase(self.phi1, self.d1) with self.assertWarns(DeprecationWarning): test_obj = pulse.Call(subroutine=sched) visitor = ParameterGetter() visitor.visit(test_obj) ref_params = {self.phi1, self.ch1} self.assertSetEqual(visitor.parameters, ref_params) def test_with_function(self): """Test ParameterExpressions formed trivially in a function.""" def get_shift(variable): return variable - 1 test_obj = pulse.ShiftPhase(get_shift(self.phi1), self.d1) visitor = ParameterGetter() visitor.visit(test_obj) ref_params = {self.phi1, self.ch1} self.assertSetEqual(visitor.parameters, ref_params) def test_get_parameter_from_alignment_context(self): """Test get parameters from alignment context.""" test_obj = AlignEquispaced(duration=self.context_dur + self.dur1) visitor = ParameterGetter() visitor.visit(test_obj) ref_params = {self.context_dur, self.dur1} self.assertSetEqual(visitor.parameters, ref_params) def test_get_parameter_from_complex_schedule(self): """Test get parameters from complicated schedule.""" test_block = deepcopy(self.test_sched) visitor = ParameterGetter() visitor.visit(test_block) self.assertEqual(len(visitor.parameters), 17) class TestParameterSetter(ParameterTestBase): """Test setting parameters.""" def test_set_parameter_to_channel(self): """Test set parameters from channel.""" test_obj = pulse.DriveChannel(self.ch1 + self.ch2) value_dict = {self.ch1: 1, self.ch2: 2} visitor = ParameterSetter(param_map=value_dict) assigned = visitor.visit(test_obj) ref_obj = pulse.DriveChannel(3) self.assertEqual(assigned, ref_obj) def test_set_parameter_to_pulse(self): """Test set parameters from pulse instruction.""" test_obj = self.parametric_waveform1 value_dict = {self.amp1_1: 0.1, self.amp1_2: 0.2, self.dur1: 160} visitor = ParameterSetter(param_map=value_dict) assigned = visitor.visit(test_obj) ref_obj = pulse.Gaussian(duration=160, amp=0.3, sigma=40) self.assertEqual(assigned, ref_obj) def test_set_parameter_to_acquire(self): """Test set parameters to acquire instruction.""" test_obj = pulse.Acquire(16000, pulse.AcquireChannel(self.ch1), pulse.MemorySlot(self.ch1)) value_dict = {self.ch1: 2} visitor = ParameterSetter(param_map=value_dict) assigned = visitor.visit(test_obj) ref_obj = pulse.Acquire(16000, pulse.AcquireChannel(2), pulse.MemorySlot(2)) self.assertEqual(assigned, ref_obj) def test_set_parameter_to_inst(self): """Test get parameters from instruction.""" test_obj = pulse.ShiftPhase(self.phi1 + self.phi2, pulse.DriveChannel(0)) value_dict = {self.phi1: 0.123, self.phi2: 0.456} visitor = ParameterSetter(param_map=value_dict) assigned = visitor.visit(test_obj) ref_obj = pulse.ShiftPhase(0.579, pulse.DriveChannel(0)) self.assertEqual(assigned, ref_obj) def test_set_parameter_to_call(self): """Test get parameters from instruction.""" sched = pulse.Schedule() sched += pulse.ShiftPhase(self.phi1, self.d1) with self.assertWarns(DeprecationWarning): test_obj = pulse.Call(subroutine=sched) value_dict = {self.phi1: 1.57, self.ch1: 2} visitor = ParameterSetter(param_map=value_dict) assigned = visitor.visit(test_obj) ref_sched = pulse.Schedule() ref_sched += pulse.ShiftPhase(1.57, pulse.DriveChannel(2)) with self.assertWarns(DeprecationWarning): ref_obj = pulse.Call(subroutine=ref_sched) self.assertEqual(assigned, ref_obj) def test_with_function(self): """Test ParameterExpressions formed trivially in a function.""" def get_shift(variable): return variable - 1 test_obj = pulse.ShiftPhase(get_shift(self.phi1), self.d1) value_dict = {self.phi1: 2.0, self.ch1: 2} visitor = ParameterSetter(param_map=value_dict) assigned = visitor.visit(test_obj) ref_obj = pulse.ShiftPhase(1.0, pulse.DriveChannel(2)) self.assertEqual(assigned, ref_obj) def test_set_parameter_to_alignment_context(self): """Test get parameters from alignment context.""" test_obj = AlignEquispaced(duration=self.context_dur + self.dur1) value_dict = {self.context_dur: 1000, self.dur1: 100} visitor = ParameterSetter(param_map=value_dict) assigned = visitor.visit(test_obj) ref_obj = AlignEquispaced(duration=1100) self.assertEqual(assigned, ref_obj) def test_nested_assignment_partial_bind(self): """Test nested schedule with call instruction. Inline the schedule and partially bind parameters.""" context = AlignEquispaced(duration=self.context_dur) subroutine = pulse.ScheduleBlock(alignment_context=context) subroutine += pulse.Play(self.parametric_waveform1, self.d1) nested_block = pulse.ScheduleBlock() with self.assertWarns(DeprecationWarning): nested_block += pulse.Call(subroutine=subroutine) test_obj = pulse.ScheduleBlock() test_obj += nested_block test_obj = inline_subroutines(test_obj) value_dict = {self.context_dur: 1000, self.dur1: 200, self.ch1: 1} visitor = ParameterSetter(param_map=value_dict) assigned = visitor.visit(test_obj) ref_context = AlignEquispaced(duration=1000) ref_subroutine = pulse.ScheduleBlock(alignment_context=ref_context) ref_subroutine += pulse.Play( pulse.Gaussian(200, self.amp1_1 + self.amp1_2, 50), pulse.DriveChannel(1) ) ref_nested_block = pulse.ScheduleBlock() ref_nested_block += ref_subroutine ref_obj = pulse.ScheduleBlock() ref_obj += ref_nested_block self.assertEqual(assigned, ref_obj) def test_complex_valued_parameter(self): """Test complex valued parameter can be casted to a complex value, but raises PendingDeprecationWarning..""" amp = Parameter("amp") test_obj = pulse.Constant(duration=160, amp=1j * amp) value_dict = {amp: 0.1} visitor = ParameterSetter(param_map=value_dict) with self.assertWarns(PendingDeprecationWarning): assigned = visitor.visit(test_obj) with self.assertWarns(DeprecationWarning): ref_obj = pulse.Constant(duration=160, amp=1j * 0.1) self.assertEqual(assigned, ref_obj) def test_complex_value_to_parameter(self): """Test complex value can be assigned to parameter object, but raises PendingDeprecationWarning.""" amp = Parameter("amp") test_obj = pulse.Constant(duration=160, amp=amp) value_dict = {amp: 0.1j} visitor = ParameterSetter(param_map=value_dict) with self.assertWarns(PendingDeprecationWarning): assigned = visitor.visit(test_obj) with self.assertWarns(DeprecationWarning): ref_obj = pulse.Constant(duration=160, amp=1j * 0.1) self.assertEqual(assigned, ref_obj) def test_complex_parameter_expression(self): """Test assignment of complex-valued parameter expression to parameter, but raises PendingDeprecationWarning.""" amp = Parameter("amp") mag = Parameter("A") phi = Parameter("phi") test_obj = pulse.Constant(duration=160, amp=amp) test_obj_copy = deepcopy(test_obj) # generate parameter expression value_dict = {amp: mag * np.exp(1j * phi)} visitor = ParameterSetter(param_map=value_dict) assigned = visitor.visit(test_obj) # generate complex value value_dict = {mag: 0.1, phi: 0.5} visitor = ParameterSetter(param_map=value_dict) with self.assertWarns(PendingDeprecationWarning): assigned = visitor.visit(assigned) # evaluated parameter expression: 0.0877582561890373 + 0.0479425538604203*I value_dict = {amp: 0.1 * np.exp(0.5j)} visitor = ParameterSetter(param_map=value_dict) with self.assertWarns(PendingDeprecationWarning): ref_obj = visitor.visit(test_obj_copy) self.assertEqual(assigned, ref_obj) def test_invalid_pulse_amplitude(self): """Test that invalid parameters are still checked upon assignment.""" amp = Parameter("amp") test_sched = pulse.ScheduleBlock() test_sched.append( pulse.Play( pulse.Constant(160, amp=2 * amp), pulse.DriveChannel(0), ), inplace=True, ) with self.assertRaises(PulseError): test_sched.assign_parameters({amp: 0.6}, inplace=False) def test_set_parameter_to_complex_schedule(self): """Test get parameters from complicated schedule.""" test_block = deepcopy(self.test_sched) value_dict = { self.amp1_1: 0.1, self.amp1_2: 0.2, self.amp2: 0.3, self.amp3: 0.4, self.dur1: 100, self.dur2: 125, self.dur3: 150, self.ch1: 0, self.ch2: 2, self.ch3: 4, self.phi1: 1.0, self.phi2: 2.0, self.phi3: 3.0, self.meas_dur: 300, self.mem1: 3, self.reg1: 0, self.context_dur: 1000, } visitor = ParameterSetter(param_map=value_dict) assigned = visitor.visit(test_block) # create ref schedule subroutine = pulse.ScheduleBlock(alignment_context=AlignLeft()) subroutine += pulse.ShiftPhase(1.0, pulse.DriveChannel(0)) subroutine += pulse.Play(pulse.Gaussian(100, 0.3, 25), pulse.DriveChannel(0)) sched = pulse.Schedule() sched += pulse.ShiftPhase(3.0, pulse.DriveChannel(4)) ref_obj = pulse.ScheduleBlock(alignment_context=AlignEquispaced(1000), name="long_schedule") ref_obj += subroutine ref_obj += pulse.ShiftPhase(2.0, pulse.DriveChannel(2)) ref_obj += pulse.Play(pulse.Gaussian(125, 0.3, 25), pulse.DriveChannel(2)) with self.assertWarns(DeprecationWarning): ref_obj += pulse.Call(sched) ref_obj += pulse.Play(pulse.Gaussian(150, 0.4, 25), pulse.DriveChannel(4)) ref_obj += pulse.Acquire( 300, pulse.AcquireChannel(0), pulse.MemorySlot(3), pulse.RegisterSlot(0) ) self.assertEqual(assigned, ref_obj) class TestAssignFromProgram(QiskitTestCase): """Test managing parameters from programs. Parameter manager is implicitly called.""" def test_attribute_parameters(self): """Test the ``parameter`` attributes.""" sigma = Parameter("sigma") amp = Parameter("amp") waveform = pulse.library.Gaussian(duration=128, sigma=sigma, amp=amp) block = pulse.ScheduleBlock() block += pulse.Play(waveform, pulse.DriveChannel(10)) ref_set = {amp, sigma} self.assertSetEqual(set(block.parameters), ref_set) def test_parametric_pulses(self): """Test Parametric Pulses with parameters determined by ParameterExpressions in the Play instruction.""" sigma = Parameter("sigma") amp = Parameter("amp") waveform = pulse.library.Gaussian(duration=128, sigma=sigma, amp=amp) block = pulse.ScheduleBlock() block += pulse.Play(waveform, pulse.DriveChannel(10)) block.assign_parameters({amp: 0.2, sigma: 4}, inplace=True) self.assertEqual(block.blocks[0].pulse.amp, 0.2) self.assertEqual(block.blocks[0].pulse.sigma, 4.0) def test_parameters_from_subroutine(self): """Test that get parameter objects from subroutines.""" param1 = Parameter("amp") waveform = pulse.library.Constant(duration=100, amp=param1) program_layer0 = pulse.Schedule() program_layer0 += pulse.Play(waveform, pulse.DriveChannel(0)) # from call instruction program_layer1 = pulse.Schedule() with self.assertWarns(DeprecationWarning): program_layer1 += pulse.instructions.Call(program_layer0) self.assertEqual(program_layer1.get_parameters("amp")[0], param1) # from nested call instruction program_layer2 = pulse.Schedule() with self.assertWarns(DeprecationWarning): program_layer2 += pulse.instructions.Call(program_layer1) self.assertEqual(program_layer2.get_parameters("amp")[0], param1) def test_assign_parameter_to_subroutine(self): """Test that assign parameter objects to subroutines.""" param1 = Parameter("amp") waveform = pulse.library.Constant(duration=100, amp=param1) program_layer0 = pulse.Schedule() program_layer0 += pulse.Play(waveform, pulse.DriveChannel(0)) reference = program_layer0.assign_parameters({param1: 0.1}, inplace=False) # to call instruction program_layer1 = pulse.Schedule() with self.assertWarns(DeprecationWarning): program_layer1 += pulse.instructions.Call(program_layer0) target = program_layer1.assign_parameters({param1: 0.1}, inplace=False) self.assertEqual(inline_subroutines(target), reference) # to nested call instruction program_layer2 = pulse.Schedule() with self.assertWarns(DeprecationWarning): program_layer2 += pulse.instructions.Call(program_layer1) target = program_layer2.assign_parameters({param1: 0.1}, inplace=False) self.assertEqual(inline_subroutines(target), reference) def test_assign_parameter_to_subroutine_parameter(self): """Test that assign parameter objects to parameter of subroutine.""" param1 = Parameter("amp") waveform = pulse.library.Constant(duration=100, amp=param1) param_sub1 = Parameter("p1") param_sub2 = Parameter("p2") subroutine = pulse.Schedule() subroutine += pulse.Play(waveform, pulse.DriveChannel(0)) reference = subroutine.assign_parameters({param1: 0.6}, inplace=False) main_prog = pulse.Schedule() pdict = {param1: param_sub1 + param_sub2} with self.assertWarns(DeprecationWarning): main_prog += pulse.instructions.Call(subroutine, value_dict=pdict) # parameter is overwritten by parameters self.assertEqual(len(main_prog.parameters), 2) target = main_prog.assign_parameters({param_sub1: 0.1, param_sub2: 0.5}, inplace=False) result = inline_subroutines(target) self.assertEqual(result, reference) class TestScheduleTimeslots(QiskitTestCase): """Test for edge cases of timing overlap on parametrized channels. Note that this test is dedicated to `Schedule` since `ScheduleBlock` implicitly assigns instruction time t0 that doesn't overlap with existing instructions. """ def test_overlapping_pulses(self): """Test that an error is still raised when overlapping instructions are assigned.""" param_idx = Parameter("q") schedule = pulse.Schedule() schedule |= pulse.Play(pulse.Waveform([1, 1, 1, 1]), pulse.DriveChannel(param_idx)) with self.assertRaises(PulseError): schedule |= pulse.Play( pulse.Waveform([0.5, 0.5, 0.5, 0.5]), pulse.DriveChannel(param_idx) ) def test_overlapping_on_assignment(self): """Test that assignment will catch against existing instructions.""" param_idx = Parameter("q") schedule = pulse.Schedule() schedule |= pulse.Play(pulse.Waveform([1, 1, 1, 1]), pulse.DriveChannel(1)) schedule |= pulse.Play(pulse.Waveform([1, 1, 1, 1]), pulse.DriveChannel(param_idx)) with self.assertRaises(PulseError): schedule.assign_parameters({param_idx: 1}) def test_overlapping_on_expression_assigment_to_zero(self): """Test constant*zero expression conflict.""" param_idx = Parameter("q") schedule = pulse.Schedule() schedule |= pulse.Play(pulse.Waveform([1, 1, 1, 1]), pulse.DriveChannel(param_idx)) schedule |= pulse.Play(pulse.Waveform([1, 1, 1, 1]), pulse.DriveChannel(2 * param_idx)) with self.assertRaises(PulseError): schedule.assign_parameters({param_idx: 0}) def test_merging_upon_assignment(self): """Test that schedule can match instructions on a channel.""" param_idx = Parameter("q") schedule = pulse.Schedule() schedule |= pulse.Play(pulse.Waveform([1, 1, 1, 1]), pulse.DriveChannel(1)) schedule = schedule.insert( 4, pulse.Play(pulse.Waveform([1, 1, 1, 1]), pulse.DriveChannel(param_idx)) ) schedule.assign_parameters({param_idx: 1}) self.assertEqual(schedule.ch_duration(pulse.DriveChannel(1)), 8) self.assertEqual(schedule.channels, (pulse.DriveChannel(1),)) def test_overlapping_on_multiple_assignment(self): """Test that assigning one qubit then another raises error when overlapping.""" param_idx1 = Parameter("q1") param_idx2 = Parameter("q2") schedule = pulse.Schedule() schedule |= pulse.Play(pulse.Waveform([1, 1, 1, 1]), pulse.DriveChannel(param_idx1)) schedule |= pulse.Play(pulse.Waveform([1, 1, 1, 1]), pulse.DriveChannel(param_idx2)) schedule.assign_parameters({param_idx1: 2}) with self.assertRaises(PulseError): schedule.assign_parameters({param_idx2: 2}) def test_cannot_build_schedule_with_unassigned_duration(self): """Test we cannot build schedule with parameterized instructions""" dur = Parameter("dur") ch = pulse.DriveChannel(0) test_play = pulse.Play(pulse.Gaussian(dur, 0.1, dur / 4), ch) sched = pulse.Schedule() with self.assertRaises(UnassignedDurationError): sched.insert(0, test_play)
https://github.com/swe-train/qiskit__qiskit
swe-train
# 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. """Test schedule block subroutine reference mechanism.""" import numpy as np from qiskit import circuit, pulse from qiskit.pulse import builder from qiskit.pulse.transforms import inline_subroutines from qiskit.test import QiskitTestCase class TestReference(QiskitTestCase): """Test for basic behavior of reference mechanism.""" def test_append_schedule(self): """Test appending schedule without calling. Appended schedules are not subroutines. These are directly exposed to the outer block. """ with pulse.build() as sched_x1: pulse.play(pulse.Constant(100, 0.1, name="x1"), pulse.DriveChannel(0)) with pulse.build() as sched_y1: builder.append_schedule(sched_x1) with pulse.build() as sched_z1: builder.append_schedule(sched_y1) self.assertEqual(len(sched_z1.references), 0) def test_append_schedule_parameter_scope(self): """Test appending schedule without calling. Parameter in the appended schedule has the scope of outer schedule. """ param = circuit.Parameter("name") with pulse.build() as sched_x1: pulse.play(pulse.Constant(100, param, name="x1"), pulse.DriveChannel(0)) with pulse.build() as sched_y1: builder.append_schedule(sched_x1) with pulse.build() as sched_z1: builder.append_schedule(sched_y1) sched_param = next(iter(sched_z1.scoped_parameters())) self.assertEqual(sched_param.name, "root::name") # object equality self.assertEqual( sched_z1.search_parameters("root::name")[0], param, ) def test_refer_schedule(self): """Test refer to schedule by name. Outer block is only aware of its inner reference. Nested reference is not directly exposed to the most outer block. """ with pulse.build() as sched_x1: pulse.play(pulse.Constant(100, 0.1, name="x1"), pulse.DriveChannel(0)) with pulse.build() as sched_y1: builder.reference("x1", "d0") with pulse.build() as sched_z1: builder.reference("y1", "d0") sched_y1.assign_references({("x1", "d0"): sched_x1}) sched_z1.assign_references({("y1", "d0"): sched_y1}) self.assertEqual(len(sched_z1.references), 1) self.assertEqual(sched_z1.references[("y1", "d0")], sched_y1) self.assertEqual(len(sched_y1.references), 1) self.assertEqual(sched_y1.references[("x1", "d0")], sched_x1) def test_refer_schedule_parameter_scope(self): """Test refer to schedule by name. Parameter in the called schedule has the scope of called schedule. """ param = circuit.Parameter("name") with pulse.build() as sched_x1: pulse.play(pulse.Constant(100, param, name="x1"), pulse.DriveChannel(0)) with pulse.build() as sched_y1: builder.reference("x1", "d0") with pulse.build() as sched_z1: builder.reference("y1", "d0") sched_y1.assign_references({("x1", "d0"): sched_x1}) sched_z1.assign_references({("y1", "d0"): sched_y1}) sched_param = next(iter(sched_z1.scoped_parameters())) self.assertEqual(sched_param.name, "root::y1,d0::x1,d0::name") # object equality self.assertEqual( sched_z1.search_parameters("root::y1,d0::x1,d0::name")[0], param, ) # regex self.assertEqual( sched_z1.search_parameters(r"\S::x1,d0::name")[0], param, ) def test_call_schedule(self): """Test call schedule. Outer block is only aware of its inner reference. Nested reference is not directly exposed to the most outer block. """ with pulse.build() as sched_x1: pulse.play(pulse.Constant(100, 0.1, name="x1"), pulse.DriveChannel(0)) with pulse.build() as sched_y1: builder.call(sched_x1, name="x1") with pulse.build() as sched_z1: builder.call(sched_y1, name="y1") self.assertEqual(len(sched_z1.references), 1) self.assertEqual(sched_z1.references[("y1",)], sched_y1) self.assertEqual(len(sched_y1.references), 1) self.assertEqual(sched_y1.references[("x1",)], sched_x1) def test_call_schedule_parameter_scope(self): """Test call schedule. Parameter in the called schedule has the scope of called schedule. """ param = circuit.Parameter("name") with pulse.build() as sched_x1: pulse.play(pulse.Constant(100, param, name="x1"), pulse.DriveChannel(0)) with pulse.build() as sched_y1: builder.call(sched_x1, name="x1") with pulse.build() as sched_z1: builder.call(sched_y1, name="y1") sched_param = next(iter(sched_z1.scoped_parameters())) self.assertEqual(sched_param.name, "root::y1::x1::name") # object equality self.assertEqual( sched_z1.search_parameters("root::y1::x1::name")[0], param, ) # regex self.assertEqual( sched_z1.search_parameters(r"\S::x1::name")[0], param, ) def test_append_and_call_schedule(self): """Test call and append schedule. Reference is copied to the outer schedule by appending. Original reference remains unchanged. """ with pulse.build() as sched_x1: pulse.play(pulse.Constant(100, 0.1, name="x1"), pulse.DriveChannel(0)) with pulse.build() as sched_y1: builder.call(sched_x1, name="x1") with pulse.build() as sched_z1: builder.append_schedule(sched_y1) self.assertEqual(len(sched_z1.references), 1) self.assertEqual(sched_z1.references[("x1",)], sched_x1) # blocks[0] is sched_y1 and its reference is now point to outer block reference self.assertIs(sched_z1.blocks[0].references, sched_z1.references) # however the original program is protected to prevent unexpected mutation self.assertIsNot(sched_y1.references, sched_z1.references) # appended schedule is preserved self.assertEqual(len(sched_y1.references), 1) self.assertEqual(sched_y1.references[("x1",)], sched_x1) def test_calling_similar_schedule(self): """Test calling schedules with the same representation. sched_x1 and sched_y1 are the different subroutines, but same representation. Two references shoud be created. """ param1 = circuit.Parameter("param") param2 = circuit.Parameter("param") with pulse.build() as sched_x1: pulse.play(pulse.Constant(100, param1, name="p"), pulse.DriveChannel(0)) with pulse.build() as sched_y1: pulse.play(pulse.Constant(100, param2, name="p"), pulse.DriveChannel(0)) with pulse.build() as sched_z1: pulse.call(sched_x1) pulse.call(sched_y1) self.assertEqual(len(sched_z1.references), 2) def test_calling_same_schedule(self): """Test calling same schedule twice. Because it calls the same schedule, no duplication should occur in reference table. """ param = circuit.Parameter("param") with pulse.build() as sched_x1: pulse.play(pulse.Constant(100, param, name="x1"), pulse.DriveChannel(0)) with pulse.build() as sched_z1: pulse.call(sched_x1, name="same_sched") pulse.call(sched_x1, name="same_sched") self.assertEqual(len(sched_z1.references), 1) def test_calling_same_schedule_with_different_assignment(self): """Test calling same schedule twice but with different parameters. Same schedule is called twice but with different assignment. Two references should be created. """ param = circuit.Parameter("param") with pulse.build() as sched_x1: pulse.play(pulse.Constant(100, param, name="x1"), pulse.DriveChannel(0)) with pulse.build() as sched_z1: pulse.call(sched_x1, param=0.1) pulse.call(sched_x1, param=0.2) self.assertEqual(len(sched_z1.references), 2) def test_alignment_context(self): """Test nested alignment context. Inline alignment is identical to append_schedule operation. Thus scope is not newly generated. """ with pulse.build(name="x1") as sched_x1: with pulse.align_right(): with pulse.align_left(): pulse.play(pulse.Constant(100, 0.1, name="x1"), pulse.DriveChannel(0)) self.assertEqual(len(sched_x1.references), 0) def test_appending_child_block(self): """Test for edge case. User can append blocks which is an element of another schedule block. But this is not standard use case. In this case, references may contain subroutines which don't exist in the context. This is because all references within the program are centrally managed in the most outer block. """ with pulse.build() as sched_x1: pulse.play(pulse.Constant(100, 0.1, name="x1"), pulse.DriveChannel(0)) with pulse.build() as sched_y1: pulse.play(pulse.Constant(100, 0.2, name="y1"), pulse.DriveChannel(0)) with pulse.build() as sched_x2: builder.call(sched_x1, name="x1") self.assertEqual(list(sched_x2.references.keys()), [("x1",)]) with pulse.build() as sched_y2: builder.call(sched_y1, name="y1") self.assertEqual(list(sched_y2.references.keys()), [("y1",)]) with pulse.build() as sched_z1: builder.append_schedule(sched_x2) builder.append_schedule(sched_y2) self.assertEqual(list(sched_z1.references.keys()), [("x1",), ("y1",)]) # child block references point to its parent, i.e. sched_z1 self.assertIs(sched_z1.blocks[0].references, sched_z1._reference_manager) self.assertIs(sched_z1.blocks[1].references, sched_z1._reference_manager) with pulse.build() as sched_z2: # Append child block # The reference of this block is sched_z1.reference thus it contains both x1 and y1. # However, y1 doesn't exist in the context, so only x1 should be added. # Usually, user will append sched_x2 directly here, rather than sched_z1.blocks[0] # This is why this situation is an edge case. builder.append_schedule(sched_z1.blocks[0]) self.assertEqual(len(sched_z2.references), 1) self.assertEqual(sched_z2.references[("x1",)], sched_x1) def test_replacement(self): """Test nested alignment context. Replacing schedule block with schedule block. Removed block contains own reference, that should be removed with replacement. New block also contains reference, that should be passed to the current reference. """ with pulse.build() as sched_x1: pulse.play(pulse.Constant(100, 0.1, name="x1"), pulse.DriveChannel(0)) with pulse.build() as sched_y1: pulse.play(pulse.Constant(100, 0.2, name="y1"), pulse.DriveChannel(0)) with pulse.build() as sched_x2: builder.call(sched_x1, name="x1") with pulse.build() as sched_y2: builder.call(sched_y1, name="y1") with pulse.build() as sched_z1: builder.append_schedule(sched_x2) builder.append_schedule(sched_y2) self.assertEqual(len(sched_z1.references), 2) self.assertEqual(sched_z1.references[("x1",)], sched_x1) self.assertEqual(sched_z1.references[("y1",)], sched_y1) # Define schedule to replace with pulse.build() as sched_r1: pulse.play(pulse.Constant(100, 0.1, name="r1"), pulse.DriveChannel(0)) with pulse.build() as sched_r2: pulse.call(sched_r1, name="r1") sched_z2 = sched_z1.replace(sched_x2, sched_r2) self.assertEqual(len(sched_z2.references), 2) self.assertEqual(sched_z2.references[("r1",)], sched_r1) self.assertEqual(sched_z2.references[("y1",)], sched_y1) def test_special_parameter_name(self): """Testcase to guarantee usage of some special symbols in parameter name. These symbols might be often used in user code. No conflict should occur with the default scope delimiter. """ param = circuit.Parameter("my.parameter_object") with pulse.build() as sched_x1: pulse.play(pulse.Constant(100, param, name="x1"), pulse.DriveChannel(0)) with pulse.build() as sched_y1: pulse.reference("sub", "q0") sched_y1.assign_references({("sub", "q0"): sched_x1}) ret_param = sched_y1.search_parameters(r"\Ssub,q0::my.parameter_object")[0] self.assertEqual(param, ret_param) def test_parameter_in_multiple_scope(self): """Testcase for scope-aware parameter getter. When a single parameter object is used in multiple scopes, the scoped_parameters method must return parameter objects associated to each scope, while parameters property returns a single parameter object. """ param = circuit.Parameter("name") with pulse.build() as sched_x1: pulse.play(pulse.Constant(100, param), pulse.DriveChannel(0)) with pulse.build() as sched_y1: pulse.play(pulse.Constant(100, param), pulse.DriveChannel(1)) with pulse.build() as sched_z1: pulse.call(sched_x1, name="x1") pulse.call(sched_y1, name="y1") self.assertEqual(len(sched_z1.parameters), 1) self.assertEqual(len(sched_z1.scoped_parameters()), 2) self.assertEqual(sched_z1.search_parameters("root::x1::name")[0], param) self.assertEqual(sched_z1.search_parameters("root::y1::name")[0], param) def test_parallel_alignment_equality(self): """Testcase for potential edge case. In parallel alignment context, reference instruction is broadcasted to all channels. When new channel is added after reference, this should be connected with reference node. """ with pulse.build() as subroutine: pulse.reference("unassigned") with pulse.build() as sched1: with pulse.align_left(): pulse.delay(10, pulse.DriveChannel(0)) pulse.call(subroutine) # This should be broadcasted to d1 as well pulse.delay(10, pulse.DriveChannel(1)) with pulse.build() as sched2: with pulse.align_left(): pulse.delay(10, pulse.DriveChannel(0)) pulse.delay(10, pulse.DriveChannel(1)) pulse.call(subroutine) self.assertNotEqual(sched1, sched2) def test_subroutine_conflict(self): """Test for edge case of appending two schedule blocks having the references with conflicting reference key. This operation should fail because one of references will be gone after assignment. """ with pulse.build() as sched_x1: pulse.play(pulse.Constant(100, 0.1), pulse.DriveChannel(0)) with pulse.build() as sched_x2: pulse.call(sched_x1, name="conflict_name") self.assertEqual(sched_x2.references[("conflict_name",)], sched_x1) with pulse.build() as sched_y1: pulse.play(pulse.Constant(100, 0.2), pulse.DriveChannel(0)) with pulse.build() as sched_y2: pulse.call(sched_y1, name="conflict_name") self.assertEqual(sched_y2.references[("conflict_name",)], sched_y1) with self.assertRaises(pulse.exceptions.PulseError): with pulse.build(): builder.append_schedule(sched_x2) builder.append_schedule(sched_y2) def test_assign_existing_reference(self): """Test for explicitly assign existing reference. This operation should fail because overriding reference is not allowed. """ with pulse.build() as sched_x1: pulse.play(pulse.Constant(100, 0.1), pulse.DriveChannel(0)) with pulse.build() as sched_y1: pulse.play(pulse.Constant(100, 0.2), pulse.DriveChannel(0)) with pulse.build() as sched_z1: pulse.call(sched_x1, name="conflict_name") with self.assertRaises(pulse.exceptions.PulseError): sched_z1.assign_references({("conflict_name",): sched_y1}) class TestSubroutineWithCXGate(QiskitTestCase): """Test called program scope with practical example of building fully parametrized CX gate.""" def setUp(self): super().setUp() # parameters of X pulse self.xp_dur = circuit.Parameter("dur") self.xp_amp = circuit.Parameter("amp") self.xp_sigma = circuit.Parameter("sigma") self.xp_beta = circuit.Parameter("beta") # amplitude of SX pulse self.sxp_amp = circuit.Parameter("amp") # parameters of CR pulse self.cr_dur = circuit.Parameter("dur") self.cr_amp = circuit.Parameter("amp") self.cr_sigma = circuit.Parameter("sigma") self.cr_risefall = circuit.Parameter("risefall") # channels self.control_ch = circuit.Parameter("ctrl") self.target_ch = circuit.Parameter("tgt") self.cr_ch = circuit.Parameter("cr") # echo pulse on control qubit with pulse.build(name="xp") as xp_sched_q0: pulse.play( pulse.Drag( duration=self.xp_dur, amp=self.xp_amp, sigma=self.xp_sigma, beta=self.xp_beta, ), channel=pulse.DriveChannel(self.control_ch), ) self.xp_sched = xp_sched_q0 # local rotation on target qubit with pulse.build(name="sx") as sx_sched_q1: pulse.play( pulse.Drag( duration=self.xp_dur, amp=self.sxp_amp, sigma=self.xp_sigma, beta=self.xp_beta, ), channel=pulse.DriveChannel(self.target_ch), ) self.sx_sched = sx_sched_q1 # cross resonance with pulse.build(name="cr") as cr_sched: pulse.play( pulse.GaussianSquare( duration=self.cr_dur, amp=self.cr_amp, sigma=self.cr_sigma, risefall_sigma_ratio=self.cr_risefall, ), channel=pulse.ControlChannel(self.cr_ch), ) self.cr_sched = cr_sched def test_lazy_ecr(self): """Test lazy subroutines through ECR schedule construction.""" with pulse.build(name="lazy_ecr") as sched: with pulse.align_sequential(): pulse.reference("cr", "q0", "q1") pulse.reference("xp", "q0") with pulse.phase_offset(np.pi, pulse.ControlChannel(self.cr_ch)): pulse.reference("cr", "q0", "q1") pulse.reference("xp", "q0") # Schedule has references self.assertTrue(sched.is_referenced()) # Schedule is not schedulable because of unassigned references self.assertFalse(sched.is_schedulable()) # Two references cr and xp are called self.assertEqual(len(sched.references), 2) # Parameters in the current scope are Parameter("cr") which is used in phase_offset # References are not assigned yet. params = {p.name for p in sched.parameters} self.assertSetEqual(params, {"cr"}) # Parameter names are scoepd scoped_params = {p.name for p in sched.scoped_parameters()} self.assertSetEqual(scoped_params, {"root::cr"}) # Assign CR and XP schedule to the empty reference sched.assign_references({("cr", "q0", "q1"): self.cr_sched}) sched.assign_references({("xp", "q0"): self.xp_sched}) # Check updated references assigned_refs = sched.references self.assertEqual(assigned_refs[("cr", "q0", "q1")], self.cr_sched) self.assertEqual(assigned_refs[("xp", "q0")], self.xp_sched) # Parameter added from subroutines scoped_params = {p.name for p in sched.scoped_parameters()} ref_params = { # This is the cr parameter that belongs to phase_offset instruction in the root scope "root::cr", # This is the same cr parameter that belongs to the play instruction in a child scope "root::cr,q0,q1::cr", "root::cr,q0,q1::amp", "root::cr,q0,q1::dur", "root::cr,q0,q1::risefall", "root::cr,q0,q1::sigma", "root::xp,q0::ctrl", "root::xp,q0::amp", "root::xp,q0::beta", "root::xp,q0::dur", "root::xp,q0::sigma", } self.assertSetEqual(scoped_params, ref_params) # Get parameter without scope, cr amp and xp amp are hit. params = sched.get_parameters(parameter_name="amp") self.assertEqual(len(params), 2) # Get parameter with scope, only xp amp params = sched.search_parameters(parameter_regex="root::xp,q0::amp") self.assertEqual(len(params), 1) def test_cnot(self): """Integration test with CNOT schedule construction.""" # echeod cross resonance with pulse.build(name="ecr", default_alignment="sequential") as ecr_sched: pulse.call(self.cr_sched, name="cr") pulse.call(self.xp_sched, name="xp") with pulse.phase_offset(np.pi, pulse.ControlChannel(self.cr_ch)): pulse.call(self.cr_sched, name="cr") pulse.call(self.xp_sched, name="xp") # cnot gate, locally equivalent to ecr with pulse.build(name="cx", default_alignment="sequential") as cx_sched: pulse.shift_phase(np.pi / 2, pulse.DriveChannel(self.control_ch)) pulse.call(self.sx_sched, name="sx") pulse.call(ecr_sched, name="ecr") # get parameter with scope, full scope is not needed xp_amp = cx_sched.search_parameters(r"\S:xp::amp")[0] self.assertEqual(self.xp_amp, xp_amp) # get parameter with scope, of course full scope can be specified xp_amp_full_scoped = cx_sched.search_parameters("root::ecr::xp::amp")[0] self.assertEqual(xp_amp_full_scoped, xp_amp) # assign parameters assigned_cx = cx_sched.assign_parameters( value_dict={ self.cr_ch: 0, self.control_ch: 0, self.target_ch: 1, self.sxp_amp: 0.1, self.xp_amp: 0.2, self.xp_dur: 160, self.xp_sigma: 40, self.xp_beta: 3.0, self.cr_amp: 0.5, self.cr_dur: 800, self.cr_sigma: 64, self.cr_risefall: 2, }, inplace=True, ) flatten_cx = inline_subroutines(assigned_cx) with pulse.build(default_alignment="sequential") as ref_cx: # sz pulse.shift_phase(np.pi / 2, pulse.DriveChannel(0)) with pulse.align_left(): # sx pulse.play( pulse.Drag( duration=160, amp=0.1, sigma=40, beta=3.0, ), channel=pulse.DriveChannel(1), ) with pulse.align_sequential(): # cr with pulse.align_left(): pulse.play( pulse.GaussianSquare( duration=800, amp=0.5, sigma=64, risefall_sigma_ratio=2, ), channel=pulse.ControlChannel(0), ) # xp with pulse.align_left(): pulse.play( pulse.Drag( duration=160, amp=0.2, sigma=40, beta=3.0, ), channel=pulse.DriveChannel(0), ) with pulse.phase_offset(np.pi, pulse.ControlChannel(0)): # cr with pulse.align_left(): pulse.play( pulse.GaussianSquare( duration=800, amp=0.5, sigma=64, risefall_sigma_ratio=2, ), channel=pulse.ControlChannel(0), ) # xp with pulse.align_left(): pulse.play( pulse.Drag( duration=160, amp=0.2, sigma=40, beta=3.0, ), channel=pulse.DriveChannel(0), ) self.assertEqual(flatten_cx, ref_cx)
https://github.com/swe-train/qiskit__qiskit
swe-train
# 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. """Test cases for the pulse Schedule transforms.""" import unittest from typing import List, Set import numpy as np from qiskit import pulse from qiskit.pulse import ( Play, Delay, Acquire, Schedule, Waveform, Drag, Gaussian, GaussianSquare, Constant, ) from qiskit.pulse import transforms, instructions from qiskit.pulse.channels import ( MemorySlot, DriveChannel, AcquireChannel, RegisterSlot, SnapshotChannel, ) from qiskit.pulse.instructions import directives from qiskit.test import QiskitTestCase from qiskit.providers.fake_provider import FakeOpenPulse2Q class TestAlignMeasures(QiskitTestCase): """Test the helper function which aligns acquires.""" def setUp(self): super().setUp() self.backend = FakeOpenPulse2Q() self.config = self.backend.configuration() self.inst_map = self.backend.defaults().instruction_schedule_map self.short_pulse = pulse.Waveform( samples=np.array([0.02739068], dtype=np.complex128), name="p0" ) def test_align_measures(self): """Test that one acquire is delayed to match the time of the later acquire.""" sched = pulse.Schedule(name="fake_experiment") sched.insert(0, Play(self.short_pulse, self.config.drive(0)), inplace=True) sched.insert(1, Acquire(5, self.config.acquire(0), MemorySlot(0)), inplace=True) sched.insert(10, Acquire(5, self.config.acquire(1), MemorySlot(1)), inplace=True) sched.insert(10, Play(self.short_pulse, self.config.measure(0)), inplace=True) sched.insert(11, Play(self.short_pulse, self.config.measure(0)), inplace=True) sched.insert(10, Play(self.short_pulse, self.config.measure(1)), inplace=True) aligned = transforms.align_measures([sched])[0] self.assertEqual(aligned.name, "fake_experiment") ref = pulse.Schedule(name="fake_experiment") ref.insert(0, Play(self.short_pulse, self.config.drive(0)), inplace=True) ref.insert(10, Acquire(5, self.config.acquire(0), MemorySlot(0)), inplace=True) ref.insert(10, Acquire(5, self.config.acquire(1), MemorySlot(1)), inplace=True) ref.insert(19, Play(self.short_pulse, self.config.measure(0)), inplace=True) ref.insert(20, Play(self.short_pulse, self.config.measure(0)), inplace=True) ref.insert(10, Play(self.short_pulse, self.config.measure(1)), inplace=True) self.assertEqual(aligned, ref) aligned = transforms.align_measures([sched], self.inst_map, align_time=20)[0] ref = pulse.Schedule(name="fake_experiment") ref.insert(10, Play(self.short_pulse, self.config.drive(0)), inplace=True) ref.insert(20, Acquire(5, self.config.acquire(0), MemorySlot(0)), inplace=True) ref.insert(20, Acquire(5, self.config.acquire(1), MemorySlot(1)), inplace=True) ref.insert(29, Play(self.short_pulse, self.config.measure(0)), inplace=True) ref.insert(30, Play(self.short_pulse, self.config.measure(0)), inplace=True) ref.insert(20, Play(self.short_pulse, self.config.measure(1)), inplace=True) self.assertEqual(aligned, ref) def test_align_post_u3(self): """Test that acquires are scheduled no sooner than the duration of the longest X gate.""" sched = pulse.Schedule(name="fake_experiment") sched = sched.insert(0, Play(self.short_pulse, self.config.drive(0))) sched = sched.insert(1, Acquire(5, self.config.acquire(0), MemorySlot(0))) sched = transforms.align_measures([sched], self.inst_map)[0] for time, inst in sched.instructions: if isinstance(inst, Acquire): self.assertEqual(time, 4) sched = transforms.align_measures([sched], self.inst_map, max_calibration_duration=10)[0] for time, inst in sched.instructions: if isinstance(inst, Acquire): self.assertEqual(time, 10) def test_multi_acquire(self): """Test that the last acquire is aligned to if multiple acquires occur on the same channel.""" sched = pulse.Schedule() sched.insert(0, Play(self.short_pulse, self.config.drive(0)), inplace=True) sched.insert(4, Acquire(5, self.config.acquire(0), MemorySlot(0)), inplace=True) sched.insert(20, Acquire(5, self.config.acquire(1), MemorySlot(1)), inplace=True) sched.insert(10, Acquire(5, self.config.acquire(0), MemorySlot(0)), inplace=True) aligned = transforms.align_measures([sched], self.inst_map) ref = pulse.Schedule() ref.insert(0, Play(self.short_pulse, self.config.drive(0)), inplace=True) ref.insert(20, Acquire(5, self.config.acquire(0), MemorySlot(0)), inplace=True) ref.insert(20, Acquire(5, self.config.acquire(1), MemorySlot(1)), inplace=True) ref.insert(26, Acquire(5, self.config.acquire(0), MemorySlot(0)), inplace=True) self.assertEqual(aligned[0], ref) def test_multiple_acquires(self): """Test that multiple acquires are also aligned.""" sched = pulse.Schedule(name="fake_experiment") sched.insert(0, Acquire(5, self.config.acquire(0), MemorySlot(0)), inplace=True) sched.insert(5, Acquire(5, self.config.acquire(0), MemorySlot(0)), inplace=True) sched.insert(10, Acquire(5, self.config.acquire(1), MemorySlot(1)), inplace=True) ref = pulse.Schedule() ref.insert(10, Acquire(5, self.config.acquire(0), MemorySlot(0)), inplace=True) ref.insert(15, Acquire(5, self.config.acquire(0), MemorySlot(0)), inplace=True) ref.insert(10, Acquire(5, self.config.acquire(1), MemorySlot(1)), inplace=True) aligned = transforms.align_measures([sched], self.inst_map)[0] self.assertEqual(aligned, ref) def test_align_across_schedules(self): """Test that acquires are aligned together across multiple schedules.""" sched1 = pulse.Schedule(name="fake_experiment") sched1 = sched1.insert(0, Play(self.short_pulse, self.config.drive(0))) sched1 = sched1.insert(10, Acquire(5, self.config.acquire(0), MemorySlot(0))) sched2 = pulse.Schedule(name="fake_experiment") sched2 = sched2.insert(3, Play(self.short_pulse, self.config.drive(0))) sched2 = sched2.insert(25, Acquire(5, self.config.acquire(0), MemorySlot(0))) schedules = transforms.align_measures([sched1, sched2], self.inst_map) for time, inst in schedules[0].instructions: if isinstance(inst, Acquire): self.assertEqual(time, 25) for time, inst in schedules[0].instructions: if isinstance(inst, Acquire): self.assertEqual(time, 25) def test_align_all(self): """Test alignment of all instructions in a schedule.""" sched0 = pulse.Schedule() sched0.insert(0, Play(self.short_pulse, self.config.drive(0)), inplace=True) sched0.insert(10, Acquire(5, self.config.acquire(0), MemorySlot(0)), inplace=True) sched1 = pulse.Schedule() sched1.insert(25, Play(self.short_pulse, self.config.drive(0)), inplace=True) sched1.insert(25, Acquire(5, self.config.acquire(0), MemorySlot(0)), inplace=True) all_aligned = transforms.align_measures([sched0, sched1], self.inst_map, align_all=True) ref1_aligned = pulse.Schedule() ref1_aligned.insert(15, Play(self.short_pulse, self.config.drive(0)), inplace=True) ref1_aligned.insert(25, Acquire(5, self.config.acquire(0), MemorySlot(0)), inplace=True) self.assertEqual(all_aligned[0], ref1_aligned) self.assertEqual(all_aligned[1], sched1) ref1_not_aligned = pulse.Schedule() ref1_not_aligned.insert(0, Play(self.short_pulse, self.config.drive(0)), inplace=True) ref1_not_aligned.insert(25, Acquire(5, self.config.acquire(0), MemorySlot(0)), inplace=True) all_not_aligned = transforms.align_measures( [sched0, sched1], self.inst_map, align_all=False, ) self.assertEqual(all_not_aligned[0], ref1_not_aligned) self.assertEqual(all_not_aligned[1], sched1) def test_measurement_at_zero(self): """Test that acquire at t=0 works.""" sched1 = pulse.Schedule(name="fake_experiment") sched1 = sched1.insert(0, Play(self.short_pulse, self.config.drive(0))) sched1 = sched1.insert(0, Acquire(5, self.config.acquire(0), MemorySlot(0))) sched2 = pulse.Schedule(name="fake_experiment") sched2 = sched2.insert(0, Play(self.short_pulse, self.config.drive(0))) sched2 = sched2.insert(0, Acquire(5, self.config.acquire(0), MemorySlot(0))) schedules = transforms.align_measures([sched1, sched2], max_calibration_duration=0) for time, inst in schedules[0].instructions: if isinstance(inst, Acquire): self.assertEqual(time, 0) for time, inst in schedules[0].instructions: if isinstance(inst, Acquire): self.assertEqual(time, 0) class TestAddImplicitAcquires(QiskitTestCase): """Test the helper function which makes implicit acquires explicit.""" def setUp(self): super().setUp() self.backend = FakeOpenPulse2Q() self.config = self.backend.configuration() self.short_pulse = pulse.Waveform( samples=np.array([0.02739068], dtype=np.complex128), name="p0" ) sched = pulse.Schedule(name="fake_experiment") sched = sched.insert(0, Play(self.short_pulse, self.config.drive(0))) sched = sched.insert(5, Acquire(5, self.config.acquire(0), MemorySlot(0))) sched = sched.insert(5, Acquire(5, self.config.acquire(1), MemorySlot(1))) self.sched = sched def test_add_implicit(self): """Test that implicit acquires are made explicit according to the meas map.""" sched = transforms.add_implicit_acquires(self.sched, [[0, 1]]) acquired_qubits = set() for _, inst in sched.instructions: if isinstance(inst, Acquire): acquired_qubits.add(inst.acquire.index) self.assertEqual(acquired_qubits, {0, 1}) def test_add_across_meas_map_sublists(self): """Test that implicit acquires in separate meas map sublists are all added.""" sched = transforms.add_implicit_acquires(self.sched, [[0, 2], [1, 3]]) acquired_qubits = set() for _, inst in sched.instructions: if isinstance(inst, Acquire): acquired_qubits.add(inst.acquire.index) self.assertEqual(acquired_qubits, {0, 1, 2, 3}) def test_dont_add_all(self): """Test that acquires aren't added if no qubits in the sublist aren't being acquired.""" sched = transforms.add_implicit_acquires(self.sched, [[4, 5], [0, 2], [1, 3]]) acquired_qubits = set() for _, inst in sched.instructions: if isinstance(inst, Acquire): acquired_qubits.add(inst.acquire.index) self.assertEqual(acquired_qubits, {0, 1, 2, 3}) def test_multiple_acquires(self): """Test for multiple acquires.""" sched = pulse.Schedule() acq_q0 = pulse.Acquire(1200, AcquireChannel(0), MemorySlot(0)) sched += acq_q0 sched += acq_q0 << sched.duration sched = transforms.add_implicit_acquires(sched, meas_map=[[0]]) self.assertEqual(sched.instructions, ((0, acq_q0), (2400, acq_q0))) class TestPad(QiskitTestCase): """Test padding of schedule with delays.""" def test_padding_empty_schedule(self): """Test padding of empty schedule.""" self.assertEqual(pulse.Schedule(), transforms.pad(pulse.Schedule())) def test_padding_schedule(self): """Test padding schedule.""" delay = 10 sched = ( Delay(delay, DriveChannel(0)).shift(10) + Delay(delay, DriveChannel(0)).shift(10) + Delay(delay, DriveChannel(1)).shift(10) ) ref_sched = ( sched # pylint: disable=unsupported-binary-operation | Delay(delay, DriveChannel(0)) | Delay(delay, DriveChannel(0)).shift(20) | Delay(delay, DriveChannel(1)) | Delay( # pylint: disable=unsupported-binary-operation 2 * delay, DriveChannel(1) ).shift(20) ) self.assertEqual(transforms.pad(sched), ref_sched) def test_padding_schedule_inverse_order(self): """Test padding schedule is insensitive to order in which commands were added. This test is the same as `test_adding_schedule` but the order by channel in which commands were added to the schedule to be padded has been reversed. """ delay = 10 sched = ( Delay(delay, DriveChannel(1)).shift(10) + Delay(delay, DriveChannel(0)).shift(10) + Delay(delay, DriveChannel(0)).shift(10) ) ref_sched = ( sched # pylint: disable=unsupported-binary-operation | Delay(delay, DriveChannel(0)) | Delay(delay, DriveChannel(0)).shift(20) | Delay(delay, DriveChannel(1)) | Delay( # pylint: disable=unsupported-binary-operation 2 * delay, DriveChannel(1) ).shift(20) ) self.assertEqual(transforms.pad(sched), ref_sched) def test_padding_until_less(self): """Test padding until time that is less than schedule duration.""" delay = 10 sched = Delay(delay, DriveChannel(0)).shift(10) + Delay(delay, DriveChannel(1)) ref_sched = sched | Delay(delay, DriveChannel(0)) | Delay(5, DriveChannel(1)).shift(10) self.assertEqual(transforms.pad(sched, until=15), ref_sched) def test_padding_until_greater(self): """Test padding until time that is greater than schedule duration.""" delay = 10 sched = Delay(delay, DriveChannel(0)).shift(10) + Delay(delay, DriveChannel(1)) ref_sched = ( sched # pylint: disable=unsupported-binary-operation | Delay(delay, DriveChannel(0)) | Delay(30, DriveChannel(0)).shift(20) | Delay(40, DriveChannel(1)).shift(10) # pylint: disable=unsupported-binary-operation ) self.assertEqual(transforms.pad(sched, until=50), ref_sched) def test_padding_supplied_channels(self): """Test padding of only specified channels.""" delay = 10 sched = Delay(delay, DriveChannel(0)).shift(10) + Delay(delay, DriveChannel(1)) ref_sched = sched | Delay(delay, DriveChannel(0)) | Delay(2 * delay, DriveChannel(2)) channels = [DriveChannel(0), DriveChannel(2)] self.assertEqual(transforms.pad(sched, channels=channels), ref_sched) def test_padding_less_than_sched_duration(self): """Test that the until arg is respected even for less than the input schedule duration.""" delay = 10 sched = Delay(delay, DriveChannel(0)) + Delay(delay, DriveChannel(0)).shift(20) ref_sched = sched | pulse.Delay(5, DriveChannel(0)).shift(10) self.assertEqual(transforms.pad(sched, until=15), ref_sched) def test_padding_prepended_delay(self): """Test that there is delay before the first instruction.""" delay = 10 sched = Delay(delay, DriveChannel(0)).shift(10) + Delay(delay, DriveChannel(0)) ref_sched = ( Delay(delay, DriveChannel(0)) + Delay(delay, DriveChannel(0)) + Delay(delay, DriveChannel(0)) ) self.assertEqual(transforms.pad(sched, until=30, inplace=True), ref_sched) def test_pad_no_delay_on_classical_io_channels(self): """Test padding does not apply to classical IO channels.""" delay = 10 sched = ( Delay(delay, MemorySlot(0)).shift(20) + Delay(delay, RegisterSlot(0)).shift(10) + Delay(delay, SnapshotChannel()) ) ref_sched = ( Delay(delay, MemorySlot(0)).shift(20) + Delay(delay, RegisterSlot(0)).shift(10) + Delay(delay, SnapshotChannel()) ) self.assertEqual(transforms.pad(sched, until=15), ref_sched) def get_pulse_ids(schedules: List[Schedule]) -> Set[int]: """Returns ids of pulses used in Schedules.""" ids = set() for schedule in schedules: for _, inst in schedule.instructions: ids.add(inst.pulse.id) return ids class TestCompressTransform(QiskitTestCase): """Compress function test.""" def test_with_duplicates(self): """Test compression of schedule.""" schedule = Schedule() drive_channel = DriveChannel(0) schedule += Play(Waveform([0.0, 0.1]), drive_channel) schedule += Play(Waveform([0.0, 0.1]), drive_channel) compressed_schedule = transforms.compress_pulses([schedule]) original_pulse_ids = get_pulse_ids([schedule]) compressed_pulse_ids = get_pulse_ids(compressed_schedule) self.assertEqual(len(compressed_pulse_ids), 1) self.assertEqual(len(original_pulse_ids), 2) self.assertTrue(next(iter(compressed_pulse_ids)) in original_pulse_ids) def test_sample_pulse_with_clipping(self): """Test sample pulses with clipping.""" schedule = Schedule() drive_channel = DriveChannel(0) schedule += Play(Waveform([0.0, 1.0]), drive_channel) schedule += Play(Waveform([0.0, 1.001], epsilon=1e-3), drive_channel) schedule += Play(Waveform([0.0, 1.0000000001]), drive_channel) compressed_schedule = transforms.compress_pulses([schedule]) original_pulse_ids = get_pulse_ids([schedule]) compressed_pulse_ids = get_pulse_ids(compressed_schedule) self.assertEqual(len(compressed_pulse_ids), 1) self.assertEqual(len(original_pulse_ids), 3) self.assertTrue(next(iter(compressed_pulse_ids)) in original_pulse_ids) def test_no_duplicates(self): """Test with no pulse duplicates.""" schedule = Schedule() drive_channel = DriveChannel(0) schedule += Play(Waveform([0.0, 1.0]), drive_channel) schedule += Play(Waveform([0.0, 0.9]), drive_channel) schedule += Play(Waveform([0.0, 0.3]), drive_channel) compressed_schedule = transforms.compress_pulses([schedule]) original_pulse_ids = get_pulse_ids([schedule]) compressed_pulse_ids = get_pulse_ids(compressed_schedule) self.assertEqual(len(original_pulse_ids), len(compressed_pulse_ids)) def test_parametric_pulses_with_duplicates(self): """Test with parametric pulses.""" schedule = Schedule() drive_channel = DriveChannel(0) schedule += Play(Gaussian(duration=25, sigma=4, amp=0.5, angle=np.pi / 2), drive_channel) schedule += Play(Gaussian(duration=25, sigma=4, amp=0.5, angle=np.pi / 2), drive_channel) schedule += Play(GaussianSquare(duration=150, amp=0.2, sigma=8, width=140), drive_channel) schedule += Play(GaussianSquare(duration=150, amp=0.2, sigma=8, width=140), drive_channel) schedule += Play(Constant(duration=150, amp=0.5, angle=0.7), drive_channel) schedule += Play(Constant(duration=150, amp=0.5, angle=0.7), drive_channel) schedule += Play(Drag(duration=25, amp=0.4, angle=-0.3, sigma=7.8, beta=4), drive_channel) schedule += Play(Drag(duration=25, amp=0.4, angle=-0.3, sigma=7.8, beta=4), drive_channel) compressed_schedule = transforms.compress_pulses([schedule]) original_pulse_ids = get_pulse_ids([schedule]) compressed_pulse_ids = get_pulse_ids(compressed_schedule) self.assertEqual(len(original_pulse_ids), 8) self.assertEqual(len(compressed_pulse_ids), 4) def test_parametric_pulses_with_no_duplicates(self): """Test parametric pulses with no duplicates.""" schedule = Schedule() drive_channel = DriveChannel(0) schedule += Play(Gaussian(duration=25, sigma=4, amp=0.5, angle=np.pi / 2), drive_channel) schedule += Play(Gaussian(duration=25, sigma=4, amp=0.49, angle=np.pi / 2), drive_channel) schedule += Play(GaussianSquare(duration=150, amp=0.2, sigma=8, width=140), drive_channel) schedule += Play(GaussianSquare(duration=150, amp=0.19, sigma=8, width=140), drive_channel) schedule += Play(Constant(duration=150, amp=0.5, angle=0.3), drive_channel) schedule += Play(Constant(duration=150, amp=0.51, angle=0.3), drive_channel) schedule += Play(Drag(duration=25, amp=0.5, angle=0.5, sigma=7.8, beta=4), drive_channel) schedule += Play(Drag(duration=25, amp=0.5, angle=0.51, sigma=7.8, beta=4), drive_channel) compressed_schedule = transforms.compress_pulses([schedule]) original_pulse_ids = get_pulse_ids([schedule]) compressed_pulse_ids = get_pulse_ids(compressed_schedule) self.assertEqual(len(original_pulse_ids), len(compressed_pulse_ids)) def test_with_different_channels(self): """Test with different channels.""" schedule = Schedule() schedule += Play(Waveform([0.0, 0.1]), DriveChannel(0)) schedule += Play(Waveform([0.0, 0.1]), DriveChannel(1)) compressed_schedule = transforms.compress_pulses([schedule]) original_pulse_ids = get_pulse_ids([schedule]) compressed_pulse_ids = get_pulse_ids(compressed_schedule) self.assertEqual(len(original_pulse_ids), 2) self.assertEqual(len(compressed_pulse_ids), 1) def test_sample_pulses_with_tolerance(self): """Test sample pulses with tolerance.""" schedule = Schedule() schedule += Play(Waveform([0.0, 0.1001], epsilon=1e-3), DriveChannel(0)) schedule += Play(Waveform([0.0, 0.1], epsilon=1e-3), DriveChannel(1)) compressed_schedule = transforms.compress_pulses([schedule]) original_pulse_ids = get_pulse_ids([schedule]) compressed_pulse_ids = get_pulse_ids(compressed_schedule) self.assertEqual(len(original_pulse_ids), 2) self.assertEqual(len(compressed_pulse_ids), 1) def test_multiple_schedules(self): """Test multiple schedules.""" schedules = [] for _ in range(2): schedule = Schedule() drive_channel = DriveChannel(0) schedule += Play(Waveform([0.0, 0.1]), drive_channel) schedule += Play(Waveform([0.0, 0.1]), drive_channel) schedule += Play(Waveform([0.0, 0.2]), drive_channel) schedules.append(schedule) compressed_schedule = transforms.compress_pulses(schedules) original_pulse_ids = get_pulse_ids(schedules) compressed_pulse_ids = get_pulse_ids(compressed_schedule) self.assertEqual(len(original_pulse_ids), 6) self.assertEqual(len(compressed_pulse_ids), 2) class TestAlignSequential(QiskitTestCase): """Test sequential alignment transform.""" def test_align_sequential(self): """Test sequential alignment without a barrier.""" context = transforms.AlignSequential() d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) schedule = pulse.Schedule() schedule.insert(1, instructions.Delay(3, d0), inplace=True) schedule.insert(4, instructions.Delay(5, d1), inplace=True) schedule.insert(12, instructions.Delay(7, d0), inplace=True) schedule = context.align(schedule) reference = pulse.Schedule() # d0 reference.insert(0, instructions.Delay(3, d0), inplace=True) reference.insert(8, instructions.Delay(7, d0), inplace=True) # d1 reference.insert(3, instructions.Delay(5, d1), inplace=True) self.assertEqual(schedule, reference) def test_align_sequential_with_barrier(self): """Test sequential alignment with a barrier.""" context = transforms.AlignSequential() d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) schedule = pulse.Schedule() schedule.insert(1, instructions.Delay(3, d0), inplace=True) schedule.append(directives.RelativeBarrier(d0, d1), inplace=True) schedule.insert(4, instructions.Delay(5, d1), inplace=True) schedule.insert(12, instructions.Delay(7, d0), inplace=True) schedule = context.align(schedule) reference = pulse.Schedule() reference.insert(0, instructions.Delay(3, d0), inplace=True) reference.insert(3, directives.RelativeBarrier(d0, d1), inplace=True) reference.insert(3, instructions.Delay(5, d1), inplace=True) reference.insert(8, instructions.Delay(7, d0), inplace=True) self.assertEqual(schedule, reference) class TestAlignLeft(QiskitTestCase): """Test left alignment transform.""" def test_align_left(self): """Test left alignment without a barrier.""" context = transforms.AlignLeft() d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) d2 = pulse.DriveChannel(2) schedule = pulse.Schedule() schedule.insert(1, instructions.Delay(3, d0), inplace=True) schedule.insert(17, instructions.Delay(11, d2), inplace=True) sched_grouped = pulse.Schedule() sched_grouped += instructions.Delay(5, d1) sched_grouped += instructions.Delay(7, d0) schedule.append(sched_grouped, inplace=True) schedule = context.align(schedule) reference = pulse.Schedule() # d0 reference.insert(0, instructions.Delay(3, d0), inplace=True) reference.insert(3, instructions.Delay(7, d0), inplace=True) # d1 reference.insert(3, instructions.Delay(5, d1), inplace=True) # d2 reference.insert(0, instructions.Delay(11, d2), inplace=True) self.assertEqual(schedule, reference) def test_align_left_with_barrier(self): """Test left alignment with a barrier.""" context = transforms.AlignLeft() d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) d2 = pulse.DriveChannel(2) schedule = pulse.Schedule() schedule.insert(1, instructions.Delay(3, d0), inplace=True) schedule.append(directives.RelativeBarrier(d0, d1, d2), inplace=True) schedule.insert(17, instructions.Delay(11, d2), inplace=True) sched_grouped = pulse.Schedule() sched_grouped += instructions.Delay(5, d1) sched_grouped += instructions.Delay(7, d0) schedule.append(sched_grouped, inplace=True) schedule = transforms.remove_directives(context.align(schedule)) reference = pulse.Schedule() # d0 reference.insert(0, instructions.Delay(3, d0), inplace=True) reference.insert(3, instructions.Delay(7, d0), inplace=True) # d1 reference = reference.insert(3, instructions.Delay(5, d1)) # d2 reference = reference.insert(3, instructions.Delay(11, d2)) self.assertEqual(schedule, reference) class TestAlignRight(QiskitTestCase): """Test right alignment transform.""" def test_align_right(self): """Test right alignment without a barrier.""" context = transforms.AlignRight() d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) d2 = pulse.DriveChannel(2) schedule = pulse.Schedule() schedule.insert(1, instructions.Delay(3, d0), inplace=True) schedule.insert(17, instructions.Delay(11, d2), inplace=True) sched_grouped = pulse.Schedule() sched_grouped.insert(2, instructions.Delay(5, d1), inplace=True) sched_grouped += instructions.Delay(7, d0) schedule.append(sched_grouped, inplace=True) schedule = context.align(schedule) reference = pulse.Schedule() # d0 reference.insert(1, instructions.Delay(3, d0), inplace=True) reference.insert(4, instructions.Delay(7, d0), inplace=True) # d1 reference.insert(6, instructions.Delay(5, d1), inplace=True) # d2 reference.insert(0, instructions.Delay(11, d2), inplace=True) self.assertEqual(schedule, reference) def test_align_right_with_barrier(self): """Test right alignment with a barrier.""" context = transforms.AlignRight() d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) d2 = pulse.DriveChannel(2) schedule = pulse.Schedule() schedule.insert(1, instructions.Delay(3, d0), inplace=True) schedule.append(directives.RelativeBarrier(d0, d1, d2), inplace=True) schedule.insert(17, instructions.Delay(11, d2), inplace=True) sched_grouped = pulse.Schedule() sched_grouped.insert(2, instructions.Delay(5, d1), inplace=True) sched_grouped += instructions.Delay(7, d0) schedule.append(sched_grouped, inplace=True) schedule = transforms.remove_directives(context.align(schedule)) reference = pulse.Schedule() # d0 reference.insert(0, instructions.Delay(3, d0), inplace=True) reference.insert(7, instructions.Delay(7, d0), inplace=True) # d1 reference.insert(9, instructions.Delay(5, d1), inplace=True) # d2 reference.insert(3, instructions.Delay(11, d2), inplace=True) self.assertEqual(schedule, reference) class TestAlignEquispaced(QiskitTestCase): """Test equispaced alignment transform.""" def test_equispaced_with_short_duration(self): """Test equispaced context with duration shorter than the schedule duration.""" context = transforms.AlignEquispaced(duration=20) d0 = pulse.DriveChannel(0) schedule = pulse.Schedule() for _ in range(3): schedule.append(Delay(10, d0), inplace=True) schedule = context.align(schedule) reference = pulse.Schedule() reference.insert(0, Delay(10, d0), inplace=True) reference.insert(10, Delay(10, d0), inplace=True) reference.insert(20, Delay(10, d0), inplace=True) self.assertEqual(schedule, reference) def test_equispaced_with_longer_duration(self): """Test equispaced context with duration longer than the schedule duration.""" context = transforms.AlignEquispaced(duration=50) d0 = pulse.DriveChannel(0) schedule = pulse.Schedule() for _ in range(3): schedule.append(Delay(10, d0), inplace=True) schedule = context.align(schedule) reference = pulse.Schedule() reference.insert(0, Delay(10, d0), inplace=True) reference.insert(20, Delay(10, d0), inplace=True) reference.insert(40, Delay(10, d0), inplace=True) self.assertEqual(schedule, reference) def test_equispaced_with_multiple_channels_short_duration(self): """Test equispaced context with multiple channels and duration shorter than the total duration.""" context = transforms.AlignEquispaced(duration=20) d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) schedule = pulse.Schedule() schedule.append(Delay(10, d0), inplace=True) schedule.append(Delay(20, d1), inplace=True) schedule = context.align(schedule) reference = pulse.Schedule() reference.insert(0, Delay(10, d0), inplace=True) reference.insert(0, Delay(20, d1), inplace=True) self.assertEqual(schedule, reference) def test_equispaced_with_multiple_channels_longer_duration(self): """Test equispaced context with multiple channels and duration longer than the total duration.""" context = transforms.AlignEquispaced(duration=30) d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) schedule = pulse.Schedule() schedule.append(Delay(10, d0), inplace=True) schedule.append(Delay(20, d1), inplace=True) schedule = context.align(schedule) reference = pulse.Schedule() reference.insert(0, Delay(10, d0), inplace=True) reference.insert(10, Delay(20, d1), inplace=True) self.assertEqual(schedule, reference) class TestAlignFunc(QiskitTestCase): """Test callback alignment transform.""" @staticmethod def _position(ind): """Returns 0.25, 0.5, 0.75 for ind = 1, 2, 3.""" return ind / (3 + 1) def test_numerical_with_short_duration(self): """Test numerical alignment context with duration shorter than the schedule duration.""" context = transforms.AlignFunc(duration=20, func=self._position) d0 = pulse.DriveChannel(0) schedule = pulse.Schedule() for _ in range(3): schedule.append(Delay(10, d0), inplace=True) schedule = context.align(schedule) reference = pulse.Schedule() reference.insert(0, Delay(10, d0), inplace=True) reference.insert(10, Delay(10, d0), inplace=True) reference.insert(20, Delay(10, d0), inplace=True) self.assertEqual(schedule, reference) def test_numerical_with_longer_duration(self): """Test numerical alignment context with duration longer than the schedule duration.""" context = transforms.AlignFunc(duration=80, func=self._position) d0 = pulse.DriveChannel(0) schedule = pulse.Schedule() for _ in range(3): schedule.append(Delay(10, d0), inplace=True) schedule = context.align(schedule) reference = pulse.Schedule() reference.insert(15, Delay(10, d0), inplace=True) reference.insert(35, Delay(10, d0), inplace=True) reference.insert(55, Delay(10, d0), inplace=True) self.assertEqual(schedule, reference) class TestFlatten(QiskitTestCase): """Test flattening transform.""" def test_flatten(self): """Test the flatten transform.""" context_left = transforms.AlignLeft() d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) schedule = pulse.Schedule() schedule += instructions.Delay(3, d0) grouped = pulse.Schedule() grouped += instructions.Delay(5, d1) grouped += instructions.Delay(7, d0) # include a grouped schedule grouped = schedule + grouped # flatten the schedule inline internal groups flattened = transforms.flatten(grouped) # align all the instructions to the left after flattening flattened = context_left.align(flattened) grouped = context_left.align(grouped) reference = pulse.Schedule() # d0 reference.insert(0, instructions.Delay(3, d0), inplace=True) reference.insert(3, instructions.Delay(7, d0), inplace=True) # d1 reference.insert(0, instructions.Delay(5, d1), inplace=True) self.assertEqual(flattened, reference) self.assertNotEqual(grouped, reference) class _TestDirective(directives.Directive): """Pulse ``RelativeBarrier`` directive.""" def __init__(self, *channels): """Test directive""" super().__init__(operands=tuple(channels)) @property def channels(self): return self.operands class TestRemoveDirectives(QiskitTestCase): """Test removing of directives.""" def test_remove_directives(self): """Test that all directives are removed.""" d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) schedule = pulse.Schedule() schedule += _TestDirective(d0, d1) schedule += instructions.Delay(3, d0) schedule += _TestDirective(d0, d1) schedule = transforms.remove_directives(schedule) reference = pulse.Schedule() # d0 reference += instructions.Delay(3, d0) self.assertEqual(schedule, reference) class TestRemoveTrivialBarriers(QiskitTestCase): """Test scheduling transforms.""" def test_remove_trivial_barriers(self): """Test that trivial barriers are properly removed.""" schedule = pulse.Schedule() schedule += directives.RelativeBarrier() schedule += directives.RelativeBarrier(pulse.DriveChannel(0)) schedule += directives.RelativeBarrier(pulse.DriveChannel(0), pulse.DriveChannel(1)) schedule = transforms.remove_trivial_barriers(schedule) reference = pulse.Schedule() reference += directives.RelativeBarrier(pulse.DriveChannel(0), pulse.DriveChannel(1)) self.assertEqual(schedule, reference) class TestRemoveSubroutines(QiskitTestCase): """Test removing of subroutines.""" def test_remove_subroutines(self): """Test that nested subroutiens are removed.""" d0 = pulse.DriveChannel(0) nested_routine = pulse.Schedule() nested_routine.insert(10, pulse.Delay(10, d0), inplace=True) subroutine = pulse.Schedule() subroutine.insert(0, pulse.Delay(20, d0), inplace=True) with self.assertWarns(DeprecationWarning): subroutine.insert(20, pulse.instructions.Call(nested_routine), inplace=True) subroutine.insert(50, pulse.Delay(10, d0), inplace=True) main_program = pulse.Schedule() main_program.insert(0, pulse.Delay(10, d0), inplace=True) with self.assertWarns(DeprecationWarning): main_program.insert(30, pulse.instructions.Call(subroutine), inplace=True) target = transforms.inline_subroutines(main_program) reference = pulse.Schedule() reference.insert(0, pulse.Delay(10, d0), inplace=True) reference.insert(30, pulse.Delay(20, d0), inplace=True) reference.insert(60, pulse.Delay(10, d0), inplace=True) reference.insert(80, pulse.Delay(10, d0), inplace=True) self.assertEqual(target, reference) def test_call_in_nested_schedule(self): """Test that subroutines in nested schedule.""" d0 = pulse.DriveChannel(0) subroutine = pulse.Schedule() subroutine.insert(10, pulse.Delay(10, d0), inplace=True) nested_sched = pulse.Schedule() with self.assertWarns(DeprecationWarning): nested_sched.insert(0, pulse.instructions.Call(subroutine), inplace=True) main_sched = pulse.Schedule() main_sched.insert(0, nested_sched, inplace=True) target = transforms.inline_subroutines(main_sched) # no call instruction reference_nested = pulse.Schedule() reference_nested.insert(0, subroutine, inplace=True) reference = pulse.Schedule() reference.insert(0, reference_nested, inplace=True) self.assertEqual(target, reference) def test_call_in_nested_block(self): """Test that subroutines in nested schedule.""" d0 = pulse.DriveChannel(0) subroutine = pulse.ScheduleBlock() subroutine.append(pulse.Delay(10, d0), inplace=True) nested_block = pulse.ScheduleBlock() with self.assertWarns(DeprecationWarning): nested_block.append(pulse.instructions.Call(subroutine), inplace=True) main_block = pulse.ScheduleBlock() main_block.append(nested_block, inplace=True) target = transforms.inline_subroutines(main_block) # no call instruction reference_nested = pulse.ScheduleBlock() reference_nested.append(subroutine, inplace=True) reference = pulse.ScheduleBlock() reference.append(reference_nested, inplace=True) self.assertEqual(target, reference) if __name__ == "__main__": unittest.main()
https://github.com/swe-train/qiskit__qiskit
swe-train
# 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. """These tests are the examples given in the arXiv paper describing OpenQASM 2. Specifically, there is a test for each subsection (except the description of 'qelib1.inc') in section 3 of https://arxiv.org/abs/1707.03429v2. The examples are copy/pasted from the source files there.""" # pylint: disable=missing-module-docstring,missing-class-docstring,missing-function-docstring import math import os import tempfile import ddt from qiskit import qasm2 from qiskit.circuit import QuantumCircuit, QuantumRegister, ClassicalRegister, Qubit from qiskit.circuit.library import U1Gate, U3Gate, CU1Gate from qiskit.test import QiskitTestCase from . import gate_builder def load(string, *args, **kwargs): # We're deliberately not using the context-manager form here because we need to use it in a # slightly odd pattern. # pylint: disable=consider-using-with temp = tempfile.NamedTemporaryFile(mode="w", delete=False) try: temp.write(string) # NamedTemporaryFile claims not to be openable a second time on Windows, so close it # (without deletion) so Rust can open it again. temp.close() return qasm2.load(temp.name, *args, **kwargs) finally: # Now actually clean up after ourselves. os.unlink(temp.name) @ddt.ddt class TestArxivExamples(QiskitTestCase): @ddt.data(qasm2.loads, load) def test_teleportation(self, parser): example = """\ // quantum teleportation example OPENQASM 2.0; include "qelib1.inc"; qreg q[3]; creg c0[1]; creg c1[1]; creg c2[1]; // optional post-rotation for state tomography gate post q { } u3(0.3,0.2,0.1) q[0]; h q[1]; cx q[1],q[2]; barrier q; cx q[0],q[1]; h q[0]; measure q[0] -> c0[0]; measure q[1] -> c1[0]; if(c0==1) z q[2]; if(c1==1) x q[2]; post q[2]; measure q[2] -> c2[0];""" parsed = parser(example) post = gate_builder("post", [], QuantumCircuit([Qubit()])) q = QuantumRegister(3, "q") c0 = ClassicalRegister(1, "c0") c1 = ClassicalRegister(1, "c1") c2 = ClassicalRegister(1, "c2") qc = QuantumCircuit(q, c0, c1, c2) qc.append(U3Gate(0.3, 0.2, 0.1), [q[0]], []) qc.h(q[1]) qc.cx(q[1], q[2]) qc.barrier(q) qc.cx(q[0], q[1]) qc.h(q[0]) qc.measure(q[0], c0[0]) qc.measure(q[1], c1[0]) qc.z(q[2]).c_if(c0, 1) qc.x(q[2]).c_if(c1, 1) qc.append(post(), [q[2]], []) qc.measure(q[2], c2[0]) self.assertEqual(parsed, qc) @ddt.data(qasm2.loads, load) def test_qft(self, parser): example = """\ // quantum Fourier transform OPENQASM 2.0; include "qelib1.inc"; qreg q[4]; creg c[4]; x q[0]; x q[2]; barrier q; h q[0]; cu1(pi/2) q[1],q[0]; h q[1]; cu1(pi/4) q[2],q[0]; cu1(pi/2) q[2],q[1]; h q[2]; cu1(pi/8) q[3],q[0]; cu1(pi/4) q[3],q[1]; cu1(pi/2) q[3],q[2]; h q[3]; measure q -> c;""" parsed = parser(example) qc = QuantumCircuit(QuantumRegister(4, "q"), ClassicalRegister(4, "c")) qc.x(0) qc.x(2) qc.barrier(range(4)) qc.h(0) qc.append(CU1Gate(math.pi / 2), [1, 0]) qc.h(1) qc.append(CU1Gate(math.pi / 4), [2, 0]) qc.append(CU1Gate(math.pi / 2), [2, 1]) qc.h(2) qc.append(CU1Gate(math.pi / 8), [3, 0]) qc.append(CU1Gate(math.pi / 4), [3, 1]) qc.append(CU1Gate(math.pi / 2), [3, 2]) qc.h(3) qc.measure(range(4), range(4)) self.assertEqual(parsed, qc) @ddt.data(qasm2.loads, load) def test_inverse_qft_1(self, parser): example = """\ // QFT and measure, version 1 OPENQASM 2.0; include "qelib1.inc"; qreg q[4]; creg c[4]; h q; barrier q; h q[0]; measure q[0] -> c[0]; if(c==1) u1(pi/2) q[1]; h q[1]; measure q[1] -> c[1]; if(c==1) u1(pi/4) q[2]; if(c==2) u1(pi/2) q[2]; if(c==3) u1(pi/2+pi/4) q[2]; h q[2]; measure q[2] -> c[2]; if(c==1) u1(pi/8) q[3]; if(c==2) u1(pi/4) q[3]; if(c==3) u1(pi/4+pi/8) q[3]; if(c==4) u1(pi/2) q[3]; if(c==5) u1(pi/2+pi/8) q[3]; if(c==6) u1(pi/2+pi/4) q[3]; if(c==7) u1(pi/2+pi/4+pi/8) q[3]; h q[3]; measure q[3] -> c[3];""" parsed = parser(example) q = QuantumRegister(4, "q") c = ClassicalRegister(4, "c") qc = QuantumCircuit(q, c) qc.h(q) qc.barrier(q) qc.h(q[0]) qc.measure(q[0], c[0]) qc.append(U1Gate(math.pi / 2).c_if(c, 1), [q[1]]) qc.h(q[1]) qc.measure(q[1], c[1]) qc.append(U1Gate(math.pi / 4).c_if(c, 1), [q[2]]) qc.append(U1Gate(math.pi / 2).c_if(c, 2), [q[2]]) qc.append(U1Gate(math.pi / 4 + math.pi / 2).c_if(c, 3), [q[2]]) qc.h(q[2]) qc.measure(q[2], c[2]) qc.append(U1Gate(math.pi / 8).c_if(c, 1), [q[3]]) qc.append(U1Gate(math.pi / 4).c_if(c, 2), [q[3]]) qc.append(U1Gate(math.pi / 8 + math.pi / 4).c_if(c, 3), [q[3]]) qc.append(U1Gate(math.pi / 2).c_if(c, 4), [q[3]]) qc.append(U1Gate(math.pi / 8 + math.pi / 2).c_if(c, 5), [q[3]]) qc.append(U1Gate(math.pi / 4 + math.pi / 2).c_if(c, 6), [q[3]]) qc.append(U1Gate(math.pi / 8 + math.pi / 4 + math.pi / 2).c_if(c, 7), [q[3]]) qc.h(q[3]) qc.measure(q[3], c[3]) self.assertEqual(parsed, qc) @ddt.data(qasm2.loads, load) def test_inverse_qft_2(self, parser): example = """\ // QFT and measure, version 2 OPENQASM 2.0; include "qelib1.inc"; qreg q[4]; creg c0[1]; creg c1[1]; creg c2[1]; creg c3[1]; h q; barrier q; h q[0]; measure q[0] -> c0[0]; if(c0==1) u1(pi/2) q[1]; h q[1]; measure q[1] -> c1[0]; if(c0==1) u1(pi/4) q[2]; if(c1==1) u1(pi/2) q[2]; h q[2]; measure q[2] -> c2[0]; if(c0==1) u1(pi/8) q[3]; if(c1==1) u1(pi/4) q[3]; if(c2==1) u1(pi/2) q[3]; h q[3]; measure q[3] -> c3[0];""" parsed = parser(example) q = QuantumRegister(4, "q") c0 = ClassicalRegister(1, "c0") c1 = ClassicalRegister(1, "c1") c2 = ClassicalRegister(1, "c2") c3 = ClassicalRegister(1, "c3") qc = QuantumCircuit(q, c0, c1, c2, c3) qc.h(q) qc.barrier(q) qc.h(q[0]) qc.measure(q[0], c0[0]) qc.append(U1Gate(math.pi / 2).c_if(c0, 1), [q[1]]) qc.h(q[1]) qc.measure(q[1], c1[0]) qc.append(U1Gate(math.pi / 4).c_if(c0, 1), [q[2]]) qc.append(U1Gate(math.pi / 2).c_if(c1, 1), [q[2]]) qc.h(q[2]) qc.measure(q[2], c2[0]) qc.append(U1Gate(math.pi / 8).c_if(c0, 1), [q[3]]) qc.append(U1Gate(math.pi / 4).c_if(c1, 1), [q[3]]) qc.append(U1Gate(math.pi / 2).c_if(c2, 1), [q[3]]) qc.h(q[3]) qc.measure(q[3], c3[0]) self.assertEqual(parsed, qc) @ddt.data(qasm2.loads, load) def test_ripple_carry_adder(self, parser): example = """\ // quantum ripple-carry adder from Cuccaro et al, quant-ph/0410184 OPENQASM 2.0; include "qelib1.inc"; gate majority a,b,c { cx c,b; cx c,a; ccx a,b,c; } gate unmaj a,b,c { ccx a,b,c; cx c,a; cx a,b; } qreg cin[1]; qreg a[4]; qreg b[4]; qreg cout[1]; creg ans[5]; // set input states x a[0]; // a = 0001 x b; // b = 1111 // add a to b, storing result in b majority cin[0],b[0],a[0]; majority a[0],b[1],a[1]; majority a[1],b[2],a[2]; majority a[2],b[3],a[3]; cx a[3],cout[0]; unmaj a[2],b[3],a[3]; unmaj a[1],b[2],a[2]; unmaj a[0],b[1],a[1]; unmaj cin[0],b[0],a[0]; measure b[0] -> ans[0]; measure b[1] -> ans[1]; measure b[2] -> ans[2]; measure b[3] -> ans[3]; measure cout[0] -> ans[4];""" parsed = parser(example) majority_definition = QuantumCircuit([Qubit(), Qubit(), Qubit()]) majority_definition.cx(2, 1) majority_definition.cx(2, 0) majority_definition.ccx(0, 1, 2) majority = gate_builder("majority", [], majority_definition) unmaj_definition = QuantumCircuit([Qubit(), Qubit(), Qubit()]) unmaj_definition.ccx(0, 1, 2) unmaj_definition.cx(2, 0) unmaj_definition.cx(0, 1) unmaj = gate_builder("unmaj", [], unmaj_definition) cin = QuantumRegister(1, "cin") a = QuantumRegister(4, "a") b = QuantumRegister(4, "b") cout = QuantumRegister(1, "cout") ans = ClassicalRegister(5, "ans") qc = QuantumCircuit(cin, a, b, cout, ans) qc.x(a[0]) qc.x(b) qc.append(majority(), [cin[0], b[0], a[0]]) qc.append(majority(), [a[0], b[1], a[1]]) qc.append(majority(), [a[1], b[2], a[2]]) qc.append(majority(), [a[2], b[3], a[3]]) qc.cx(a[3], cout[0]) qc.append(unmaj(), [a[2], b[3], a[3]]) qc.append(unmaj(), [a[1], b[2], a[2]]) qc.append(unmaj(), [a[0], b[1], a[1]]) qc.append(unmaj(), [cin[0], b[0], a[0]]) qc.measure(b, ans[:4]) qc.measure(cout[0], ans[4]) self.assertEqual(parsed, qc) @ddt.data(qasm2.loads, load) def test_randomised_benchmarking(self, parser): example = """\ // One randomized benchmarking sequence OPENQASM 2.0; include "qelib1.inc"; qreg q[2]; creg c[2]; h q[0]; barrier q; cz q[0],q[1]; barrier q; s q[0]; cz q[0],q[1]; barrier q; s q[0]; z q[0]; h q[0]; barrier q; measure q -> c; """ parsed = parser(example) q = QuantumRegister(2, "q") c = ClassicalRegister(2, "c") qc = QuantumCircuit(q, c) qc.h(q[0]) qc.barrier(q) qc.cz(q[0], q[1]) qc.barrier(q) qc.s(q[0]) qc.cz(q[0], q[1]) qc.barrier(q) qc.s(q[0]) qc.z(q[0]) qc.h(q[0]) qc.barrier(q) qc.measure(q, c) self.assertEqual(parsed, qc) @ddt.data(qasm2.loads, load) def test_process_tomography(self, parser): example = """\ OPENQASM 2.0; include "qelib1.inc"; gate pre q { } // pre-rotation gate post q { } // post-rotation qreg q[1]; creg c[1]; pre q[0]; barrier q; h q[0]; barrier q; post q[0]; measure q[0] -> c[0];""" parsed = parser(example) pre = gate_builder("pre", [], QuantumCircuit([Qubit()])) post = gate_builder("post", [], QuantumCircuit([Qubit()])) qc = QuantumCircuit(QuantumRegister(1, "q"), ClassicalRegister(1, "c")) qc.append(pre(), [0]) qc.barrier(qc.qubits) qc.h(0) qc.barrier(qc.qubits) qc.append(post(), [0]) qc.measure(0, 0) self.assertEqual(parsed, qc) @ddt.data(qasm2.loads, load) def test_error_correction(self, parser): example = """\ // Repetition code syndrome measurement OPENQASM 2.0; include "qelib1.inc"; qreg q[3]; qreg a[2]; creg c[3]; creg syn[2]; gate syndrome d1,d2,d3,a1,a2 { cx d1,a1; cx d2,a1; cx d2,a2; cx d3,a2; } x q[0]; // error barrier q; syndrome q[0],q[1],q[2],a[0],a[1]; measure a -> syn; if(syn==1) x q[0]; if(syn==2) x q[2]; if(syn==3) x q[1]; measure q -> c;""" parsed = parser(example) syndrome_definition = QuantumCircuit([Qubit() for _ in [None] * 5]) syndrome_definition.cx(0, 3) syndrome_definition.cx(1, 3) syndrome_definition.cx(1, 4) syndrome_definition.cx(2, 4) syndrome = gate_builder("syndrome", [], syndrome_definition) q = QuantumRegister(3, "q") a = QuantumRegister(2, "a") c = ClassicalRegister(3, "c") syn = ClassicalRegister(2, "syn") qc = QuantumCircuit(q, a, c, syn) qc.x(q[0]) qc.barrier(q) qc.append(syndrome(), [q[0], q[1], q[2], a[0], a[1]]) qc.measure(a, syn) qc.x(q[0]).c_if(syn, 1) qc.x(q[2]).c_if(syn, 2) qc.x(q[1]).c_if(syn, 3) qc.measure(q, c) self.assertEqual(parsed, qc)
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test cases for the circuit qasm_file and qasm_string method.""" import os from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.circuit import Gate, Parameter from qiskit.exceptions import QiskitError from qiskit.test import QiskitTestCase from qiskit.transpiler.passes import Unroller from qiskit.converters.circuit_to_dag import circuit_to_dag class LoadFromQasmTest(QiskitTestCase): """Test circuit.from_qasm_* set of methods.""" def setUp(self): super().setUp() self.qasm_file_name = "entangled_registers.qasm" self.qasm_dir = os.path.join( os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "qasm" ) self.qasm_file_path = os.path.join(self.qasm_dir, self.qasm_file_name) def test_qasm_file(self): """ Test qasm_file and get_circuit. If all is correct we should get the qasm file loaded in _qasm_file_path """ q_circuit = QuantumCircuit.from_qasm_file(self.qasm_file_path) qr_a = QuantumRegister(4, "a") qr_b = QuantumRegister(4, "b") cr_c = ClassicalRegister(4, "c") cr_d = ClassicalRegister(4, "d") q_circuit_2 = QuantumCircuit(qr_a, qr_b, cr_c, cr_d) q_circuit_2.h(qr_a) q_circuit_2.cx(qr_a, qr_b) q_circuit_2.barrier(qr_a) q_circuit_2.barrier(qr_b) q_circuit_2.measure(qr_a, cr_c) q_circuit_2.measure(qr_b, cr_d) self.assertEqual(q_circuit, q_circuit_2) def test_loading_all_qelib1_gates(self): """Test setting up a circuit with all gates defined in qiskit/qasm/libs/qelib1.inc.""" from qiskit.circuit.library import U1Gate, U2Gate, U3Gate, CU1Gate, CU3Gate, UGate all_gates_qasm = os.path.join(self.qasm_dir, "all_gates.qasm") qasm_circuit = QuantumCircuit.from_qasm_file(all_gates_qasm) ref_circuit = QuantumCircuit(3, 3) # abstract gates (legacy) ref_circuit.append(UGate(0.2, 0.1, 0.6), [0]) ref_circuit.cx(0, 1) # the hardware primitives ref_circuit.append(U3Gate(0.2, 0.1, 0.6), [0]) ref_circuit.append(U2Gate(0.1, 0.6), [0]) ref_circuit.append(U1Gate(0.6), [0]) ref_circuit.id(0) ref_circuit.cx(0, 1) # the standard single qubit gates ref_circuit.u(0.2, 0.1, 0.6, 0) ref_circuit.p(0.6, 0) ref_circuit.x(0) ref_circuit.y(0) ref_circuit.z(0) ref_circuit.h(0) ref_circuit.s(0) ref_circuit.t(0) ref_circuit.sdg(0) ref_circuit.tdg(0) ref_circuit.sx(0) ref_circuit.sxdg(0) # the standard rotations ref_circuit.rx(0.1, 0) ref_circuit.ry(0.1, 0) ref_circuit.rz(0.1, 0) # the barrier ref_circuit.barrier() # the standard user-defined gates ref_circuit.swap(0, 1) ref_circuit.cswap(0, 1, 2) ref_circuit.cy(0, 1) ref_circuit.cz(0, 1) ref_circuit.ch(0, 1) ref_circuit.csx(0, 1) ref_circuit.append(CU1Gate(0.6), [0, 1]) ref_circuit.append(CU3Gate(0.2, 0.1, 0.6), [0, 1]) ref_circuit.cp(0.6, 0, 1) ref_circuit.cu(0.2, 0.1, 0.6, 0, 0, 1) ref_circuit.ccx(0, 1, 2) ref_circuit.crx(0.6, 0, 1) ref_circuit.cry(0.6, 0, 1) ref_circuit.crz(0.6, 0, 1) ref_circuit.rxx(0.2, 0, 1) ref_circuit.rzz(0.2, 0, 1) ref_circuit.measure([0, 1, 2], [0, 1, 2]) self.assertEqual(qasm_circuit, ref_circuit) def test_fail_qasm_file(self): """ Test fail_qasm_file. If all is correct we should get a QiskitError """ self.assertRaises(QiskitError, QuantumCircuit.from_qasm_file, "") def test_qasm_text(self): """ Test qasm_text and get_circuit. If all is correct we should get the qasm file loaded from the string """ qasm_string = "// A simple 8 qubit example\nOPENQASM 2.0;\n" qasm_string += 'include "qelib1.inc";\nqreg a[4];\n' qasm_string += "qreg b[4];\ncreg c[4];\ncreg d[4];\nh a;\ncx a, b;\n" qasm_string += "barrier a;\nbarrier b;\nmeasure a[0]->c[0];\n" qasm_string += "measure a[1]->c[1];\nmeasure a[2]->c[2];\n" qasm_string += "measure a[3]->c[3];\nmeasure b[0]->d[0];\n" qasm_string += "measure b[1]->d[1];\nmeasure b[2]->d[2];\n" qasm_string += "measure b[3]->d[3];" q_circuit = QuantumCircuit.from_qasm_str(qasm_string) qr_a = QuantumRegister(4, "a") qr_b = QuantumRegister(4, "b") cr_c = ClassicalRegister(4, "c") cr_d = ClassicalRegister(4, "d") ref = QuantumCircuit(qr_a, qr_b, cr_c, cr_d) ref.h(qr_a[3]) ref.cx(qr_a[3], qr_b[3]) ref.h(qr_a[2]) ref.cx(qr_a[2], qr_b[2]) ref.h(qr_a[1]) ref.cx(qr_a[1], qr_b[1]) ref.h(qr_a[0]) ref.cx(qr_a[0], qr_b[0]) ref.barrier(qr_b) ref.measure(qr_b, cr_d) ref.barrier(qr_a) ref.measure(qr_a, cr_c) self.assertEqual(len(q_circuit.cregs), 2) self.assertEqual(len(q_circuit.qregs), 2) self.assertEqual(q_circuit, ref) def test_qasm_text_conditional(self): """ Test qasm_text and get_circuit when conditionals are present. """ qasm_string = ( "\n".join( [ "OPENQASM 2.0;", 'include "qelib1.inc";', "qreg q[1];", "creg c0[4];", "creg c1[4];", "x q[0];", "if(c1==4) x q[0];", ] ) + "\n" ) q_circuit = QuantumCircuit.from_qasm_str(qasm_string) qr = QuantumRegister(1, "q") cr0 = ClassicalRegister(4, "c0") cr1 = ClassicalRegister(4, "c1") ref = QuantumCircuit(qr, cr0, cr1) ref.x(qr[0]) ref.x(qr[0]).c_if(cr1, 4) self.assertEqual(len(q_circuit.cregs), 2) self.assertEqual(len(q_circuit.qregs), 1) self.assertEqual(q_circuit, ref) def test_opaque_gate(self): """ Test parse an opaque gate See https://github.com/Qiskit/qiskit-terra/issues/1566. """ qasm_string = ( "\n".join( [ "OPENQASM 2.0;", 'include "qelib1.inc";', "opaque my_gate(theta,phi,lambda) a,b;", "qreg q[3];", "my_gate(1,2,3) q[1],q[2];", ] ) + "\n" ) circuit = QuantumCircuit.from_qasm_str(qasm_string) qr = QuantumRegister(3, "q") expected = QuantumCircuit(qr) expected.append(Gate(name="my_gate", num_qubits=2, params=[1, 2, 3]), [qr[1], qr[2]]) self.assertEqual(circuit, expected) def test_qasm_example_file(self): """Loads qasm/example.qasm.""" qasm_filename = os.path.join(self.qasm_dir, "example.qasm") expected_circuit = QuantumCircuit.from_qasm_str( "\n".join( [ "OPENQASM 2.0;", 'include "qelib1.inc";', "qreg q[3];", "qreg r[3];", "creg c[3];", "creg d[3];", "h q[2];", "cx q[2],r[2];", "measure r[2] -> d[2];", "h q[1];", "cx q[1],r[1];", "measure r[1] -> d[1];", "h q[0];", "cx q[0],r[0];", "measure r[0] -> d[0];", "barrier q[0],q[1],q[2];", "measure q[2] -> c[2];", "measure q[1] -> c[1];", "measure q[0] -> c[0];", ] ) + "\n" ) q_circuit = QuantumCircuit.from_qasm_file(qasm_filename) self.assertEqual(q_circuit, expected_circuit) self.assertEqual(len(q_circuit.cregs), 2) self.assertEqual(len(q_circuit.qregs), 2) def test_qasm_qas_string_order(self): """Test that gates are returned in qasm in ascending order.""" expected_qasm = ( "\n".join( [ "OPENQASM 2.0;", 'include "qelib1.inc";', "qreg q[3];", "h q[0];", "h q[1];", "h q[2];", ] ) + "\n" ) qasm_string = """OPENQASM 2.0; include "qelib1.inc"; qreg q[3]; h q;""" q_circuit = QuantumCircuit.from_qasm_str(qasm_string) self.assertEqual(q_circuit.qasm(), expected_qasm) def test_from_qasm_str_custom_gate1(self): """Test load custom gates (simple case)""" qasm_string = """OPENQASM 2.0; include "qelib1.inc"; gate rinv q {sdg q; h q; sdg q; h q; } qreg qr[1]; rinv qr[0];""" circuit = QuantumCircuit.from_qasm_str(qasm_string) rinv_q = QuantumRegister(1, name="q") rinv_gate = QuantumCircuit(rinv_q, name="rinv") rinv_gate.sdg(rinv_q) rinv_gate.h(rinv_q) rinv_gate.sdg(rinv_q) rinv_gate.h(rinv_q) rinv = rinv_gate.to_instruction() qr = QuantumRegister(1, name="qr") expected = QuantumCircuit(qr, name="circuit") expected.append(rinv, [qr[0]]) self.assertEqualUnroll(["sdg", "h"], circuit, expected) def test_from_qasm_str_custom_gate2(self): """Test load custom gates (no so simple case, different bit order) See: https://github.com/Qiskit/qiskit-terra/pull/3393#issuecomment-551307250 """ qasm_string = """OPENQASM 2.0; include "qelib1.inc"; gate swap2 a,b { cx a,b; cx b,a; // different bit order cx a,b; } qreg qr[3]; swap2 qr[0], qr[1]; swap2 qr[1], qr[2];""" circuit = QuantumCircuit.from_qasm_str(qasm_string) ab_args = QuantumRegister(2, name="ab") swap_gate = QuantumCircuit(ab_args, name="swap2") swap_gate.cx(ab_args[0], ab_args[1]) swap_gate.cx(ab_args[1], ab_args[0]) swap_gate.cx(ab_args[0], ab_args[1]) swap = swap_gate.to_instruction() qr = QuantumRegister(3, name="qr") expected = QuantumCircuit(qr, name="circuit") expected.append(swap, [qr[0], qr[1]]) expected.append(swap, [qr[1], qr[2]]) self.assertEqualUnroll(["cx"], expected, circuit) def test_from_qasm_str_custom_gate3(self): """Test load custom gates (no so simple case, different bit count) See: https://github.com/Qiskit/qiskit-terra/pull/3393#issuecomment-551307250 """ qasm_string = """OPENQASM 2.0; include "qelib1.inc"; gate cswap2 a,b,c { cx c,b; // different bit count ccx a,b,c; //previously defined gate cx c,b; } qreg qr[3]; cswap2 qr[1], qr[0], qr[2];""" circuit = QuantumCircuit.from_qasm_str(qasm_string) abc_args = QuantumRegister(3, name="abc") cswap_gate = QuantumCircuit(abc_args, name="cswap2") cswap_gate.cx(abc_args[2], abc_args[1]) cswap_gate.ccx(abc_args[0], abc_args[1], abc_args[2]) cswap_gate.cx(abc_args[2], abc_args[1]) cswap = cswap_gate.to_instruction() qr = QuantumRegister(3, name="qr") expected = QuantumCircuit(qr, name="circuit") expected.append(cswap, [qr[1], qr[0], qr[2]]) self.assertEqualUnroll(["cx", "h", "tdg", "t"], circuit, expected) def test_from_qasm_str_custom_gate4(self): """Test load custom gates (parameterized) See: https://github.com/Qiskit/qiskit-terra/pull/3393#issuecomment-551307250 """ qasm_string = """OPENQASM 2.0; include "qelib1.inc"; gate my_gate(phi,lambda) q {u(1.5707963267948966,phi,lambda) q;} qreg qr[1]; my_gate(pi, pi) qr[0];""" circuit = QuantumCircuit.from_qasm_str(qasm_string) my_gate_circuit = QuantumCircuit(1, name="my_gate") phi = Parameter("phi") lam = Parameter("lambda") my_gate_circuit.u(1.5707963267948966, phi, lam, 0) my_gate = my_gate_circuit.to_gate() qr = QuantumRegister(1, name="qr") expected = QuantumCircuit(qr, name="circuit") expected.append(my_gate, [qr[0]]) expected = expected.bind_parameters({phi: 3.141592653589793, lam: 3.141592653589793}) self.assertEqualUnroll("u", circuit, expected) def test_from_qasm_str_custom_gate5(self): """Test load custom gates (parameterized, with biop and constant) See: https://github.com/Qiskit/qiskit-terra/pull/3393#issuecomment-551307250 """ qasm_string = """OPENQASM 2.0; include "qelib1.inc"; gate my_gate(phi,lambda) q {u(pi/2,phi,lambda) q;} // biop with pi qreg qr[1]; my_gate(pi, pi) qr[0];""" circuit = QuantumCircuit.from_qasm_str(qasm_string) my_gate_circuit = QuantumCircuit(1, name="my_gate") phi = Parameter("phi") lam = Parameter("lambda") my_gate_circuit.u(1.5707963267948966, phi, lam, 0) my_gate = my_gate_circuit.to_gate() qr = QuantumRegister(1, name="qr") expected = QuantumCircuit(qr, name="circuit") expected.append(my_gate, [qr[0]]) expected = expected.bind_parameters({phi: 3.141592653589793, lam: 3.141592653589793}) self.assertEqualUnroll("u", circuit, expected) def test_from_qasm_str_custom_gate6(self): """Test load custom gates (parameters used in expressions) See: https://github.com/Qiskit/qiskit-terra/pull/3393#issuecomment-591668924 """ qasm_string = """OPENQASM 2.0; include "qelib1.inc"; gate my_gate(phi,lambda) q {rx(phi+pi) q; ry(lambda/2) q;} // parameters used in expressions qreg qr[1]; my_gate(pi, pi) qr[0];""" circuit = QuantumCircuit.from_qasm_str(qasm_string) my_gate_circuit = QuantumCircuit(1, name="my_gate") phi = Parameter("phi") lam = Parameter("lambda") my_gate_circuit.rx(phi + 3.141592653589793, 0) my_gate_circuit.ry(lam / 2, 0) my_gate = my_gate_circuit.to_gate() qr = QuantumRegister(1, name="qr") expected = QuantumCircuit(qr, name="circuit") expected.append(my_gate, [qr[0]]) expected = expected.bind_parameters({phi: 3.141592653589793, lam: 3.141592653589793}) self.assertEqualUnroll(["rx", "ry"], circuit, expected) def test_from_qasm_str_custom_gate7(self): """Test load custom gates (build in functions) See: https://github.com/Qiskit/qiskit-terra/pull/3393#issuecomment-592208951 """ qasm_string = """OPENQASM 2.0; include "qelib1.inc"; gate my_gate(phi,lambda) q {u(asin(cos(phi)/2), phi+pi, lambda/2) q;} // build func qreg qr[1]; my_gate(pi, pi) qr[0];""" circuit = QuantumCircuit.from_qasm_str(qasm_string) qr = QuantumRegister(1, name="qr") expected = QuantumCircuit(qr, name="circuit") expected.u(-0.5235987755982988, 6.283185307179586, 1.5707963267948966, qr[0]) self.assertEqualUnroll("u", circuit, expected) def test_from_qasm_str_nested_custom_gate(self): """Test chain of custom gates See: https://github.com/Qiskit/qiskit-terra/pull/3393#issuecomment-592261942 """ qasm_string = """OPENQASM 2.0; include "qelib1.inc"; gate my_other_gate(phi,lambda) q {u(asin(cos(phi)/2), phi+pi, lambda/2) q;} gate my_gate(phi) r {my_other_gate(phi, phi+pi) r;} qreg qr[1]; my_gate(pi) qr[0];""" circuit = QuantumCircuit.from_qasm_str(qasm_string) qr = QuantumRegister(1, name="qr") expected = QuantumCircuit(qr, name="circuit") expected.u(-0.5235987755982988, 6.283185307179586, 3.141592653589793, qr[0]) self.assertEqualUnroll("u", circuit, expected) def test_from_qasm_str_delay(self): """Test delay instruction/opaque-gate See: https://github.com/Qiskit/qiskit-terra/issues/6510 """ qasm_string = """OPENQASM 2.0; include "qelib1.inc"; opaque delay(time) q; qreg q[1]; delay(172) q[0];""" circuit = QuantumCircuit.from_qasm_str(qasm_string) qr = QuantumRegister(1, name="q") expected = QuantumCircuit(qr, name="circuit") expected.delay(172, qr[0]) self.assertEqualUnroll("u", circuit, expected) def test_definition_with_u_cx(self): """Test that gate-definition bodies can use U and CX.""" qasm_string = """ OPENQASM 2.0; gate bell q0, q1 { U(pi/2, 0, pi) q0; CX q0, q1; } qreg q[2]; bell q[0], q[1]; """ circuit = QuantumCircuit.from_qasm_str(qasm_string) qr = QuantumRegister(2, "q") expected = QuantumCircuit(qr) expected.h(0) expected.cx(0, 1) self.assertEqualUnroll(["u", "cx"], circuit, expected) def assertEqualUnroll(self, basis, circuit, expected): """Compares the dags after unrolling to basis""" circuit_dag = circuit_to_dag(circuit) expected_dag = circuit_to_dag(expected) circuit_result = Unroller(basis).run(circuit_dag) expected_result = Unroller(basis).run(expected_dag) self.assertEqual(circuit_result, expected_result)
https://github.com/swe-train/qiskit__qiskit
swe-train
# 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. """Test QASM3 exporter.""" # We can't really help how long the lines output by the exporter are in some cases. # pylint: disable=line-too-long from io import StringIO from math import pi import re import unittest from ddt import ddt, data from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, transpile from qiskit.circuit import Parameter, Qubit, Clbit, Instruction, Gate, Delay, Barrier from qiskit.circuit.classical import expr from qiskit.circuit.controlflow import CASE_DEFAULT from qiskit.test import QiskitTestCase from qiskit.qasm3 import Exporter, dumps, dump, QASM3ExporterError, ExperimentalFeatures from qiskit.qasm3.exporter import QASM3Builder from qiskit.qasm3.printer import BasicPrinter # Tests marked with this decorator should be restored after gate definition with parameters is fixed # properly, and the dummy tests after them should be deleted. See gh-7335. requires_fixed_parameterisation = unittest.expectedFailure class TestQASM3Functions(QiskitTestCase): """QASM3 module - high level functions""" def setUp(self): self.circuit = QuantumCircuit(2) self.circuit.u(2 * pi, 3 * pi, -5 * pi, 0) self.expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "qubit[2] q;", "U(2*pi, 3*pi, -5*pi) q[0];", "", ] ) super().setUp() def test_dumps(self): """Test dumps.""" result = dumps(self.circuit) self.assertEqual(result, self.expected_qasm) def test_dump(self): """Test dump into an IO stream.""" io = StringIO() dump(self.circuit, io) result = io.getvalue() self.assertEqual(result, self.expected_qasm) @ddt class TestCircuitQASM3(QiskitTestCase): """QASM3 exporter.""" maxDiff = 1_000_000 @classmethod def setUpClass(cls): # These regexes are not perfect by any means, but sufficient for simple tests on controlled # input circuits. They can allow false negatives (in which case, update the regex), but to # be useful for the tests must _never_ have false positive matches. We use an explicit # space (`\s`) or semicolon rather than the end-of-word `\b` because we want to ensure that # the exporter isn't putting out invalid characters as part of the identifiers. cls.register_regex = re.compile( r"^\s*(let|(qu)?bit(\[\d+\])?)\s+(?P<name>\w+)[\s;]", re.U | re.M ) scalar_type_names = { "angle", "duration", "float", "int", "stretch", "uint", } cls.scalar_parameter_regex = re.compile( r"^\s*((input|output|const)\s+)?" # Modifier rf"({'|'.join(scalar_type_names)})\s*(\[[^\]]+\])?\s+" # Type name and designator r"(?P<name>\w+)[\s;]", # Parameter name re.U | re.M, ) super().setUpClass() def test_regs_conds_qasm(self): """Test with registers and conditionals.""" qr1 = QuantumRegister(1, "qr1") qr2 = QuantumRegister(2, "qr2") cr = ClassicalRegister(3, "cr") qc = QuantumCircuit(qr1, qr2, cr) qc.measure(qr1[0], cr[0]) qc.measure(qr2[0], cr[1]) qc.measure(qr2[1], cr[2]) qc.x(qr2[1]).c_if(cr, 0) qc.y(qr1[0]).c_if(cr, 1) qc.z(qr1[0]).c_if(cr, 2) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "bit[3] cr;", "qubit[1] qr1;", "qubit[2] qr2;", "cr[0] = measure qr1[0];", "cr[1] = measure qr2[0];", "cr[2] = measure qr2[1];", "if (cr == 0) {", " x qr2[1];", "}", "if (cr == 1) {", " y qr1[0];", "}", "if (cr == 2) {", " z qr1[0];", "}", "", ] ) self.assertEqual(Exporter().dumps(qc), expected_qasm) def test_registers_as_aliases(self): """Test that different types of alias creation and concatenation work.""" qubits = [Qubit() for _ in [None] * 10] first_four = QuantumRegister(name="first_four", bits=qubits[:4]) last_five = QuantumRegister(name="last_five", bits=qubits[5:]) alternate = QuantumRegister(name="alternate", bits=qubits[::2]) sporadic = QuantumRegister(name="sporadic", bits=[qubits[4], qubits[2], qubits[9]]) qc = QuantumCircuit(qubits, first_four, last_five, alternate, sporadic) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "qubit _qubit0;", "qubit _qubit1;", "qubit _qubit2;", "qubit _qubit3;", "qubit _qubit4;", "qubit _qubit5;", "qubit _qubit6;", "qubit _qubit7;", "qubit _qubit8;", "qubit _qubit9;", "let first_four = {_qubit0, _qubit1, _qubit2, _qubit3};", "let last_five = {_qubit5, _qubit6, _qubit7, _qubit8, _qubit9};", "let alternate = {first_four[0], first_four[2], _qubit4, last_five[1], last_five[3]};", "let sporadic = {alternate[2], alternate[1], last_five[4]};", "", ] ) self.assertEqual(Exporter(allow_aliasing=True).dumps(qc), expected_qasm) def test_composite_circuit(self): """Test with a composite circuit instruction and barriers""" composite_circ_qreg = QuantumRegister(2) composite_circ = QuantumCircuit(composite_circ_qreg, name="composite_circ") composite_circ.h(0) composite_circ.x(1) composite_circ.cx(0, 1) composite_circ_instr = composite_circ.to_gate() qr = QuantumRegister(2, "qr") cr = ClassicalRegister(2, "cr") qc = QuantumCircuit(qr, cr) qc.h(0) qc.cx(0, 1) qc.barrier() qc.append(composite_circ_instr, [0, 1]) qc.measure([0, 1], [0, 1]) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "gate composite_circ _gate_q_0, _gate_q_1 {", " h _gate_q_0;", " x _gate_q_1;", " cx _gate_q_0, _gate_q_1;", "}", "bit[2] cr;", "qubit[2] qr;", "h qr[0];", "cx qr[0], qr[1];", "barrier qr[0], qr[1];", "composite_circ qr[0], qr[1];", "cr[0] = measure qr[0];", "cr[1] = measure qr[1];", "", ] ) self.assertEqual(Exporter().dumps(qc), expected_qasm) def test_custom_gate(self): """Test custom gates (via to_gate).""" composite_circ_qreg = QuantumRegister(2) composite_circ = QuantumCircuit(composite_circ_qreg, name="composite_circ") composite_circ.h(0) composite_circ.x(1) composite_circ.cx(0, 1) composite_circ_instr = composite_circ.to_gate() qr = QuantumRegister(2, "qr") cr = ClassicalRegister(2, "cr") qc = QuantumCircuit(qr, cr) qc.h(0) qc.cx(0, 1) qc.barrier() qc.append(composite_circ_instr, [0, 1]) qc.measure([0, 1], [0, 1]) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "gate composite_circ _gate_q_0, _gate_q_1 {", " h _gate_q_0;", " x _gate_q_1;", " cx _gate_q_0, _gate_q_1;", "}", "bit[2] cr;", "qubit[2] qr;", "h qr[0];", "cx qr[0], qr[1];", "barrier qr[0], qr[1];", "composite_circ qr[0], qr[1];", "cr[0] = measure qr[0];", "cr[1] = measure qr[1];", "", ] ) self.assertEqual(Exporter().dumps(qc), expected_qasm) def test_same_composite_circuits(self): """Test when a composite circuit is added to the circuit multiple times.""" composite_circ_qreg = QuantumRegister(2) composite_circ = QuantumCircuit(composite_circ_qreg, name="composite_circ") composite_circ.h(0) composite_circ.x(1) composite_circ.cx(0, 1) composite_circ_instr = composite_circ.to_gate() qr = QuantumRegister(2, "qr") cr = ClassicalRegister(2, "cr") qc = QuantumCircuit(qr, cr) qc.h(0) qc.cx(0, 1) qc.barrier() qc.append(composite_circ_instr, [0, 1]) qc.append(composite_circ_instr, [0, 1]) qc.measure([0, 1], [0, 1]) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "gate composite_circ _gate_q_0, _gate_q_1 {", " h _gate_q_0;", " x _gate_q_1;", " cx _gate_q_0, _gate_q_1;", "}", "bit[2] cr;", "qubit[2] qr;", "h qr[0];", "cx qr[0], qr[1];", "barrier qr[0], qr[1];", "composite_circ qr[0], qr[1];", "composite_circ qr[0], qr[1];", "cr[0] = measure qr[0];", "cr[1] = measure qr[1];", "", ] ) self.assertEqual(Exporter().dumps(qc), expected_qasm) def test_composite_circuits_with_same_name(self): """Test when multiple composite circuit instructions same name and different implementation.""" my_gate = QuantumCircuit(1, name="my_gate") my_gate.h(0) my_gate_inst1 = my_gate.to_gate() my_gate = QuantumCircuit(1, name="my_gate") my_gate.x(0) my_gate_inst2 = my_gate.to_gate() my_gate = QuantumCircuit(1, name="my_gate") my_gate.x(0) my_gate_inst3 = my_gate.to_gate() qr = QuantumRegister(1, name="qr") circuit = QuantumCircuit(qr, name="circuit") circuit.append(my_gate_inst1, [qr[0]]) circuit.append(my_gate_inst2, [qr[0]]) my_gate_inst2_id = id(circuit.data[-1].operation) circuit.append(my_gate_inst3, [qr[0]]) my_gate_inst3_id = id(circuit.data[-1].operation) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "gate my_gate _gate_q_0 {", " h _gate_q_0;", "}", f"gate my_gate_{my_gate_inst2_id} _gate_q_0 {{", " x _gate_q_0;", "}", f"gate my_gate_{my_gate_inst3_id} _gate_q_0 {{", " x _gate_q_0;", "}", "qubit[1] qr;", "my_gate qr[0];", f"my_gate_{my_gate_inst2_id} qr[0];", f"my_gate_{my_gate_inst3_id} qr[0];", "", ] ) self.assertEqual(Exporter().dumps(circuit), expected_qasm) def test_pi_disable_constants_false(self): """Test pi constant (disable_constants=False)""" circuit = QuantumCircuit(2) circuit.u(2 * pi, 3 * pi, -5 * pi, 0) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "qubit[2] q;", "U(2*pi, 3*pi, -5*pi) q[0];", "", ] ) self.assertEqual(Exporter(disable_constants=False).dumps(circuit), expected_qasm) def test_pi_disable_constants_true(self): """Test pi constant (disable_constants=True)""" circuit = QuantumCircuit(2) circuit.u(2 * pi, 3 * pi, -5 * pi, 0) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "qubit[2] q;", "U(6.283185307179586, 9.42477796076938, -15.707963267948966) q[0];", "", ] ) self.assertEqual(Exporter(disable_constants=True).dumps(circuit), expected_qasm) def test_custom_gate_with_unbound_parameter(self): """Test custom gate with unbound parameter.""" parameter_a = Parameter("a") custom = QuantumCircuit(1, name="custom") custom.rx(parameter_a, 0) circuit = QuantumCircuit(1) circuit.append(custom.to_gate(), [0]) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "input float[64] a;", "gate custom(a) _gate_q_0 {", " rx(a) _gate_q_0;", "}", "qubit[1] q;", "custom(a) q[0];", "", ] ) self.assertEqual(Exporter().dumps(circuit), expected_qasm) def test_custom_gate_with_bound_parameter(self): """Test custom gate with bound parameter.""" parameter_a = Parameter("a") custom = QuantumCircuit(1) custom.rx(parameter_a, 0) custom_gate = custom.bind_parameters({parameter_a: 0.5}).to_gate() custom_gate.name = "custom" circuit = QuantumCircuit(1) circuit.append(custom_gate, [0]) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "gate custom _gate_q_0 {", " rx(0.5) _gate_q_0;", "}", "qubit[1] q;", "custom q[0];", "", ] ) self.assertEqual(Exporter().dumps(circuit), expected_qasm) @requires_fixed_parameterisation def test_custom_gate_with_params_bound_main_call(self): """Custom gate with unbound parameters that are bound in the main circuit""" parameter0 = Parameter("p0") parameter1 = Parameter("p1") custom = QuantumCircuit(2, name="custom") custom.rz(parameter0, 0) custom.rz(parameter1 / 2, 1) qr_all_qubits = QuantumRegister(3, "q") qr_r = QuantumRegister(3, "r") circuit = QuantumCircuit(qr_all_qubits, qr_r) circuit.append(custom.to_gate(), [qr_all_qubits[0], qr_r[0]]) circuit.assign_parameters({parameter0: pi, parameter1: pi / 2}, inplace=True) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "gate custom(_gate_p_0, _gate_p_0) _gate_q_0, _gate_q_1 {", " rz(pi) _gate_q_0;", " rz(pi/4) _gate_q_1;", "}", "qubit[3] q;", "qubit[3] r;", "custom(pi, pi/2) q[0], r[0];", "", ] ) self.assertEqual(Exporter().dumps(circuit), expected_qasm) def test_reused_custom_parameter(self): """Test reused custom gate with parameter.""" parameter_a = Parameter("a") custom = QuantumCircuit(1) custom.rx(parameter_a, 0) circuit = QuantumCircuit(1) circuit.append(custom.bind_parameters({parameter_a: 0.5}).to_gate(), [0]) circuit.append(custom.bind_parameters({parameter_a: 1}).to_gate(), [0]) circuit_name_0 = circuit.data[0].operation.definition.name circuit_name_1 = circuit.data[1].operation.definition.name expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', f"gate {circuit_name_0} _gate_q_0 {{", " rx(0.5) _gate_q_0;", "}", f"gate {circuit_name_1} _gate_q_0 {{", " rx(1.0) _gate_q_0;", "}", "qubit[1] q;", f"{circuit_name_0} q[0];", f"{circuit_name_1} q[0];", "", ] ) self.assertEqual(Exporter().dumps(circuit), expected_qasm) def test_unbound_circuit(self): """Test with unbound parameters (turning them into inputs).""" qc = QuantumCircuit(1) theta = Parameter("θ") qc.rz(theta, 0) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "input float[64] θ;", "qubit[1] q;", "rz(θ) q[0];", "", ] ) self.assertEqual(Exporter().dumps(qc), expected_qasm) def test_unknown_parameterized_gate_called_multiple_times(self): """Test that a parameterised gate is called correctly if the first instance of it is generic.""" x, y = Parameter("x"), Parameter("y") qc = QuantumCircuit(2) qc.rzx(x, 0, 1) qc.rzx(y, 0, 1) qc.rzx(0.5, 0, 1) expected_qasm = "\n".join( [ "OPENQASM 3;", "input float[64] x;", "input float[64] y;", "gate rzx(x) _gate_q_0, _gate_q_1 {", " h _gate_q_1;", " cx _gate_q_0, _gate_q_1;", " rz(x) _gate_q_1;", " cx _gate_q_0, _gate_q_1;", " h _gate_q_1;", "}", "qubit[2] q;", "rzx(x) q[0], q[1];", "rzx(y) q[0], q[1];", "rzx(0.5) q[0], q[1];", "", ] ) # Set the includes and basis gates to ensure that this gate is unknown. exporter = Exporter(includes=[], basis_gates=("rz", "h", "cx")) self.assertEqual(exporter.dumps(qc), expected_qasm) def test_gate_qasm_with_ctrl_state(self): """Test with open controlled gate that has ctrl_state""" qc = QuantumCircuit(2) qc.ch(0, 1, ctrl_state=0) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "gate ch_o0 _gate_q_0, _gate_q_1 {", " x _gate_q_0;", " ch _gate_q_0, _gate_q_1;", " x _gate_q_0;", "}", "qubit[2] q;", "ch_o0 q[0], q[1];", "", ] ) self.assertEqual(Exporter().dumps(qc), expected_qasm) def test_custom_gate_collision_with_stdlib(self): """Test a custom gate with name collision with the standard library.""" custom = QuantumCircuit(2, name="cx") custom.cx(0, 1) custom_gate = custom.to_gate() qc = QuantumCircuit(2) qc.append(custom_gate, [0, 1]) custom_gate_id = id(qc.data[-1].operation) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', f"gate cx_{custom_gate_id} _gate_q_0, _gate_q_1 {{", " cx _gate_q_0, _gate_q_1;", "}", "qubit[2] q;", f"cx_{custom_gate_id} q[0], q[1];", "", ] ) self.assertEqual(Exporter().dumps(qc), expected_qasm) @requires_fixed_parameterisation def test_no_include(self): """Test explicit gate declaration (no include)""" q = QuantumRegister(2, "q") circuit = QuantumCircuit(q) circuit.rz(pi / 2, 0) circuit.sx(0) circuit.cx(0, 1) expected_qasm = "\n".join( [ "OPENQASM 3;", "gate u3(_gate_p_0, _gate_p_1, _gate_p_2) _gate_q_0 {", " U(0, 0, pi/2) _gate_q_0;", "}", "gate u1(_gate_p_0) _gate_q_0 {", " u3(0, 0, pi/2) _gate_q_0;", "}", "gate rz(_gate_p_0) _gate_q_0 {", " u1(pi/2) _gate_q_0;", "}", "gate sdg _gate_q_0 {", " u1(-pi/2) _gate_q_0;", "}", "gate u2(_gate_p_0, _gate_p_1) _gate_q_0 {", " u3(pi/2, 0, pi) _gate_q_0;", "}", "gate h _gate_q_0 {", " u2(0, pi) _gate_q_0;", "}", "gate sx _gate_q_0 {", " sdg _gate_q_0;", " h _gate_q_0;", " sdg _gate_q_0;", "}", "gate cx c, t {", " ctrl @ U(pi, 0, pi) c, t;", "}", "qubit[2] q;", "rz(pi/2) q[0];", "sx q[0];", "cx q[0], q[1];", "", ] ) self.assertEqual(Exporter(includes=[]).dumps(circuit), expected_qasm) @requires_fixed_parameterisation def test_teleportation(self): """Teleportation with physical qubits""" qc = QuantumCircuit(3, 2) qc.h(1) qc.cx(1, 2) qc.barrier() qc.cx(0, 1) qc.h(0) qc.barrier() qc.measure([0, 1], [0, 1]) qc.barrier() qc.x(2).c_if(qc.clbits[1], 1) qc.z(2).c_if(qc.clbits[0], 1) transpiled = transpile(qc, initial_layout=[0, 1, 2]) expected_qasm = "\n".join( [ "OPENQASM 3;", "gate u3(_gate_p_0, _gate_p_1, _gate_p_2) _gate_q_0 {", " U(pi/2, 0, pi) _gate_q_0;", "}", "gate u2(_gate_p_0, _gate_p_1) _gate_q_0 {", " u3(pi/2, 0, pi) _gate_q_0;", "}", "gate h _gate_q_0 {", " u2(0, pi) _gate_q_0;", "}", "gate cx c, t {", " ctrl @ U(pi, 0, pi) c, t;", "}", "gate x _gate_q_0 {", " u3(pi, 0, pi) _gate_q_0;", "}", "gate u1(_gate_p_0) _gate_q_0 {", " u3(0, 0, pi) _gate_q_0;", "}", "gate z _gate_q_0 {", " u1(pi) _gate_q_0;", "}", "bit[2] c;", "h $1;", "cx $1, $2;", "barrier $0, $1, $2;", "cx $0, $1;", "h $0;", "barrier $0, $1, $2;", "c[0] = measure $0;", "c[1] = measure $1;", "barrier $0, $1, $2;", "if (c[1]) {", " x $2;", "}", "if (c[0]) {", " z $2;", "}", "", ] ) self.assertEqual(Exporter(includes=[]).dumps(transpiled), expected_qasm) @requires_fixed_parameterisation def test_basis_gates(self): """Teleportation with physical qubits""" qc = QuantumCircuit(3, 2) qc.h(1) qc.cx(1, 2) qc.barrier() qc.cx(0, 1) qc.h(0) qc.barrier() qc.measure([0, 1], [0, 1]) qc.barrier() qc.x(2).c_if(qc.clbits[1], 1) qc.z(2).c_if(qc.clbits[0], 1) transpiled = transpile(qc, initial_layout=[0, 1, 2]) expected_qasm = "\n".join( [ "OPENQASM 3;", "gate u3(_gate_p_0, _gate_p_1, _gate_p_2) _gate_q_0 {", " U(pi/2, 0, pi) _gate_q_0;", "}", "gate u2(_gate_p_0, _gate_p_1) _gate_q_0 {", " u3(pi/2, 0, pi) _gate_q_0;", "}", "gate h _gate_q_0 {", " u2(0, pi) _gate_q_0;", "}", "gate x _gate_q_0 {", " u3(pi, 0, pi) _gate_q_0;", "}", "bit[2] c;", "h $1;", "cx $1, $2;", "barrier $0, $1, $2;", "cx $0, $1;", "h $0;", "barrier $0, $1, $2;", "c[0] = measure $0;", "c[1] = measure $1;", "barrier $0, $1, $2;", "if (c[1]) {", " x $2;", "}", "if (c[0]) {", " z $2;", "}", "", ] ) self.assertEqual( Exporter(includes=[], basis_gates=["cx", "z", "U"]).dumps(transpiled), expected_qasm, ) def test_opaque_instruction_in_basis_gates(self): """Test that an instruction that is set in the basis gates is output verbatim with no definition.""" qc = QuantumCircuit(1) qc.x(0) qc.append(Gate("my_gate", 1, []), [0], []) basis_gates = ["my_gate", "x"] transpiled = transpile(qc, initial_layout=[0]) expected_qasm = "\n".join( [ "OPENQASM 3;", "x $0;", "my_gate $0;", "", ] ) self.assertEqual( Exporter(includes=[], basis_gates=basis_gates).dumps(transpiled), expected_qasm ) def test_reset_statement(self): """Test that a reset statement gets output into valid QASM 3. This includes tests of reset operations on single qubits and in nested scopes.""" qreg = QuantumRegister(2, "qr") qc = QuantumCircuit(qreg) qc.reset(0) qc.reset([0, 1]) expected_qasm = "\n".join( [ "OPENQASM 3;", "qubit[2] qr;", "reset qr[0];", "reset qr[0];", "reset qr[1];", "", ] ) self.assertEqual(Exporter(includes=[]).dumps(qc), expected_qasm) def test_delay_statement(self): """Test that delay operations get output into valid QASM 3.""" qreg = QuantumRegister(2, "qr") qc = QuantumCircuit(qreg) qc.delay(100, qreg[0], unit="ms") qc.delay(2, qreg[1], unit="ps") # "ps" is not a valid unit in OQ3, so we need to convert. expected_qasm = "\n".join( [ "OPENQASM 3;", "qubit[2] qr;", "delay[100ms] qr[0];", "delay[2000ns] qr[1];", "", ] ) self.assertEqual(Exporter(includes=[]).dumps(qc), expected_qasm) def test_loose_qubits(self): """Test that qubits that are not in any register can be used without issue.""" bits = [Qubit(), Qubit()] qr = QuantumRegister(2, name="qr") cr = ClassicalRegister(2, name="cr") qc = QuantumCircuit(bits, qr, cr) qc.h(0) qc.h(1) qc.h(2) qc.h(3) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "bit[2] cr;", "qubit _qubit0;", "qubit _qubit1;", "qubit[2] qr;", "h _qubit0;", "h _qubit1;", "h qr[0];", "h qr[1];", "", ] ) self.assertEqual(dumps(qc), expected_qasm) def test_loose_clbits(self): """Test that clbits that are not in any register can be used without issue.""" qreg = QuantumRegister(1, name="qr") bits = [Clbit() for _ in [None] * 7] cr1 = ClassicalRegister(name="cr1", bits=bits[1:3]) cr2 = ClassicalRegister(name="cr2", bits=bits[4:6]) qc = QuantumCircuit(bits, qreg, cr1, cr2) qc.measure(0, 0) qc.measure(0, 1) qc.measure(0, 2) qc.measure(0, 3) qc.measure(0, 4) qc.measure(0, 5) qc.measure(0, 6) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "bit _bit0;", "bit _bit3;", "bit _bit6;", "bit[2] cr1;", "bit[2] cr2;", "qubit[1] qr;", "_bit0 = measure qr[0];", "cr1[0] = measure qr[0];", "cr1[1] = measure qr[0];", "_bit3 = measure qr[0];", "cr2[0] = measure qr[0];", "cr2[1] = measure qr[0];", "_bit6 = measure qr[0];", "", ] ) self.assertEqual(dumps(qc), expected_qasm) def test_classical_register_aliasing(self): """Test that clbits that are not in any register can be used without issue.""" qreg = QuantumRegister(1, name="qr") bits = [Clbit() for _ in [None] * 7] cr1 = ClassicalRegister(name="cr1", bits=bits[1:3]) cr2 = ClassicalRegister(name="cr2", bits=bits[4:6]) # cr3 overlaps cr2, but this should be allowed in this alias form. cr3 = ClassicalRegister(name="cr3", bits=bits[5:]) qc = QuantumCircuit(bits, qreg, cr1, cr2, cr3) qc.measure(0, 0) qc.measure(0, 1) qc.measure(0, 2) qc.measure(0, 3) qc.measure(0, 4) qc.measure(0, 5) qc.measure(0, 6) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "bit _bit0;", "bit _bit1;", "bit _bit2;", "bit _bit3;", "bit _bit4;", "bit _bit5;", "bit _bit6;", "let cr1 = {_bit1, _bit2};", "let cr2 = {_bit4, _bit5};", "let cr3 = {cr2[1], _bit6};", "qubit[1] qr;", "_bit0 = measure qr[0];", "cr1[0] = measure qr[0];", "cr1[1] = measure qr[0];", "_bit3 = measure qr[0];", "cr2[0] = measure qr[0];", "cr3[0] = measure qr[0];", "cr3[1] = measure qr[0];", "", ] ) self.assertEqual(dumps(qc, allow_aliasing=True), expected_qasm) def test_old_alias_classical_registers_option(self): """Test that the ``alias_classical_registers`` option still functions during its changeover period.""" qreg = QuantumRegister(1, name="qr") bits = [Clbit() for _ in [None] * 7] cr1 = ClassicalRegister(name="cr1", bits=bits[1:3]) cr2 = ClassicalRegister(name="cr2", bits=bits[4:6]) # cr3 overlaps cr2, but this should be allowed in this alias form. cr3 = ClassicalRegister(name="cr3", bits=bits[5:]) qc = QuantumCircuit(bits, qreg, cr1, cr2, cr3) qc.measure(0, 0) qc.measure(0, 1) qc.measure(0, 2) qc.measure(0, 3) qc.measure(0, 4) qc.measure(0, 5) qc.measure(0, 6) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "bit _bit0;", "bit _bit1;", "bit _bit2;", "bit _bit3;", "bit _bit4;", "bit _bit5;", "bit _bit6;", "let cr1 = {_bit1, _bit2};", "let cr2 = {_bit4, _bit5};", "let cr3 = {cr2[1], _bit6};", "qubit[1] qr;", "_bit0 = measure qr[0];", "cr1[0] = measure qr[0];", "cr1[1] = measure qr[0];", "_bit3 = measure qr[0];", "cr2[0] = measure qr[0];", "cr3[0] = measure qr[0];", "cr3[1] = measure qr[0];", "", ] ) self.assertEqual(dumps(qc, alias_classical_registers=True), expected_qasm) def test_simple_for_loop(self): """Test that a simple for loop outputs the expected result.""" parameter = Parameter("x") loop_body = QuantumCircuit(1) loop_body.rx(parameter, 0) loop_body.break_loop() loop_body.continue_loop() qc = QuantumCircuit(2) qc.for_loop([0, 3, 4], parameter, loop_body, [1], []) qc.x(0) qr_name = qc.qregs[0].name expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', f"qubit[2] {qr_name};", f"for {parameter.name} in {{0, 3, 4}} {{", f" rx({parameter.name}) {qr_name}[1];", " break;", " continue;", "}", f"x {qr_name}[0];", "", ] ) self.assertEqual(dumps(qc), expected_qasm) def test_nested_for_loop(self): """Test that a for loop nested inside another outputs the expected result.""" inner_parameter = Parameter("x") outer_parameter = Parameter("y") inner_body = QuantumCircuit(2) inner_body.rz(inner_parameter, 0) inner_body.rz(outer_parameter, 1) inner_body.break_loop() outer_body = QuantumCircuit(2) outer_body.h(0) outer_body.rz(outer_parameter, 1) # Note we reverse the order of the bits here to test that this is traced. outer_body.for_loop(range(1, 5, 2), inner_parameter, inner_body, [1, 0], []) outer_body.continue_loop() qc = QuantumCircuit(2) qc.for_loop(range(4), outer_parameter, outer_body, [0, 1], []) qc.x(0) qr_name = qc.qregs[0].name expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', f"qubit[2] {qr_name};", f"for {outer_parameter.name} in [0:3] {{", f" h {qr_name}[0];", f" rz({outer_parameter.name}) {qr_name}[1];", f" for {inner_parameter.name} in [1:2:4] {{", # Note the reversed bit order. f" rz({inner_parameter.name}) {qr_name}[1];", f" rz({outer_parameter.name}) {qr_name}[0];", " break;", " }", " continue;", "}", f"x {qr_name}[0];", "", ] ) self.assertEqual(dumps(qc), expected_qasm) def test_regular_parameter_in_nested_for_loop(self): """Test that a for loop nested inside another outputs the expected result, including defining parameters that are used in nested loop scopes.""" inner_parameter = Parameter("x") outer_parameter = Parameter("y") regular_parameter = Parameter("t") inner_body = QuantumCircuit(2) inner_body.h(0) inner_body.rx(regular_parameter, 1) inner_body.break_loop() outer_body = QuantumCircuit(2) outer_body.h(0) outer_body.h(1) # Note we reverse the order of the bits here to test that this is traced. outer_body.for_loop(range(1, 5, 2), inner_parameter, inner_body, [1, 0], []) outer_body.continue_loop() qc = QuantumCircuit(2) qc.for_loop(range(4), outer_parameter, outer_body, [0, 1], []) qc.x(0) qr_name = qc.qregs[0].name expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', # This next line will be missing until gh-7280 is fixed. f"input float[64] {regular_parameter.name};", f"qubit[2] {qr_name};", f"for {outer_parameter.name} in [0:3] {{", f" h {qr_name}[0];", f" h {qr_name}[1];", f" for {inner_parameter.name} in [1:2:4] {{", # Note the reversed bit order. f" h {qr_name}[1];", f" rx({regular_parameter.name}) {qr_name}[0];", " break;", " }", " continue;", "}", f"x {qr_name}[0];", "", ] ) self.assertEqual(dumps(qc), expected_qasm) def test_for_loop_with_no_parameter(self): """Test that a for loop with the parameter set to ``None`` outputs the expected result.""" loop_body = QuantumCircuit(1) loop_body.h(0) qc = QuantumCircuit(2) qc.for_loop([0, 3, 4], None, loop_body, [1], []) qr_name = qc.qregs[0].name expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', f"qubit[2] {qr_name};", "for _ in {0, 3, 4} {", f" h {qr_name}[1];", "}", "", ] ) self.assertEqual(dumps(qc), expected_qasm) def test_simple_while_loop(self): """Test that a simple while loop works correctly.""" loop_body = QuantumCircuit(1) loop_body.h(0) loop_body.break_loop() loop_body.continue_loop() qr = QuantumRegister(2, name="qr") cr = ClassicalRegister(2, name="cr") qc = QuantumCircuit(qr, cr) qc.while_loop((cr, 0), loop_body, [1], []) qc.x(0) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "bit[2] cr;", "qubit[2] qr;", "while (cr == 0) {", " h qr[1];", " break;", " continue;", "}", "x qr[0];", "", ] ) self.assertEqual(dumps(qc), expected_qasm) def test_nested_while_loop(self): """Test that a while loop nested inside another outputs the expected result.""" inner_body = QuantumCircuit(2, 2) inner_body.measure(0, 0) inner_body.measure(1, 1) inner_body.break_loop() outer_body = QuantumCircuit(2, 2) outer_body.measure(0, 0) outer_body.measure(1, 1) # We reverse the order of the bits here to test this works, and test a single-bit condition. outer_body.while_loop((outer_body.clbits[0], 0), inner_body, [1, 0], [1, 0]) outer_body.continue_loop() qr = QuantumRegister(2, name="qr") cr = ClassicalRegister(2, name="cr") qc = QuantumCircuit(qr, cr) qc.while_loop((cr, 0), outer_body, [0, 1], [0, 1]) qc.x(0) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "bit[2] cr;", "qubit[2] qr;", "while (cr == 0) {", " cr[0] = measure qr[0];", " cr[1] = measure qr[1];", # Note the reversed bits in the body. " while (!cr[0]) {", " cr[1] = measure qr[1];", " cr[0] = measure qr[0];", " break;", " }", " continue;", "}", "x qr[0];", "", ] ) self.assertEqual(dumps(qc), expected_qasm) def test_simple_if_statement(self): """Test that a simple if statement with no else works correctly.""" true_body = QuantumCircuit(1) true_body.h(0) qr = QuantumRegister(2, name="qr") cr = ClassicalRegister(2, name="cr") qc = QuantumCircuit(qr, cr) qc.if_test((cr, 0), true_body, [1], []) qc.x(0) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "bit[2] cr;", "qubit[2] qr;", "if (cr == 0) {", " h qr[1];", "}", "x qr[0];", "", ] ) self.assertEqual(dumps(qc), expected_qasm) def test_simple_if_else_statement(self): """Test that a simple if statement with an else branch works correctly.""" true_body = QuantumCircuit(1) true_body.h(0) false_body = QuantumCircuit(1) false_body.z(0) qr = QuantumRegister(2, name="qr") cr = ClassicalRegister(2, name="cr") qc = QuantumCircuit(qr, cr) qc.if_else((cr, 0), true_body, false_body, [1], []) qc.x(0) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "bit[2] cr;", "qubit[2] qr;", "if (cr == 0) {", " h qr[1];", "} else {", " z qr[1];", "}", "x qr[0];", "", ] ) self.assertEqual(dumps(qc), expected_qasm) def test_nested_if_else_statement(self): """Test that a nested if/else statement works correctly.""" inner_true_body = QuantumCircuit(2, 2) inner_true_body.measure(0, 0) inner_false_body = QuantumCircuit(2, 2) inner_false_body.measure(1, 1) outer_true_body = QuantumCircuit(2, 2) outer_true_body.if_else( (outer_true_body.clbits[0], 0), inner_true_body, inner_false_body, [0, 1], [0, 1] ) outer_false_body = QuantumCircuit(2, 2) # Note the flipped bits here. outer_false_body.if_else( (outer_false_body.clbits[0], 1), inner_true_body, inner_false_body, [1, 0], [1, 0] ) qr = QuantumRegister(2, name="qr") cr = ClassicalRegister(2, name="cr") qc = QuantumCircuit(qr, cr) qc.if_else((cr, 0), outer_true_body, outer_false_body, [0, 1], [0, 1]) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "bit[2] cr;", "qubit[2] qr;", "if (cr == 0) {", " if (!cr[0]) {", " cr[0] = measure qr[0];", " } else {", " cr[1] = measure qr[1];", " }", "} else {", " if (cr[0]) {", " cr[1] = measure qr[1];", " } else {", " cr[0] = measure qr[0];", " }", "}", "", ] ) self.assertEqual(dumps(qc), expected_qasm) def test_chain_else_if(self): """Test the basic 'else/if' chaining logic for flattening the else scope if its content is a single if/else statement.""" inner_true_body = QuantumCircuit(2, 2) inner_true_body.measure(0, 0) inner_false_body = QuantumCircuit(2, 2) inner_false_body.measure(1, 1) outer_true_body = QuantumCircuit(2, 2) outer_true_body.if_else( (outer_true_body.clbits[0], 0), inner_true_body, inner_false_body, [0, 1], [0, 1] ) outer_false_body = QuantumCircuit(2, 2) # Note the flipped bits here. outer_false_body.if_else( (outer_false_body.clbits[0], 1), inner_true_body, inner_false_body, [1, 0], [1, 0] ) qr = QuantumRegister(2, name="qr") cr = ClassicalRegister(2, name="cr") qc = QuantumCircuit(qr, cr) qc.if_else((cr, 0), outer_true_body, outer_false_body, [0, 1], [0, 1]) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "bit[2] cr;", "qubit[2] qr;", "if (cr == 0) {", " if (!cr[0]) {", " cr[0] = measure qr[0];", " } else {", " cr[1] = measure qr[1];", " }", "} else if (cr[0]) {", " cr[1] = measure qr[1];", "} else {", " cr[0] = measure qr[0];", "}", "", ] ) # This is not the default behaviour, and it's pretty buried how you'd access it. builder = QASM3Builder( qc, includeslist=("stdgates.inc",), basis_gates=("U",), disable_constants=False, allow_aliasing=False, ) stream = StringIO() BasicPrinter(stream, indent=" ", chain_else_if=True).visit(builder.build_program()) self.assertEqual(stream.getvalue(), expected_qasm) def test_chain_else_if_does_not_chain_if_extra_instructions(self): """Test the basic 'else/if' chaining logic for flattening the else scope if its content is a single if/else statement does not cause a flattening if the 'else' block is not a single if/else.""" inner_true_body = QuantumCircuit(2, 2) inner_true_body.measure(0, 0) inner_false_body = QuantumCircuit(2, 2) inner_false_body.measure(1, 1) outer_true_body = QuantumCircuit(2, 2) outer_true_body.if_else( (outer_true_body.clbits[0], 0), inner_true_body, inner_false_body, [0, 1], [0, 1] ) outer_false_body = QuantumCircuit(2, 2) # Note the flipped bits here. outer_false_body.if_else( (outer_false_body.clbits[0], 1), inner_true_body, inner_false_body, [1, 0], [1, 0] ) outer_false_body.h(0) qr = QuantumRegister(2, name="qr") cr = ClassicalRegister(2, name="cr") qc = QuantumCircuit(qr, cr) qc.if_else((cr, 0), outer_true_body, outer_false_body, [0, 1], [0, 1]) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "bit[2] cr;", "qubit[2] qr;", "if (cr == 0) {", " if (!cr[0]) {", " cr[0] = measure qr[0];", " } else {", " cr[1] = measure qr[1];", " }", "} else {", " if (cr[0]) {", " cr[1] = measure qr[1];", " } else {", " cr[0] = measure qr[0];", " }", " h qr[0];", "}", "", ] ) # This is not the default behaviour, and it's pretty buried how you'd access it. builder = QASM3Builder( qc, includeslist=("stdgates.inc",), basis_gates=("U",), disable_constants=False, allow_aliasing=False, ) stream = StringIO() BasicPrinter(stream, indent=" ", chain_else_if=True).visit(builder.build_program()) self.assertEqual(stream.getvalue(), expected_qasm) def test_custom_gate_used_in_loop_scope(self): """Test that a custom gate only used within a loop scope still gets a definition at the top level.""" parameter_a = Parameter("a") parameter_b = Parameter("b") custom = QuantumCircuit(1) custom.rx(parameter_a, 0) custom_gate = custom.bind_parameters({parameter_a: 0.5}).to_gate() custom_gate.name = "custom" loop_body = QuantumCircuit(1) loop_body.append(custom_gate, [0]) qc = QuantumCircuit(1) qc.for_loop(range(2), parameter_b, loop_body, [0], []) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "gate custom _gate_q_0 {", " rx(0.5) _gate_q_0;", "}", "qubit[1] q;", "for b in [0:1] {", " custom q[0];", "}", "", ] ) self.assertEqual(dumps(qc), expected_qasm) def test_registers_have_escaped_names(self): """Test that both types of register are emitted with safely escaped names if they begin with invalid names. Regression test of gh-9658.""" qc = QuantumCircuit( QuantumRegister(2, name="q_{reg}"), ClassicalRegister(2, name="c_{reg}") ) qc.measure([0, 1], [0, 1]) out_qasm = dumps(qc) matches = {match_["name"] for match_ in self.register_regex.finditer(out_qasm)} self.assertEqual(len(matches), 2, msg=f"Observed OQ3 output:\n{out_qasm}") def test_parameters_have_escaped_names(self): """Test that parameters are emitted with safely escaped names if they begin with invalid names. Regression test of gh-9658.""" qc = QuantumCircuit(1) qc.u(Parameter("p_{0}"), 2 * Parameter("p_?0!"), 0, 0) out_qasm = dumps(qc) matches = {match_["name"] for match_ in self.scalar_parameter_regex.finditer(out_qasm)} self.assertEqual(len(matches), 2, msg=f"Observed OQ3 output:\n{out_qasm}") def test_parameter_expression_after_naming_escape(self): """Test that :class:`.Parameter` instances are correctly renamed when they are used with :class:`.ParameterExpression` blocks, even if they have names that needed to be escaped.""" param = Parameter("measure") # an invalid name qc = QuantumCircuit(1) qc.u(2 * param, 0, 0, 0) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "input float[64] _measure;", "qubit[1] q;", "U(2*_measure, 0, 0) q[0];", "", ] ) self.assertEqual(dumps(qc), expected_qasm) def test_parameters_and_registers_cannot_have_naming_clashes(self): """Test that parameters and registers are considered part of the same symbol table for the purposes of avoiding clashes.""" qreg = QuantumRegister(1, "clash") param = Parameter("clash") qc = QuantumCircuit(qreg) qc.u(param, 0, 0, 0) out_qasm = dumps(qc) register_name = self.register_regex.search(out_qasm) parameter_name = self.scalar_parameter_regex.search(out_qasm) self.assertTrue(register_name) self.assertTrue(parameter_name) self.assertIn("clash", register_name["name"]) self.assertIn("clash", parameter_name["name"]) self.assertNotEqual(register_name["name"], parameter_name["name"]) # Not necessarily all the reserved keywords, just a sensibly-sized subset. @data("bit", "const", "def", "defcal", "float", "gate", "include", "int", "let", "measure") def test_reserved_keywords_as_names_are_escaped(self, keyword): """Test that reserved keywords used to name registers and parameters are escaped into another form when output, and the escaping cannot introduce new conflicts.""" with self.subTest("register"): qreg = QuantumRegister(1, keyword) qc = QuantumCircuit(qreg) out_qasm = dumps(qc) register_name = self.register_regex.search(out_qasm) self.assertTrue(register_name, msg=f"Observed OQ3:\n{out_qasm}") self.assertNotEqual(keyword, register_name["name"]) with self.subTest("parameter"): qc = QuantumCircuit(1) param = Parameter(keyword) qc.u(param, 0, 0, 0) out_qasm = dumps(qc) parameter_name = self.scalar_parameter_regex.search(out_qasm) self.assertTrue(parameter_name, msg=f"Observed OQ3:\n{out_qasm}") self.assertNotEqual(keyword, parameter_name["name"]) def test_expr_condition(self): """Simple test that the conditions of `if`s and `while`s can be `Expr` nodes.""" bits = [Qubit(), Clbit()] cr = ClassicalRegister(2, "cr") if_body = QuantumCircuit(1) if_body.x(0) while_body = QuantumCircuit(1) while_body.x(0) qc = QuantumCircuit(bits, cr) qc.if_test(expr.logic_not(qc.clbits[0]), if_body, [0], []) qc.while_loop(expr.equal(cr, 3), while_body, [0], []) expected = """\ OPENQASM 3; include "stdgates.inc"; bit _bit0; bit[2] cr; qubit _qubit0; if (!_bit0) { x _qubit0; } while (cr == 3) { x _qubit0; } """ self.assertEqual(dumps(qc), expected) def test_expr_nested_condition(self): """Simple test that the conditions of `if`s and `while`s can be `Expr` nodes when nested, and the mapping of inner bits to outer bits is correct.""" bits = [Qubit(), Clbit(), Clbit()] cr = ClassicalRegister(2, "cr") inner_if_body = QuantumCircuit(1) inner_if_body.x(0) outer_if_body = QuantumCircuit(1, 1) outer_if_body.if_test(expr.lift(outer_if_body.clbits[0]), inner_if_body, [0], []) inner_while_body = QuantumCircuit(1) inner_while_body.x(0) outer_while_body = QuantumCircuit([Qubit()], cr) outer_while_body.while_loop(expr.equal(expr.bit_and(cr, 3), 3), inner_while_body, [0], []) qc = QuantumCircuit(bits, cr) qc.if_test(expr.logic_not(qc.clbits[0]), outer_if_body, [0], [1]) qc.while_loop(expr.equal(cr, 3), outer_while_body, [0], cr) expected = """\ OPENQASM 3; include "stdgates.inc"; bit _bit0; bit _bit1; bit[2] cr; qubit _qubit0; if (!_bit0) { if (_bit1) { x _qubit0; } } while (cr == 3) { while ((cr & 3) == 3) { x _qubit0; } } """ self.assertEqual(dumps(qc), expected) def test_expr_associativity_left(self): """Test that operations that are in the expression tree in a left-associative form are output to OQ3 correctly.""" body = QuantumCircuit() cr1 = ClassicalRegister(3, "cr1") cr2 = ClassicalRegister(3, "cr2") cr3 = ClassicalRegister(3, "cr3") qc = QuantumCircuit(cr1, cr2, cr3) qc.if_test(expr.equal(expr.bit_and(expr.bit_and(cr1, cr2), cr3), 7), body.copy(), [], []) qc.if_test(expr.equal(expr.bit_or(expr.bit_or(cr1, cr2), cr3), 7), body.copy(), [], []) qc.if_test(expr.equal(expr.bit_xor(expr.bit_xor(cr1, cr2), cr3), 7), body.copy(), [], []) qc.if_test(expr.logic_and(expr.logic_and(cr1[0], cr1[1]), cr1[2]), body.copy(), [], []) qc.if_test(expr.logic_or(expr.logic_or(cr1[0], cr1[1]), cr1[2]), body.copy(), [], []) # Note that bitwise operations have lower priority than `==` so there's extra parentheses. # All these operators are left-associative in OQ3. expected = """\ OPENQASM 3; include "stdgates.inc"; bit[3] cr1; bit[3] cr2; bit[3] cr3; if ((cr1 & cr2 & cr3) == 7) { } if ((cr1 | cr2 | cr3) == 7) { } if ((cr1 ^ cr2 ^ cr3) == 7) { } if (cr1[0] && cr1[1] && cr1[2]) { } if (cr1[0] || cr1[1] || cr1[2]) { } """ self.assertEqual(dumps(qc), expected) def test_expr_associativity_right(self): """Test that operations that are in the expression tree in a right-associative form are output to OQ3 correctly.""" body = QuantumCircuit() cr1 = ClassicalRegister(3, "cr1") cr2 = ClassicalRegister(3, "cr2") cr3 = ClassicalRegister(3, "cr3") qc = QuantumCircuit(cr1, cr2, cr3) qc.if_test(expr.equal(expr.bit_and(cr1, expr.bit_and(cr2, cr3)), 7), body.copy(), [], []) qc.if_test(expr.equal(expr.bit_or(cr1, expr.bit_or(cr2, cr3)), 7), body.copy(), [], []) qc.if_test(expr.equal(expr.bit_xor(cr1, expr.bit_xor(cr2, cr3)), 7), body.copy(), [], []) qc.if_test(expr.logic_and(cr1[0], expr.logic_and(cr1[1], cr1[2])), body.copy(), [], []) qc.if_test(expr.logic_or(cr1[0], expr.logic_or(cr1[1], cr1[2])), body.copy(), [], []) # Note that bitwise operations have lower priority than `==` so there's extra parentheses. # All these operators are left-associative in OQ3, so we need parentheses for them to be # parsed correctly. Mathematically, they're all actually associative in general, so the # order doesn't _technically_ matter. expected = """\ OPENQASM 3; include "stdgates.inc"; bit[3] cr1; bit[3] cr2; bit[3] cr3; if ((cr1 & (cr2 & cr3)) == 7) { } if ((cr1 | (cr2 | cr3)) == 7) { } if ((cr1 ^ (cr2 ^ cr3)) == 7) { } if (cr1[0] && (cr1[1] && cr1[2])) { } if (cr1[0] || (cr1[1] || cr1[2])) { } """ self.assertEqual(dumps(qc), expected) def test_expr_binding_unary(self): """Test that nested unary operators don't insert unnecessary brackets.""" body = QuantumCircuit() cr = ClassicalRegister(2, "cr") qc = QuantumCircuit(cr) qc.if_test(expr.equal(expr.bit_not(expr.bit_not(cr)), 3), body.copy(), [], []) qc.if_test(expr.logic_not(expr.logic_not(cr[0])), body.copy(), [], []) expected = """\ OPENQASM 3; include "stdgates.inc"; bit[2] cr; if (~~cr == 3) { } if (!!cr[0]) { } """ self.assertEqual(dumps(qc), expected) def test_expr_precedence(self): """Test that the precedence properties of operators are correctly output.""" body = QuantumCircuit() cr = ClassicalRegister(2, "cr") # This tree is _completely_ inside out, so there's brackets needed round every operand. inside_out = expr.logic_not( expr.less( expr.bit_and( expr.bit_xor(expr.bit_or(cr, cr), expr.bit_or(cr, cr)), expr.bit_xor(expr.bit_or(cr, cr), expr.bit_or(cr, cr)), ), expr.bit_and( expr.bit_xor(expr.bit_or(cr, cr), expr.bit_or(cr, cr)), expr.bit_xor(expr.bit_or(cr, cr), expr.bit_or(cr, cr)), ), ) ) # This one is the other way round - the tightest-binding operations are on the inside, so no # brackets should be needed at all except to put in a comparison to a bitwise binary # operation, since those bind less tightly than anything that can cast them to a bool. outside_in = expr.logic_or( expr.logic_and( expr.equal(expr.bit_or(cr, cr), expr.bit_and(cr, cr)), expr.equal(expr.bit_and(cr, cr), expr.bit_or(cr, cr)), ), expr.logic_and( expr.greater(expr.bit_or(cr, cr), expr.bit_xor(cr, cr)), expr.less_equal(expr.bit_xor(cr, cr), expr.bit_or(cr, cr)), ), ) # And an extra test of the logical operator order. logics = expr.logic_or( expr.logic_and( expr.logic_or(expr.logic_not(cr[0]), expr.logic_not(cr[0])), expr.logic_not(expr.logic_and(cr[0], cr[0])), ), expr.logic_and( expr.logic_not(expr.logic_and(cr[0], cr[0])), expr.logic_or(expr.logic_not(cr[0]), expr.logic_not(cr[0])), ), ) qc = QuantumCircuit(cr) qc.if_test(inside_out, body.copy(), [], []) qc.if_test(outside_in, body.copy(), [], []) qc.if_test(logics, body.copy(), [], []) expected = """\ OPENQASM 3; include "stdgates.inc"; bit[2] cr; if (!((((cr | cr) ^ (cr | cr)) & ((cr | cr) ^ (cr | cr)))\ < (((cr | cr) ^ (cr | cr)) & ((cr | cr) ^ (cr | cr))))) { } if ((cr | cr) == (cr & cr) && (cr & cr) == (cr | cr)\ || (cr | cr) > (cr ^ cr) && (cr ^ cr) <= (cr | cr)) { } if ((!cr[0] || !cr[0]) && !(cr[0] && cr[0]) || !(cr[0] && cr[0]) && (!cr[0] || !cr[0])) { } """ self.assertEqual(dumps(qc), expected) def test_no_unnecessary_cast(self): """This is a bit of a cross `Expr`-constructor / OQ3-exporter test. It doesn't really matter whether or not the `Expr` constructor functions insert cast nodes into their output for the literals (at the time of writing [commit 2616602], they don't because they do some type inference) but the OQ3 export definitely shouldn't have them.""" cr = ClassicalRegister(8, "cr") qc = QuantumCircuit(cr) # Note that the integer '1' has a minimum bit-width of 1, whereas the register has a width # of 8. We're testing to make sure that there's no spurious cast up from `bit[1]` to # `bit[8]`, or anything like that, _whether or not_ the `Expr` node includes one. qc.if_test(expr.equal(cr, 1), QuantumCircuit(), [], []) expected = """\ OPENQASM 3; include "stdgates.inc"; bit[8] cr; if (cr == 1) { } """ self.assertEqual(dumps(qc), expected) class TestCircuitQASM3ExporterTemporaryCasesWithBadParameterisation(QiskitTestCase): """Test functionality that is not what we _want_, but is what we need to do while the definition of custom gates with parameterisation does not work correctly. These tests are modified versions of those marked with the `requires_fixed_parameterisation` decorator, and this whole class can be deleted once those are fixed. See gh-7335. """ maxDiff = 1_000_000 def test_basis_gates(self): """Teleportation with physical qubits""" qc = QuantumCircuit(3, 2) first_h = qc.h(1)[0].operation qc.cx(1, 2) qc.barrier() qc.cx(0, 1) qc.h(0) qc.barrier() qc.measure([0, 1], [0, 1]) qc.barrier() first_x = qc.x(2).c_if(qc.clbits[1], 1)[0].operation qc.z(2).c_if(qc.clbits[0], 1) u2 = first_h.definition.data[0].operation u3_1 = u2.definition.data[0].operation u3_2 = first_x.definition.data[0].operation expected_qasm = "\n".join( [ "OPENQASM 3;", f"gate u3_{id(u3_1)}(_gate_p_0, _gate_p_1, _gate_p_2) _gate_q_0 {{", " U(pi/2, 0, pi) _gate_q_0;", "}", f"gate u2_{id(u2)}(_gate_p_0, _gate_p_1) _gate_q_0 {{", f" u3_{id(u3_1)}(pi/2, 0, pi) _gate_q_0;", "}", "gate h _gate_q_0 {", f" u2_{id(u2)}(0, pi) _gate_q_0;", "}", f"gate u3_{id(u3_2)}(_gate_p_0, _gate_p_1, _gate_p_2) _gate_q_0 {{", " U(pi, 0, pi) _gate_q_0;", "}", "gate x _gate_q_0 {", f" u3_{id(u3_2)}(pi, 0, pi) _gate_q_0;", "}", "bit[2] c;", "qubit[3] q;", "h q[1];", "cx q[1], q[2];", "barrier q[0], q[1], q[2];", "cx q[0], q[1];", "h q[0];", "barrier q[0], q[1], q[2];", "c[0] = measure q[0];", "c[1] = measure q[1];", "barrier q[0], q[1], q[2];", "if (c[1]) {", " x q[2];", "}", "if (c[0]) {", " z q[2];", "}", "", ] ) self.assertEqual( Exporter(includes=[], basis_gates=["cx", "z", "U"]).dumps(qc), expected_qasm, ) def test_teleportation(self): """Teleportation with physical qubits""" qc = QuantumCircuit(3, 2) qc.h(1) qc.cx(1, 2) qc.barrier() qc.cx(0, 1) qc.h(0) qc.barrier() qc.measure([0, 1], [0, 1]) qc.barrier() qc.x(2).c_if(qc.clbits[1], 1) qc.z(2).c_if(qc.clbits[0], 1) transpiled = transpile(qc, initial_layout=[0, 1, 2]) first_h = transpiled.data[0].operation u2 = first_h.definition.data[0].operation u3_1 = u2.definition.data[0].operation first_x = transpiled.data[-2].operation u3_2 = first_x.definition.data[0].operation first_z = transpiled.data[-1].operation u1 = first_z.definition.data[0].operation u3_3 = u1.definition.data[0].operation expected_qasm = "\n".join( [ "OPENQASM 3;", f"gate u3_{id(u3_1)}(_gate_p_0, _gate_p_1, _gate_p_2) _gate_q_0 {{", " U(pi/2, 0, pi) _gate_q_0;", "}", f"gate u2_{id(u2)}(_gate_p_0, _gate_p_1) _gate_q_0 {{", f" u3_{id(u3_1)}(pi/2, 0, pi) _gate_q_0;", "}", "gate h _gate_q_0 {", f" u2_{id(u2)}(0, pi) _gate_q_0;", "}", "gate cx c, t {", " ctrl @ U(pi, 0, pi) c, t;", "}", f"gate u3_{id(u3_2)}(_gate_p_0, _gate_p_1, _gate_p_2) _gate_q_0 {{", " U(pi, 0, pi) _gate_q_0;", "}", "gate x _gate_q_0 {", f" u3_{id(u3_2)}(pi, 0, pi) _gate_q_0;", "}", f"gate u3_{id(u3_3)}(_gate_p_0, _gate_p_1, _gate_p_2) _gate_q_0 {{", " U(0, 0, pi) _gate_q_0;", "}", f"gate u1_{id(u1)}(_gate_p_0) _gate_q_0 {{", f" u3_{id(u3_3)}(0, 0, pi) _gate_q_0;", "}", "gate z _gate_q_0 {", f" u1_{id(u1)}(pi) _gate_q_0;", "}", "bit[2] c;", "h $1;", "cx $1, $2;", "barrier $0, $1, $2;", "cx $0, $1;", "h $0;", "barrier $0, $1, $2;", "c[0] = measure $0;", "c[1] = measure $1;", "barrier $0, $1, $2;", "if (c[1]) {", " x $2;", "}", "if (c[0]) {", " z $2;", "}", "", ] ) self.assertEqual(Exporter(includes=[]).dumps(transpiled), expected_qasm) def test_custom_gate_with_params_bound_main_call(self): """Custom gate with unbound parameters that are bound in the main circuit""" parameter0 = Parameter("p0") parameter1 = Parameter("p1") custom = QuantumCircuit(2, name="custom") custom.rz(parameter0, 0) custom.rz(parameter1 / 2, 1) qr_all_qubits = QuantumRegister(3, "q") qr_r = QuantumRegister(3, "r") circuit = QuantumCircuit(qr_all_qubits, qr_r) circuit.append(custom.to_gate(), [qr_all_qubits[0], qr_r[0]]) circuit.assign_parameters({parameter0: pi, parameter1: pi / 2}, inplace=True) custom_id = id(circuit.data[0].operation) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', f"gate custom_{custom_id}(_gate_p_0, _gate_p_1) _gate_q_0, _gate_q_1 {{", " rz(pi) _gate_q_0;", " rz(pi/4) _gate_q_1;", "}", "qubit[3] q;", "qubit[3] r;", f"custom_{custom_id}(pi, pi/2) q[0], r[0];", "", ] ) self.assertEqual(Exporter().dumps(circuit), expected_qasm) def test_no_include(self): """Test explicit gate declaration (no include)""" q = QuantumRegister(2, "q") circuit = QuantumCircuit(q) circuit.rz(pi / 2, 0) circuit.sx(0) circuit.cx(0, 1) rz = circuit.data[0].operation u1_1 = rz.definition.data[0].operation u3_1 = u1_1.definition.data[0].operation sx = circuit.data[1].operation sdg = sx.definition.data[0].operation u1_2 = sdg.definition.data[0].operation u3_2 = u1_2.definition.data[0].operation h_ = sx.definition.data[1].operation u2_1 = h_.definition.data[0].operation u3_3 = u2_1.definition.data[0].operation expected_qasm = "\n".join( [ "OPENQASM 3;", f"gate u3_{id(u3_1)}(_gate_p_0, _gate_p_1, _gate_p_2) _gate_q_0 {{", " U(0, 0, pi/2) _gate_q_0;", "}", f"gate u1_{id(u1_1)}(_gate_p_0) _gate_q_0 {{", f" u3_{id(u3_1)}(0, 0, pi/2) _gate_q_0;", "}", f"gate rz_{id(rz)}(_gate_p_0) _gate_q_0 {{", f" u1_{id(u1_1)}(pi/2) _gate_q_0;", "}", f"gate u3_{id(u3_2)}(_gate_p_0, _gate_p_1, _gate_p_2) _gate_q_0 {{", " U(0, 0, -pi/2) _gate_q_0;", "}", f"gate u1_{id(u1_2)}(_gate_p_0) _gate_q_0 {{", f" u3_{id(u3_2)}(0, 0, -pi/2) _gate_q_0;", "}", "gate sdg _gate_q_0 {", f" u1_{id(u1_2)}(-pi/2) _gate_q_0;", "}", f"gate u3_{id(u3_3)}(_gate_p_0, _gate_p_1, _gate_p_2) _gate_q_0 {{", " U(pi/2, 0, pi) _gate_q_0;", "}", f"gate u2_{id(u2_1)}(_gate_p_0, _gate_p_1) _gate_q_0 {{", f" u3_{id(u3_3)}(pi/2, 0, pi) _gate_q_0;", "}", "gate h _gate_q_0 {", f" u2_{id(u2_1)}(0, pi) _gate_q_0;", "}", "gate sx _gate_q_0 {", " sdg _gate_q_0;", " h _gate_q_0;", " sdg _gate_q_0;", "}", "gate cx c, t {", " ctrl @ U(pi, 0, pi) c, t;", "}", "qubit[2] q;", f"rz_{id(rz)}(pi/2) q[0];", "sx q[0];", "cx q[0], q[1];", "", ] ) self.assertEqual(Exporter(includes=[]).dumps(circuit), expected_qasm) def test_unusual_conditions(self): """Test that special QASM constructs such as ``measure`` are correctly handled when the Terra instructions have old-style conditions.""" qc = QuantumCircuit(3, 2) qc.h(0) qc.measure(0, 0) qc.measure(1, 1).c_if(0, True) qc.reset([0, 1]).c_if(0, True) with qc.while_loop((qc.clbits[0], True)): qc.break_loop().c_if(0, True) qc.continue_loop().c_if(0, True) # Terra forbids delay and barrier from being conditioned through `c_if`, but in theory they # should work fine in a dynamic-circuits sense (although what a conditional barrier _means_ # is a whole other kettle of fish). delay = Delay(16, "dt") delay.condition = (qc.clbits[0], True) qc.append(delay, [0], []) barrier = Barrier(2) barrier.condition = (qc.clbits[0], True) qc.append(barrier, [0, 1], []) expected = """ OPENQASM 3; include "stdgates.inc"; bit[2] c; qubit[3] q; h q[0]; c[0] = measure q[0]; if (c[0]) { c[1] = measure q[1]; } if (c[0]) { reset q[0]; } if (c[0]) { reset q[1]; } while (c[0]) { if (c[0]) { break; } if (c[0]) { continue; } } if (c[0]) { delay[16dt] q[0]; } if (c[0]) { barrier q[0], q[1]; }""" self.assertEqual(dumps(qc).strip(), expected.strip()) class TestExperimentalFeatures(QiskitTestCase): """Tests of features that are hidden behind experimental flags.""" maxDiff = None def test_switch_forbidden_without_flag(self): """Omitting the feature flag should raise an error.""" case = QuantumCircuit(1) circuit = QuantumCircuit(1, 1) circuit.switch(circuit.clbits[0], [((True, False), case)], [0], []) with self.assertRaisesRegex(QASM3ExporterError, "'switch' statements are not stabilized"): dumps(circuit) def test_switch_clbit(self): """Test that a switch statement can be constructed with a bit as a condition.""" qubit = Qubit() clbit = Clbit() case1 = QuantumCircuit([qubit, clbit]) case1.x(0) case2 = QuantumCircuit([qubit, clbit]) case2.z(0) circuit = QuantumCircuit([qubit, clbit]) circuit.switch(clbit, [(True, case1), (False, case2)], [0], [0]) test = dumps(circuit, experimental=ExperimentalFeatures.SWITCH_CASE_V1) expected = """\ OPENQASM 3; include "stdgates.inc"; bit _bit0; int switch_dummy; qubit _qubit0; switch_dummy = _bit0; switch (switch_dummy) { case 1: { x _qubit0; } break; case 0: { z _qubit0; } break; } """ self.assertEqual(test, expected) def test_switch_register(self): """Test that a switch statement can be constructed with a register as a condition.""" qubit = Qubit() creg = ClassicalRegister(2, "c") case1 = QuantumCircuit([qubit], creg) case1.x(0) case2 = QuantumCircuit([qubit], creg) case2.y(0) case3 = QuantumCircuit([qubit], creg) case3.z(0) circuit = QuantumCircuit([qubit], creg) circuit.switch(creg, [(0, case1), (1, case2), (2, case3)], [0], circuit.clbits) test = dumps(circuit, experimental=ExperimentalFeatures.SWITCH_CASE_V1) expected = """\ OPENQASM 3; include "stdgates.inc"; bit[2] c; int switch_dummy; qubit _qubit0; switch_dummy = c; switch (switch_dummy) { case 0: { x _qubit0; } break; case 1: { y _qubit0; } break; case 2: { z _qubit0; } break; } """ self.assertEqual(test, expected) def test_switch_with_default(self): """Test that a switch statement can be constructed with a default case at the end.""" qubit = Qubit() creg = ClassicalRegister(2, "c") case1 = QuantumCircuit([qubit], creg) case1.x(0) case2 = QuantumCircuit([qubit], creg) case2.y(0) case3 = QuantumCircuit([qubit], creg) case3.z(0) circuit = QuantumCircuit([qubit], creg) circuit.switch(creg, [(0, case1), (1, case2), (CASE_DEFAULT, case3)], [0], circuit.clbits) test = dumps(circuit, experimental=ExperimentalFeatures.SWITCH_CASE_V1) expected = """\ OPENQASM 3; include "stdgates.inc"; bit[2] c; int switch_dummy; qubit _qubit0; switch_dummy = c; switch (switch_dummy) { case 0: { x _qubit0; } break; case 1: { y _qubit0; } break; default: { z _qubit0; } break; } """ self.assertEqual(test, expected) def test_switch_multiple_cases_to_same_block(self): """Test that it is possible to add multiple cases that apply to the same block, if they are given as a compound value. This is an allowed special case of block fall-through.""" qubit = Qubit() creg = ClassicalRegister(2, "c") case1 = QuantumCircuit([qubit], creg) case1.x(0) case2 = QuantumCircuit([qubit], creg) case2.y(0) circuit = QuantumCircuit([qubit], creg) circuit.switch(creg, [(0, case1), ((1, 2), case2)], [0], circuit.clbits) test = dumps(circuit, experimental=ExperimentalFeatures.SWITCH_CASE_V1) expected = """\ OPENQASM 3; include "stdgates.inc"; bit[2] c; int switch_dummy; qubit _qubit0; switch_dummy = c; switch (switch_dummy) { case 0: { x _qubit0; } break; case 1: case 2: { y _qubit0; } break; } """ self.assertEqual(test, expected) def test_multiple_switches_dont_clash_on_dummy(self): """Test that having more than one switch statement in the circuit doesn't cause naming clashes in the dummy integer value used.""" qubit = Qubit() creg = ClassicalRegister(2, "switch_dummy") case1 = QuantumCircuit([qubit], creg) case1.x(0) case2 = QuantumCircuit([qubit], creg) case2.y(0) circuit = QuantumCircuit([qubit], creg) circuit.switch(creg, [(0, case1), ((1, 2), case2)], [0], circuit.clbits) circuit.switch(creg, [(0, case1), ((1, 2), case2)], [0], circuit.clbits) test = dumps(circuit, experimental=ExperimentalFeatures.SWITCH_CASE_V1) expected = """\ OPENQASM 3; include "stdgates.inc"; bit[2] switch_dummy; int switch_dummy__generated0; int switch_dummy__generated1; qubit _qubit0; switch_dummy__generated0 = switch_dummy; switch (switch_dummy__generated0) { case 0: { x _qubit0; } break; case 1: case 2: { y _qubit0; } break; } switch_dummy__generated1 = switch_dummy; switch (switch_dummy__generated1) { case 0: { x _qubit0; } break; case 1: case 2: { y _qubit0; } break; } """ self.assertEqual(test, expected) def test_switch_nested_in_if(self): """Test that the switch statement works when in a nested scope, including the dummy classical variable being declared globally. This isn't necessary in the OQ3 language, but it is universally valid and the IBM QSS stack prefers that. They're our primary consumers of OQ3 strings, so it's best to play nicely with them.""" qubit = Qubit() creg = ClassicalRegister(2, "c") case1 = QuantumCircuit([qubit], creg) case1.x(0) case2 = QuantumCircuit([qubit], creg) case2.y(0) body = QuantumCircuit([qubit], creg) body.switch(creg, [(0, case1), ((1, 2), case2)], [0], body.clbits) circuit = QuantumCircuit([qubit], creg) circuit.if_else((creg, 1), body.copy(), body, [0], body.clbits) test = dumps(circuit, experimental=ExperimentalFeatures.SWITCH_CASE_V1) expected = """\ OPENQASM 3; include "stdgates.inc"; bit[2] c; int switch_dummy; int switch_dummy__generated0; qubit _qubit0; if (c == 1) { switch_dummy = c; switch (switch_dummy) { case 0: { x _qubit0; } break; case 1: case 2: { y _qubit0; } break; } } else { switch_dummy__generated0 = c; switch (switch_dummy__generated0) { case 0: { x _qubit0; } break; case 1: case 2: { y _qubit0; } break; } } """ self.assertEqual(test, expected) def test_expr_target(self): """Simple test that the target of `switch` can be `Expr` nodes.""" bits = [Qubit(), Clbit()] cr = ClassicalRegister(2, "cr") case0 = QuantumCircuit(1) case0.x(0) case1 = QuantumCircuit(1) case1.x(0) qc = QuantumCircuit(bits, cr) qc.switch(expr.logic_not(bits[1]), [(False, case0)], [0], []) qc.switch(expr.bit_and(cr, 3), [(3, case1)], [0], []) expected = """\ OPENQASM 3; include "stdgates.inc"; bit _bit0; bit[2] cr; int switch_dummy; int switch_dummy__generated0; qubit _qubit0; switch_dummy = !_bit0; switch (switch_dummy) { case 0: { x _qubit0; } break; } switch_dummy__generated0 = cr & 3; switch (switch_dummy__generated0) { case 3: { x _qubit0; } break; } """ test = dumps(qc, experimental=ExperimentalFeatures.SWITCH_CASE_V1) self.assertEqual(test, expected) @ddt class TestQASM3ExporterFailurePaths(QiskitTestCase): """Tests of the failure paths for the exporter.""" def test_disallow_overlapping_classical_registers_if_no_aliasing(self): """Test that the exporter rejects circuits with a classical bit in more than one register if the ``alias_classical_registers`` option is set false.""" qubits = [Qubit() for _ in [None] * 3] clbits = [Clbit() for _ in [None] * 5] registers = [ClassicalRegister(bits=clbits[:4]), ClassicalRegister(bits=clbits[1:])] qc = QuantumCircuit(qubits, *registers) exporter = Exporter(alias_classical_registers=False) with self.assertRaisesRegex(QASM3ExporterError, r"classical registers .* overlap"): exporter.dumps(qc) @data([1, 2, 1.1], [1j, 2]) def test_disallow_for_loops_with_non_integers(self, indices): """Test that the exporter rejects ``for`` loops that include non-integer values in their index sets.""" loop_body = QuantumCircuit() qc = QuantumCircuit(2, 2) qc.for_loop(indices, None, loop_body, [], []) exporter = Exporter() with self.assertRaisesRegex( QASM3ExporterError, r"The values in QASM 3 'for' loops must all be integers.*" ): exporter.dumps(qc) def test_disallow_custom_subroutine_with_parameters(self): """Test that the exporter throws an error instead of trying to export a subroutine with parameters, while this is not supported.""" subroutine = QuantumCircuit(1) subroutine.rx(Parameter("x"), 0) qc = QuantumCircuit(1) qc.append(subroutine.to_instruction(), [0], []) exporter = Exporter() with self.assertRaisesRegex( QASM3ExporterError, "Exporting non-unitary instructions is not yet supported" ): exporter.dumps(qc) def test_disallow_opaque_instruction(self): """Test that the exporter throws an error instead of trying to export something into a ``defcal`` block, while this is not supported.""" qc = QuantumCircuit(1) qc.append(Instruction("opaque", 1, 0, []), [0], []) exporter = Exporter() with self.assertRaisesRegex( QASM3ExporterError, "Exporting opaque instructions .* is not yet supported" ): exporter.dumps(qc)
https://github.com/swe-train/qiskit__qiskit
swe-train
# 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. # pylint: disable=missing-module-docstring,missing-class-docstring,missing-function-docstring import itertools import math import sys import ddt import qiskit.qasm2 from qiskit.test import QiskitTestCase @ddt.ddt class TestSimple(QiskitTestCase): def test_unary_constants(self): program = "qreg q[1]; U(-(0.5 + 0.5), +(+1 - 2), -+-+2) q[0];" parsed = qiskit.qasm2.loads(program) expected = [-1.0, -1.0, 2.0] self.assertEqual(list(parsed.data[0].operation.params), expected) def test_unary_symbolic(self): program = """ gate u(a, b, c) q { U(-(a + a), +(+b - c), -+-+c) q; } qreg q[1]; u(0.5, 1.0, 2.0) q[0]; """ parsed = qiskit.qasm2.loads(program) expected = [-1.0, -1.0, 2.0] actual = [float(x) for x in parsed.data[0].operation.definition.data[0].operation.params] self.assertEqual(list(actual), expected) @ddt.data( ("+", lambda a, b: a + b), ("-", lambda a, b: a - b), ("*", lambda a, b: a * b), ("/", lambda a, b: a / b), ("^", lambda a, b: a**b), ) @ddt.unpack def test_binary_constants(self, str_op, py_op): program = f"qreg q[1]; U(0.25{str_op}0.5, 1.0{str_op}0.5, 3.2{str_op}-0.8) q[0];" parsed = qiskit.qasm2.loads(program) expected = [py_op(0.25, 0.5), py_op(1.0, 0.5), py_op(3.2, -0.8)] # These should be bit-for-bit exact. self.assertEqual(list(parsed.data[0].operation.params), expected) @ddt.data( ("+", lambda a, b: a + b), ("-", lambda a, b: a - b), ("*", lambda a, b: a * b), ("/", lambda a, b: a / b), ("^", lambda a, b: a**b), ) @ddt.unpack def test_binary_symbolic(self, str_op, py_op): program = f""" gate u(a, b, c) q {{ U(a {str_op} b, a {str_op} (b {str_op} c), 0.0) q; }} qreg q[1]; u(1.0, 2.0, 3.0) q[0]; """ parsed = qiskit.qasm2.loads(program) outer = [1.0, 2.0, 3.0] abstract_op = parsed.data[0].operation self.assertEqual(list(abstract_op.params), outer) expected = [py_op(1.0, 2.0), py_op(1.0, py_op(2.0, 3.0)), 0.0] actual = [float(x) for x in abstract_op.definition.data[0].operation.params] self.assertEqual(list(actual), expected) @ddt.data( ("cos", math.cos), ("exp", math.exp), ("ln", math.log), ("sin", math.sin), ("sqrt", math.sqrt), ("tan", math.tan), ) @ddt.unpack def test_function_constants(self, function_str, function_py): program = f"qreg q[1]; U({function_str}(0.5),{function_str}(1.0),{function_str}(pi)) q[0];" parsed = qiskit.qasm2.loads(program) expected = [function_py(0.5), function_py(1.0), function_py(math.pi)] # These should be bit-for-bit exact. self.assertEqual(list(parsed.data[0].operation.params), expected) @ddt.data( ("cos", math.cos), ("exp", math.exp), ("ln", math.log), ("sin", math.sin), ("sqrt", math.sqrt), ("tan", math.tan), ) @ddt.unpack def test_function_symbolic(self, function_str, function_py): program = f""" gate u(a, b, c) q {{ U({function_str}(a), {function_str}(b), {function_str}(c)) q; }} qreg q[1]; u(0.5, 1.0, pi) q[0]; """ parsed = qiskit.qasm2.loads(program) outer = [0.5, 1.0, math.pi] abstract_op = parsed.data[0].operation self.assertEqual(list(abstract_op.params), outer) expected = [function_py(x) for x in outer] actual = [float(x) for x in abstract_op.definition.data[0].operation.params] self.assertEqual(list(actual), expected) class TestPrecedenceAssociativity(QiskitTestCase): def test_precedence(self): # OQ3's precedence rules are the same as Python's, so we can effectively just eval. expr = " 1.0 + 2.0 * -3.0 ^ 1.5 - 0.5 / +0.25" expected = 1.0 + 2.0 * -(3.0**1.5) - 0.5 / +0.25 program = f"qreg q[1]; U({expr}, 0, 0) q[0];" parsed = qiskit.qasm2.loads(program) self.assertEqual(parsed.data[0].operation.params[0], expected) def test_addition_left(self): # `eps` is the smallest floating-point value such that `1 + eps != 1`. That means that if # addition is correctly parsed and resolved as left-associative, then the first parameter # should first calculate `1 + (eps / 2)`, which will be 1, and then the same again, whereas # the second will do `(eps / 2) + (eps / 2) = eps`, then `eps + 1` will be different. eps = sys.float_info.epsilon program = f"qreg q[1]; U(1 + {eps / 2} + {eps / 2}, {eps / 2} + {eps / 2} + 1, 0) q[0];" parsed = qiskit.qasm2.loads(program) self.assertNotEqual(1.0 + eps, 1.0) # Sanity check for the test. self.assertEqual(list(parsed.data[0].operation.params), [1.0, 1.0 + eps, 0.0]) def test_multiplication_left(self): # A similar principle to the epsilon test for addition; if multiplication associates right, # then `(0.5 * 2.0 * fmax)` is `inf`, otherwise it's `fmax`. fmax = sys.float_info.max program = f"qreg q[1]; U({fmax} * 0.5 * 2.0, 2.0 * 0.5 * {fmax}, 2.0 * {fmax} * 0.5) q[0];" parsed = qiskit.qasm2.loads(program) self.assertEqual(list(parsed.data[0].operation.params), [fmax, fmax, math.inf]) def test_subtraction_left(self): # If subtraction associated right, we'd accidentally get 2. program = "qreg q[1]; U(2.0 - 1.0 - 1.0, 0, 0) q[0];" parsed = qiskit.qasm2.loads(program) self.assertEqual(list(parsed.data[0].operation.params), [0.0, 0.0, 0.0]) def test_division_left(self): # If division associated right, we'd accidentally get 4. program = "qreg q[1]; U(4.0 / 2.0 / 2.0, 0, 0) q[0];" parsed = qiskit.qasm2.loads(program) self.assertEqual(list(parsed.data[0].operation.params), [1.0, 0.0, 0.0]) def test_power_right(self): # If the power operator associated left, we'd accidentally get 64 instead. program = "qreg q[1]; U(2.0 ^ 3.0 ^ 2.0, 0, 0) q[0];" parsed = qiskit.qasm2.loads(program) self.assertEqual(list(parsed.data[0].operation.params), [512.0, 0.0, 0.0]) class TestCustomClassical(QiskitTestCase): def test_evaluation_order(self): """We should be evaluating all functions, including custom user ones the exact number of times we expect, and left-to-right in parameter lists.""" # pylint: disable=invalid-name order = itertools.count() def f(): return next(order) program = """ qreg q[1]; U(f(), 2 * f() + f(), atan2(f(), f()) - f()) q[0]; """ parsed = qiskit.qasm2.loads( program, custom_classical=[ qiskit.qasm2.CustomClassical("f", 0, f), qiskit.qasm2.CustomClassical("atan2", 2, math.atan2), ], ) self.assertEqual( list(parsed.data[0].operation.params), [0, 2 * 1 + 2, math.atan2(3, 4) - 5] ) self.assertEqual(next(order), 6) @ddt.ddt class TestErrors(QiskitTestCase): @ddt.data("0.0", "(1.0 - 1.0)") def test_refuses_to_divide_by_zero(self, denom): program = f"qreg q[1]; U(2.0 / {denom}, 0.0, 0.0) q[0];" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "divide by zero"): qiskit.qasm2.loads(program) program = f"gate rx(a) q {{ U(a / {denom}, 0.0, 0.0) q; }}" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "divide by zero"): qiskit.qasm2.loads(program) @ddt.data("0.0", "1.0 - 1.0", "-2.0", "2.0 - 3.0") def test_refuses_to_ln_non_positive(self, operand): program = f"qreg q[1]; U(ln({operand}), 0.0, 0.0) q[0];" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "ln of non-positive"): qiskit.qasm2.loads(program) program = f"gate rx(a) q {{ U(a + ln({operand}), 0.0, 0.0) q; }}" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "ln of non-positive"): qiskit.qasm2.loads(program) @ddt.data("-2.0", "2.0 - 3.0") def test_refuses_to_sqrt_negative(self, operand): program = f"qreg q[1]; U(sqrt({operand}), 0.0, 0.0) q[0];" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "sqrt of negative"): qiskit.qasm2.loads(program) program = f"gate rx(a) q {{ U(a + sqrt({operand}), 0.0, 0.0) q; }}" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "sqrt of negative"): qiskit.qasm2.loads(program) @ddt.data("*", "/", "^") def test_cannot_use_nonunary_operators_in_unary_position(self, operator): program = f"qreg q[1]; U({operator}1.0, 0.0, 0.0) q[0];" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "not a valid unary operator"): qiskit.qasm2.loads(program) @ddt.data("+", "-", "*", "/", "^") def test_missing_binary_operand_errors(self, operator): program = f"qreg q[1]; U(1.0 {operator}, 0.0, 0.0) q[0];" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "missing operand"): qiskit.qasm2.loads(program) program = f"qreg q[1]; U((1.0 {operator}), 0.0, 0.0) q[0];" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "missing operand"): qiskit.qasm2.loads(program) def test_parenthesis_must_be_closed(self): program = "qreg q[1]; U((1 + 1 2), 3, 2) q[0];" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "needed a closing parenthesis"): qiskit.qasm2.loads(program) def test_premature_right_parenthesis(self): program = "qreg q[1]; U(sin(), 0.0, 0.0) q[0];" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "did not find an .* expression"): qiskit.qasm2.loads(program)
https://github.com/swe-train/qiskit__qiskit
swe-train
# 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. # pylint: disable=missing-module-docstring,missing-class-docstring,missing-function-docstring import ddt import qiskit.qasm2 from qiskit.test import QiskitTestCase @ddt.ddt class TestLexer(QiskitTestCase): # Most of the lexer is fully exercised in the parser tests. These tests here are really mopping # up some error messages and whatnot that might otherwise be missed. def test_pathological_formatting(self): # This is deliberately _terribly_ formatted, included multiple blanks lines in quick # succession and comments in places you really wouldn't expect to see comments. program = """ OPENQASM // do we really need a comment here? 2.0//and another comment very squished up ; include // this line introduces a file import "qelib1.inc" // this is the file imported ; // this is a semicolon gate // we're making a gate bell( // void, with loose parenthesis in comment ) ) a,// b{h a;cx a //,,,, ,b;} qreg // a quantum register q [ // a square bracket 2];bell q[0],// q[1];creg c[2];measure q->c;""" parsed = qiskit.qasm2.loads(program) expected_unrolled = qiskit.QuantumCircuit( qiskit.QuantumRegister(2, "q"), qiskit.ClassicalRegister(2, "c") ) expected_unrolled.h(0) expected_unrolled.cx(0, 1) expected_unrolled.measure([0, 1], [0, 1]) self.assertEqual(parsed.decompose(), expected_unrolled) @ddt.data("0.25", "00.25", "2.5e-1", "2.5e-01", "0.025E+1", ".25", ".025e1", "25e-2") def test_float_lexes(self, number): program = f"qreg q[1]; U({number}, 0, 0) q[0];" parsed = qiskit.qasm2.loads(program) self.assertEqual(list(parsed.data[0].operation.params), [0.25, 0, 0]) def test_no_decimal_float_rejected_in_strict_mode(self): with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, r"\[strict\] all floats must include a decimal point", ): qiskit.qasm2.loads("OPENQASM 2.0; qreg q[1]; U(25e-2, 0, 0) q[0];", strict=True) @ddt.data("", "qre", "cre", ".") def test_non_ascii_bytes_error(self, prefix): token = f"{prefix}\xff" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "encountered a non-ASCII byte"): qiskit.qasm2.loads(token) def test_integers_cannot_start_with_zero(self): with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, "integers cannot have leading zeroes" ): qiskit.qasm2.loads("0123") @ddt.data("", "+", "-") def test_float_exponents_must_have_a_digit(self, sign): token = f"12.34e{sign}" with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, "needed to see an integer exponent" ): qiskit.qasm2.loads(token) def test_non_builtins_cannot_be_capitalised(self): with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, "identifiers cannot start with capital" ): qiskit.qasm2.loads("Qubit") def test_unterminated_filename_is_invalid(self): with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, "unexpected end-of-file while lexing string literal" ): qiskit.qasm2.loads('include "qelib1.inc') def test_filename_with_linebreak_is_invalid(self): with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, "unexpected line break while lexing string literal" ): qiskit.qasm2.loads('include "qe\nlib1.inc";') def test_strict_single_quoted_path_rejected(self): with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, r"\[strict\] paths must be in double quotes" ): qiskit.qasm2.loads("OPENQASM 2.0; include 'qelib1.inc';", strict=True) def test_version_must_have_word_boundary_after(self): with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, r"expected a word boundary after a version" ): qiskit.qasm2.loads("OPENQASM 2a;") with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, r"expected a word boundary after a version" ): qiskit.qasm2.loads("OPENQASM 2.0a;") def test_no_boundary_float_in_version_position(self): with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, r"expected a word boundary after a float" ): qiskit.qasm2.loads("OPENQASM .5a;") with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, r"expected a word boundary after a float" ): qiskit.qasm2.loads("OPENQASM 0.2e1a;") def test_integers_must_have_word_boundaries_after(self): with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, r"expected a word boundary after an integer" ): qiskit.qasm2.loads("OPENQASM 2.0; qreg q[2a];") def test_floats_must_have_word_boundaries_after(self): with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, r"expected a word boundary after a float" ): qiskit.qasm2.loads("OPENQASM 2.0; qreg q[1]; U(2.0a, 0, 0) q[0];") def test_single_equals_is_rejected(self): with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, r"single equals '=' is never valid" ): qiskit.qasm2.loads("if (a = 2) U(0, 0, 0) q[0];") def test_bare_dot_is_not_valid_float(self): with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, r"expected a numeric fractional part" ): qiskit.qasm2.loads("qreg q[0]; U(2 + ., 0, 0) q[0];") def test_invalid_token(self): with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, r"encountered '!', which doesn't match" ): qiskit.qasm2.loads("!")
https://github.com/swe-train/qiskit__qiskit
swe-train
# 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. # pylint: disable=missing-module-docstring,missing-class-docstring,missing-function-docstring import enum import math import ddt import qiskit.qasm2 from qiskit.circuit import Gate, library as lib from qiskit.test import QiskitTestCase from test import combine # pylint: disable=wrong-import-order # We need to use this enum a _bunch_ of times, so let's not give it a long name. # pylint: disable=invalid-name class T(enum.Enum): # This is a deliberately stripped-down list that doesn't include most of the expression-specific # tokens, because we don't want to complicate matters with those in tests of the general parser # errors. We test the expression subparser elsewhere. OPENQASM = "OPENQASM" BARRIER = "barrier" CREG = "creg" GATE = "gate" IF = "if" INCLUDE = "include" MEASURE = "measure" OPAQUE = "opaque" QREG = "qreg" RESET = "reset" PI = "pi" ARROW = "->" EQUALS = "==" SEMICOLON = ";" COMMA = "," LPAREN = "(" RPAREN = ")" LBRACKET = "[" RBRACKET = "]" LBRACE = "{" RBRACE = "}" ID = "q" REAL = "1.5" INTEGER = "1" FILENAME = '"qelib1.inc"' def bad_token_parametrisation(): """Generate the test cases for the "bad token" tests; this makes a sequence of OpenQASM 2 statements, then puts various invalid tokens after them to verify that the parser correctly throws an error on them.""" token_set = frozenset(T) def without(*tokens): return token_set - set(tokens) # ddt isn't a particularly great parametriser - it'll only correctly unpack tuples and lists in # the way we really want, but if we want to control the test id, we also have to set `__name__` # which isn't settable on either of those. We can't use unpack, then, so we just need a class # to pass. class BadTokenCase: def __init__(self, statement, disallowed, name=None): self.statement = statement self.disallowed = disallowed self.__name__ = name for statement, disallowed in [ # This should only include stopping points where the next token is somewhat fixed; in # places where there's a real decision to be made (such as number of qubits in a gate, # or the statement type in a gate body), there should be a better error message. # # There's a large subset of OQ2 that's reducible to a regular language, so we _could_ # define that, build a DFA for it, and use that to very quickly generate a complete set # of tests. That would be more complex to read and verify for correctness, though. ( "", without( T.OPENQASM, T.ID, T.INCLUDE, T.OPAQUE, T.GATE, T.QREG, T.CREG, T.IF, T.RESET, T.BARRIER, T.MEASURE, T.SEMICOLON, ), ), ("OPENQASM", without(T.REAL, T.INTEGER)), ("OPENQASM 2.0", without(T.SEMICOLON)), ("include", without(T.FILENAME)), ('include "qelib1.inc"', without(T.SEMICOLON)), ("opaque", without(T.ID)), ("opaque bell", without(T.LPAREN, T.ID, T.SEMICOLON)), ("opaque bell (", without(T.ID, T.RPAREN)), ("opaque bell (a", without(T.COMMA, T.RPAREN)), ("opaque bell (a,", without(T.ID, T.RPAREN)), ("opaque bell (a, b", without(T.COMMA, T.RPAREN)), ("opaque bell (a, b)", without(T.ID, T.SEMICOLON)), ("opaque bell (a, b) q1", without(T.COMMA, T.SEMICOLON)), ("opaque bell (a, b) q1,", without(T.ID, T.SEMICOLON)), ("opaque bell (a, b) q1, q2", without(T.COMMA, T.SEMICOLON)), ("gate", without(T.ID)), ("gate bell (", without(T.ID, T.RPAREN)), ("gate bell (a", without(T.COMMA, T.RPAREN)), ("gate bell (a,", without(T.ID, T.RPAREN)), ("gate bell (a, b", without(T.COMMA, T.RPAREN)), ("gate bell (a, b) q1", without(T.COMMA, T.LBRACE)), ("gate bell (a, b) q1,", without(T.ID, T.LBRACE)), ("gate bell (a, b) q1, q2", without(T.COMMA, T.LBRACE)), ("qreg", without(T.ID)), ("qreg reg", without(T.LBRACKET)), ("qreg reg[", without(T.INTEGER)), ("qreg reg[5", without(T.RBRACKET)), ("qreg reg[5]", without(T.SEMICOLON)), ("creg", without(T.ID)), ("creg reg", without(T.LBRACKET)), ("creg reg[", without(T.INTEGER)), ("creg reg[5", without(T.RBRACKET)), ("creg reg[5]", without(T.SEMICOLON)), ("CX", without(T.LPAREN, T.ID, T.SEMICOLON)), ("CX(", without(T.PI, T.INTEGER, T.REAL, T.ID, T.LPAREN, T.RPAREN)), ("CX()", without(T.ID, T.SEMICOLON)), ("CX q", without(T.LBRACKET, T.COMMA, T.SEMICOLON)), ("CX q[", without(T.INTEGER)), ("CX q[0", without(T.RBRACKET)), ("CX q[0]", without(T.COMMA, T.SEMICOLON)), ("CX q[0],", without(T.ID, T.SEMICOLON)), ("CX q[0], q", without(T.LBRACKET, T.COMMA, T.SEMICOLON)), # No need to repeatedly "every" possible number of arguments. ("measure", without(T.ID)), ("measure q", without(T.LBRACKET, T.ARROW)), ("measure q[", without(T.INTEGER)), ("measure q[0", without(T.RBRACKET)), ("measure q[0]", without(T.ARROW)), ("measure q[0] ->", without(T.ID)), ("measure q[0] -> c", without(T.LBRACKET, T.SEMICOLON)), ("measure q[0] -> c[", without(T.INTEGER)), ("measure q[0] -> c[0", without(T.RBRACKET)), ("measure q[0] -> c[0]", without(T.SEMICOLON)), ("reset", without(T.ID)), ("reset q", without(T.LBRACKET, T.SEMICOLON)), ("reset q[", without(T.INTEGER)), ("reset q[0", without(T.RBRACKET)), ("reset q[0]", without(T.SEMICOLON)), ("barrier", without(T.ID, T.SEMICOLON)), ("barrier q", without(T.LBRACKET, T.COMMA, T.SEMICOLON)), ("barrier q[", without(T.INTEGER)), ("barrier q[0", without(T.RBRACKET)), ("barrier q[0]", without(T.COMMA, T.SEMICOLON)), ("if", without(T.LPAREN)), ("if (", without(T.ID)), ("if (cond", without(T.EQUALS)), ("if (cond ==", without(T.INTEGER)), ("if (cond == 0", without(T.RPAREN)), ("if (cond == 0)", without(T.ID, T.RESET, T.MEASURE)), ]: for token in disallowed: yield BadTokenCase(statement, token.value, name=f"'{statement}'-{token.name.lower()}") def eof_parametrisation(): for tokens in [ ("OPENQASM", "2.0", ";"), ("include", '"qelib1.inc"', ";"), ("opaque", "bell", "(", "a", ",", "b", ")", "q1", ",", "q2", ";"), ("gate", "bell", "(", "a", ",", "b", ")", "q1", ",", "q2", "{", "}"), ("qreg", "qr", "[", "5", "]", ";"), ("creg", "cr", "[", "5", "]", ";"), ("CX", "(", ")", "q", "[", "0", "]", ",", "q", "[", "1", "]", ";"), ("measure", "q", "[", "0", "]", "->", "c", "[", "0", "]", ";"), ("reset", "q", "[", "0", "]", ";"), ("barrier", "q", ";"), # No need to test every combination of `if`, really. ("if", "(", "cond", "==", "0", ")", "CX q[0], q[1];"), ]: prefix = "" for token in tokens[:-1]: prefix = f"{prefix} {token}".strip() yield prefix @ddt.ddt class TestIncompleteStructure(QiskitTestCase): PRELUDE = "OPENQASM 2.0; qreg q[5]; creg c[5]; creg cond[1];" @ddt.idata(bad_token_parametrisation()) def test_bad_token(self, case): """Test that the parser raises an error when an incorrect token is given.""" statement = case.statement disallowed = case.disallowed prelude = "" if statement.startswith("OPENQASM") else self.PRELUDE full = f"{prelude} {statement} {disallowed}" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "needed .*, but instead"): qiskit.qasm2.loads(full) @ddt.idata(eof_parametrisation()) def test_eof(self, statement): """Test that the parser raises an error when the end-of-file is reached instead of a token that is required.""" prelude = "" if statement.startswith("OPENQASM") else self.PRELUDE full = f"{prelude} {statement}" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "unexpected end-of-file"): qiskit.qasm2.loads(full) def test_loading_directory(self): """Test that the correct error is raised when a file fails to open.""" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "failed to read"): qiskit.qasm2.load(".") class TestVersion(QiskitTestCase): def test_invalid_version(self): program = "OPENQASM 3.0;" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "can only handle OpenQASM 2.0"): qiskit.qasm2.loads(program) program = "OPENQASM 2.1;" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "can only handle OpenQASM 2.0"): qiskit.qasm2.loads(program) program = "OPENQASM 20.e-1;" with self.assertRaises(qiskit.qasm2.QASM2ParseError): qiskit.qasm2.loads(program) def test_openqasm_must_be_first_statement(self): program = "qreg q[0]; OPENQASM 2.0;" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "only the first statement"): qiskit.qasm2.loads(program) @ddt.ddt class TestScoping(QiskitTestCase): def test_register_use_before_definition(self): program = "CX after[0], after[1]; qreg after[2];" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "not defined in this scope"): qiskit.qasm2.loads(program) program = "qreg q[2]; measure q[0] -> c[0]; creg c[2];" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "not defined in this scope"): qiskit.qasm2.loads(program) @combine( definer=["qreg reg[2];", "creg reg[2];", "gate reg a {}", "opaque reg a;"], bad_definer=["qreg reg[2];", "creg reg[2];"], ) def test_register_already_defined(self, definer, bad_definer): program = f"{definer} {bad_definer}" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "already defined"): qiskit.qasm2.loads(program) def test_qelib1_not_implicit(self): program = """ OPENQASM 2.0; qreg q[2]; cx q[0], q[1]; """ with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'cx' is not defined"): qiskit.qasm2.loads(program) def test_cannot_access_gates_before_definition(self): program = """ qreg q[2]; cx q[0], q[1]; gate cx a, b { CX a, b; } """ with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'cx' is not defined"): qiskit.qasm2.loads(program) def test_cannot_access_gate_recursively(self): program = """ gate cx a, b { cx a, b; } """ with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'cx' is not defined"): qiskit.qasm2.loads(program) def test_cannot_access_qubits_from_previous_gate(self): program = """ gate cx a, b { CX a, b; } gate other c { CX a, b; } """ with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'a' is not defined"): qiskit.qasm2.loads(program) def test_cannot_access_parameters_from_previous_gate(self): program = """ gate first(a, b) q { U(a, 0, b) q; } gate second q { U(a, 0, b) q; } """ with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, "'a' is not a parameter.*defined" ): qiskit.qasm2.loads(program) def test_cannot_access_quantum_registers_within_gate(self): program = """ qreg q[2]; gate my_gate a { CX a, q; } """ with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'q' is a quantum register"): qiskit.qasm2.loads(program) def test_parameters_not_defined_outside_gate(self): program = """ gate my_gate(a) q {} qreg qr[2]; U(a, 0, 0) qr; """ with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, "'a' is not a parameter.*defined" ): qiskit.qasm2.loads(program) def test_qubits_not_defined_outside_gate(self): program = """ gate my_gate(a) q {} U(0, 0, 0) q; """ with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'q' is not defined"): qiskit.qasm2.loads(program) @ddt.data('include "qelib1.inc";', "gate h q { }") def test_gates_cannot_redefine(self, definer): program = f"{definer} gate h q {{ }}" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "already defined"): qiskit.qasm2.loads(program) def test_cannot_use_undeclared_register_conditional(self): program = "qreg q[1]; if (c == 0) U(0, 0, 0) q[0];" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "not defined"): qiskit.qasm2.loads(program) @ddt.ddt class TestTyping(QiskitTestCase): @ddt.data( "CX q[0], U;", "measure U -> c[0];", "measure q[0] -> U;", "reset U;", "barrier U;", "if (U == 0) CX q[0], q[1];", "gate my_gate a { U(0, 0, 0) U; }", ) def test_cannot_use_gates_incorrectly(self, usage): program = f"qreg q[2]; creg c[2]; {usage}" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'U' is a gate"): qiskit.qasm2.loads(program) @ddt.data( "measure q[0] -> q[1];", "if (q == 0) CX q[0], q[1];", "q q[0], q[1];", "gate my_gate a { U(0, 0, 0) q; }", ) def test_cannot_use_qregs_incorrectly(self, usage): program = f"qreg q[2]; creg c[2]; {usage}" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'q' is a quantum register"): qiskit.qasm2.loads(program) @ddt.data( "CX q[0], c[1];", "measure c[0] -> c[1];", "reset c[0];", "barrier c[0];", "c q[0], q[1];", "gate my_gate a { U(0, 0, 0) c; }", ) def test_cannot_use_cregs_incorrectly(self, usage): program = f"qreg q[2]; creg c[2]; {usage}" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'c' is a classical register"): qiskit.qasm2.loads(program) def test_cannot_use_parameters_incorrectly(self): program = "gate my_gate(p) q { CX p, q; }" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'p' is a parameter"): qiskit.qasm2.loads(program) def test_cannot_use_qubits_incorrectly(self): program = "gate my_gate(p) q { U(q, q, q) q; }" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'q' is a gate qubit"): qiskit.qasm2.loads(program) @ddt.data(("h", 0), ("h", 2), ("CX", 0), ("CX", 1), ("CX", 3), ("ccx", 2), ("ccx", 4)) @ddt.unpack def test_gates_accept_only_valid_number_qubits(self, gate, bad_count): arguments = ", ".join(f"q[{i}]" for i in range(bad_count)) program = f'include "qelib1.inc"; qreg q[5];\n{gate} {arguments};' with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "takes .* quantum arguments?"): qiskit.qasm2.loads(program) @ddt.data(("U", 2), ("U", 4), ("rx", 0), ("rx", 2), ("u3", 1)) @ddt.unpack def test_gates_accept_only_valid_number_parameters(self, gate, bad_count): arguments = ", ".join("0" for _ in [None] * bad_count) program = f'include "qelib1.inc"; qreg q[5];\n{gate}({arguments}) q[0];' with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "takes .* parameters?"): qiskit.qasm2.loads(program) @ddt.ddt class TestGateDefinition(QiskitTestCase): def test_no_zero_qubit(self): program = "gate zero {}" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "gates must act on at least one"): qiskit.qasm2.loads(program) program = "gate zero(a) {}" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "gates must act on at least one"): qiskit.qasm2.loads(program) def test_no_zero_qubit_opaque(self): program = "opaque zero;" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "gates must act on at least one"): qiskit.qasm2.loads(program) program = "opaque zero(a);" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "gates must act on at least one"): qiskit.qasm2.loads(program) def test_cannot_subscript_qubit(self): program = """ gate my_gate a { CX a[0], a[1]; } """ with self.assertRaises(qiskit.qasm2.QASM2ParseError): qiskit.qasm2.loads(program) def test_cannot_repeat_parameters(self): program = "gate my_gate(a, a) q {}" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "already defined"): qiskit.qasm2.loads(program) def test_cannot_repeat_qubits(self): program = "gate my_gate a, a {}" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "already defined"): qiskit.qasm2.loads(program) def test_qubit_cannot_shadow_parameter(self): program = "gate my_gate(a) a {}" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "already defined"): qiskit.qasm2.loads(program) @ddt.data("measure q -> c;", "reset q", "if (c == 0) U(0, 0, 0) q;", "gate my_x q {}") def test_definition_cannot_contain_nonunitary(self, statement): program = f"OPENQASM 2.0; creg c[5]; gate my_gate q {{ {statement} }}" with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, "only gate applications are valid" ): qiskit.qasm2.loads(program) def test_cannot_redefine_u(self): program = "gate U(a, b, c) q {}" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "already defined"): qiskit.qasm2.loads(program) def test_cannot_redefine_cx(self): program = "gate CX a, b {}" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "already defined"): qiskit.qasm2.loads(program) @ddt.ddt class TestBitResolution(QiskitTestCase): def test_disallow_out_of_range(self): with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "out-of-range"): qiskit.qasm2.loads("qreg q[2]; U(0, 0, 0) q[2];") with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "out-of-range"): qiskit.qasm2.loads("qreg q[2]; creg c[2]; measure q[2] -> c[0];") with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "out-of-range"): qiskit.qasm2.loads("qreg q[2]; creg c[2]; measure q[0] -> c[2];") @combine( conditional=[True, False], call=[ "CX q1[0], q1[0];", "CX q1, q1[0];", "CX q1[0], q1;", "CX q1, q1;", "ccx q1[0], q1[1], q1[0];", "ccx q2, q1, q2[0];", ], ) def test_disallow_duplicate_qubits(self, call, conditional): program = """ include "qelib1.inc"; qreg q1[3]; qreg q2[3]; qreg q3[3]; """ if conditional: program += "creg cond[1]; if (cond == 0) " program += call with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "duplicate qubit"): qiskit.qasm2.loads(program) @ddt.data( (("q1[1]", "q2[2]"), "CX q1, q2"), (("q1[1]", "q2[2]"), "CX q2, q1"), (("q1[3]", "q2[2]"), "CX q1, q2"), (("q1[2]", "q2[3]", "q3[3]"), "ccx q1, q2, q3"), (("q1[2]", "q2[3]", "q3[3]"), "ccx q2, q3, q1"), (("q1[2]", "q2[3]", "q3[3]"), "ccx q3, q1, q2"), (("q1[2]", "q2[3]", "q3[3]"), "ccx q1, q2[0], q3"), (("q1[2]", "q2[3]", "q3[3]"), "ccx q2[0], q3, q1"), (("q1[2]", "q2[3]", "q3[3]"), "ccx q3, q1, q2[0]"), ) @ddt.unpack def test_incorrect_gate_broadcast_lengths(self, registers, call): setup = 'include "qelib1.inc";\n' + "\n".join(f"qreg {reg};" for reg in registers) program = f"{setup}\n{call};" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "cannot resolve broadcast"): qiskit.qasm2.loads(program) cond = "creg cond[1];\nif (cond == 0)" program = f"{setup}\n{cond} {call};" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "cannot resolve broadcast"): qiskit.qasm2.loads(program) @ddt.data( ("qreg q[2]; creg c[2];", "q[0] -> c"), ("qreg q[2]; creg c[2];", "q -> c[0]"), ("qreg q[1]; creg c[2];", "q -> c[0]"), ("qreg q[2]; creg c[1];", "q[0] -> c"), ("qreg q[2]; creg c[3];", "q -> c"), ) @ddt.unpack def test_incorrect_measure_broadcast_lengths(self, setup, operands): program = f"{setup}\nmeasure {operands};" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "cannot resolve broadcast"): qiskit.qasm2.loads(program) program = f"{setup}\ncreg cond[1];\nif (cond == 0) measure {operands};" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "cannot resolve broadcast"): qiskit.qasm2.loads(program) @ddt.ddt class TestCustomInstructions(QiskitTestCase): def test_cannot_use_custom_before_definition(self): program = "qreg q[2]; my_gate q[0], q[1];" class MyGate(Gate): def __init__(self): super().__init__("my_gate", 2, []) with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, "cannot use .* before definition" ): qiskit.qasm2.loads( program, custom_instructions=[qiskit.qasm2.CustomInstruction("my_gate", 0, 2, MyGate)], ) def test_cannot_misdefine_u(self): program = "qreg q[1]; U(0.5, 0.25) q[0]" with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, "custom instruction .* mismatched" ): qiskit.qasm2.loads( program, custom_instructions=[qiskit.qasm2.CustomInstruction("U", 2, 1, lib.U2Gate)] ) def test_cannot_misdefine_cx(self): program = "qreg q[1]; CX q[0]" with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, "custom instruction .* mismatched" ): qiskit.qasm2.loads( program, custom_instructions=[qiskit.qasm2.CustomInstruction("CX", 0, 1, lib.XGate)] ) def test_builtin_is_typechecked(self): program = "qreg q[1]; my(0.5) q[0];" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'my' takes 2 quantum arguments"): qiskit.qasm2.loads( program, custom_instructions=[ qiskit.qasm2.CustomInstruction("my", 1, 2, lib.RXXGate, builtin=True) ], ) with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'my' takes 2 parameters"): qiskit.qasm2.loads( program, custom_instructions=[ qiskit.qasm2.CustomInstruction("my", 2, 1, lib.U2Gate, builtin=True) ], ) def test_cannot_define_builtin_twice(self): program = "gate builtin q {}; gate builtin q {};" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'builtin' is already defined"): qiskit.qasm2.loads( program, custom_instructions=[ qiskit.qasm2.CustomInstruction("builtin", 0, 1, lambda: Gate("builtin", 1, [])) ], ) def test_cannot_redefine_custom_u(self): program = "gate U(a, b, c) q {}" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "already defined"): qiskit.qasm2.loads( program, custom_instructions=[ qiskit.qasm2.CustomInstruction("U", 3, 1, lib.UGate, builtin=True) ], ) def test_cannot_redefine_custom_cx(self): program = "gate CX a, b {}" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "already defined"): qiskit.qasm2.loads( program, custom_instructions=[ qiskit.qasm2.CustomInstruction("CX", 0, 2, lib.CXGate, builtin=True) ], ) @combine( program=["gate my(a) q {}", "opaque my(a) q;"], builtin=[True, False], ) def test_custom_definition_must_match_gate(self, program, builtin): with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'my' is mismatched"): qiskit.qasm2.loads( program, custom_instructions=[ qiskit.qasm2.CustomInstruction("my", 1, 2, lib.RXXGate, builtin=builtin) ], ) with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'my' is mismatched"): qiskit.qasm2.loads( program, custom_instructions=[ qiskit.qasm2.CustomInstruction("my", 2, 1, lib.U2Gate, builtin=builtin) ], ) def test_cannot_have_duplicate_customs(self): customs = [ qiskit.qasm2.CustomInstruction("my", 1, 2, lib.RXXGate), qiskit.qasm2.CustomInstruction("x", 0, 1, lib.XGate), qiskit.qasm2.CustomInstruction("my", 1, 2, lib.RZZGate), ] with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "duplicate custom instruction"): qiskit.qasm2.loads("", custom_instructions=customs) def test_qiskit_delay_float_input_wraps_exception(self): program = "opaque delay(t) q; qreg q[1]; delay(1.5) q[0];" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "can only accept an integer"): qiskit.qasm2.loads(program, custom_instructions=qiskit.qasm2.LEGACY_CUSTOM_INSTRUCTIONS) def test_u0_float_input_wraps_exception(self): program = "opaque u0(n) q; qreg q[1]; u0(1.1) q[0];" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "must be an integer"): qiskit.qasm2.loads(program, custom_instructions=qiskit.qasm2.LEGACY_CUSTOM_INSTRUCTIONS) @ddt.ddt class TestCustomClassical(QiskitTestCase): @ddt.data("cos", "exp", "sin", "sqrt", "tan", "ln") def test_cannot_override_builtin(self, builtin): with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, r"cannot override builtin"): qiskit.qasm2.loads( "", custom_classical=[qiskit.qasm2.CustomClassical(builtin, 1, math.exp)], ) def test_duplicate_names_disallowed(self): with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, r"duplicate custom classical"): qiskit.qasm2.loads( "", custom_classical=[ qiskit.qasm2.CustomClassical("f", 1, math.exp), qiskit.qasm2.CustomClassical("f", 1, math.exp), ], ) def test_cannot_shadow_custom_instruction(self): with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, r"custom classical.*naming clash" ): qiskit.qasm2.loads( "", custom_instructions=[ qiskit.qasm2.CustomInstruction("f", 0, 1, lib.RXGate, builtin=True) ], custom_classical=[qiskit.qasm2.CustomClassical("f", 1, math.exp)], ) def test_cannot_shadow_builtin_instruction(self): with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, r"custom classical.*cannot shadow" ): qiskit.qasm2.loads( "", custom_classical=[qiskit.qasm2.CustomClassical("U", 1, math.exp)], ) def test_cannot_shadow_with_gate_definition(self): with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, r"'f' is already defined"): qiskit.qasm2.loads( "gate f q {}", custom_classical=[qiskit.qasm2.CustomClassical("f", 1, math.exp)], ) @ddt.data("qreg", "creg") def test_cannot_shadow_with_register_definition(self, regtype): with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, r"'f' is already defined"): qiskit.qasm2.loads( f"{regtype} f[2];", custom_classical=[qiskit.qasm2.CustomClassical("f", 1, math.exp)], ) @ddt.data((0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)) @ddt.unpack def test_mismatched_argument_count(self, n_good, n_bad): arg_string = ", ".join(["0" for _ in [None] * n_bad]) program = f""" qreg q[1]; U(f({arg_string}), 0, 0) q[0]; """ with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, r"custom function argument-count mismatch" ): qiskit.qasm2.loads( program, custom_classical=[qiskit.qasm2.CustomClassical("f", n_good, lambda *_: 0)] ) def test_output_type_error_is_caught(self): program = """ qreg q[1]; U(f(), 0, 0) q[0]; """ with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, r"user.*returned non-float"): qiskit.qasm2.loads( program, custom_classical=[qiskit.qasm2.CustomClassical("f", 0, lambda: "not a float")], ) def test_inner_exception_is_wrapped(self): inner_exception = Exception("custom exception") def raises(): raise inner_exception program = """ qreg q[1]; U(raises(), 0, 0) q[0]; """ with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, "caught exception when constant folding" ) as excinfo: qiskit.qasm2.loads( program, custom_classical=[qiskit.qasm2.CustomClassical("raises", 0, raises)] ) assert excinfo.exception.__cause__ is inner_exception def test_cannot_be_used_as_gate(self): program = """ qreg q[1]; f(0) q[0]; """ with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, r"'f' is a custom classical function" ): qiskit.qasm2.loads( program, custom_classical=[qiskit.qasm2.CustomClassical("f", 1, lambda x: x)] ) def test_cannot_be_used_as_qarg(self): program = """ U(0, 0, 0) f; """ with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, r"'f' is a custom classical function" ): qiskit.qasm2.loads( program, custom_classical=[qiskit.qasm2.CustomClassical("f", 1, lambda x: x)] ) def test_cannot_be_used_as_carg(self): program = """ qreg q[1]; measure q[0] -> f; """ with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, r"'f' is a custom classical function" ): qiskit.qasm2.loads( program, custom_classical=[qiskit.qasm2.CustomClassical("f", 1, lambda x: x)] ) @ddt.ddt class TestStrict(QiskitTestCase): @ddt.data( "gate my_gate(p0, p1,) q0, q1 {}", "gate my_gate(p0, p1) q0, q1, {}", "opaque my_gate(p0, p1,) q0, q1;", "opaque my_gate(p0, p1) q0, q1,;", 'include "qelib1.inc"; qreg q[2]; cu3(0.5, 0.25, 0.125,) q[0], q[1];', 'include "qelib1.inc"; qreg q[2]; cu3(0.5, 0.25, 0.125) q[0], q[1],;', "qreg q[2]; barrier q[0], q[1],;", 'include "qelib1.inc"; qreg q[1]; rx(sin(pi,)) q[0];', ) def test_trailing_comma(self, program): with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, r"\[strict\] .*trailing comma"): qiskit.qasm2.loads("OPENQASM 2.0;\n" + program, strict=True) def test_trailing_semicolon_after_gate(self): program = "OPENQASM 2.0; gate my_gate q {};" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, r"\[strict\] .*extra semicolon"): qiskit.qasm2.loads(program, strict=True) def test_empty_statement(self): program = "OPENQASM 2.0; ;" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, r"\[strict\] .*empty statement"): qiskit.qasm2.loads(program, strict=True) def test_required_version_regular(self): program = "qreg q[1];" with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, r"\[strict\] the first statement" ): qiskit.qasm2.loads(program, strict=True) def test_required_version_empty(self): with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, r"\[strict\] .*needed a version statement" ): qiskit.qasm2.loads("", strict=True) def test_barrier_requires_args(self): program = "OPENQASM 2.0; qreg q[2]; barrier;" with self.assertRaisesRegex( qiskit.qasm2.QASM2ParseError, r"\[strict\] barrier statements must have at least one" ): qiskit.qasm2.loads(program, strict=True)
https://github.com/swe-train/qiskit__qiskit
swe-train
# 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. # pylint: disable=missing-module-docstring,missing-class-docstring,missing-function-docstring import io import math import os import pathlib import pickle import shutil import tempfile import unittest import ddt import qiskit.qasm2 from qiskit import qpy from qiskit.circuit import ( ClassicalRegister, Gate, Parameter, QuantumCircuit, QuantumRegister, Qubit, library as lib, ) from qiskit.test import QiskitTestCase from . import gate_builder class TestEmpty(QiskitTestCase): def test_allows_empty(self): self.assertEqual(qiskit.qasm2.loads(""), QuantumCircuit()) class TestVersion(QiskitTestCase): def test_complete_version(self): program = "OPENQASM 2.0;" parsed = qiskit.qasm2.loads(program) self.assertEqual(parsed, QuantumCircuit()) def test_incomplete_version(self): program = "OPENQASM 2;" parsed = qiskit.qasm2.loads(program) self.assertEqual(parsed, QuantumCircuit()) def test_after_comment(self): program = """ // hello, world OPENQASM 2.0; qreg q[2]; """ parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(2, "q")) self.assertEqual(parsed, qc) class TestRegisters(QiskitTestCase): def test_qreg(self): program = "qreg q1[2]; qreg q2[1]; qreg q3[4];" parsed = qiskit.qasm2.loads(program) regs = [QuantumRegister(2, "q1"), QuantumRegister(1, "q2"), QuantumRegister(4, "q3")] self.assertEqual(list(parsed.qregs), regs) self.assertEqual(list(parsed.cregs), []) def test_creg(self): program = "creg c1[2]; creg c2[1]; creg c3[4];" parsed = qiskit.qasm2.loads(program) regs = [ClassicalRegister(2, "c1"), ClassicalRegister(1, "c2"), ClassicalRegister(4, "c3")] self.assertEqual(list(parsed.cregs), regs) self.assertEqual(list(parsed.qregs), []) def test_interleaved_registers(self): program = "qreg q1[3]; creg c1[2]; qreg q2[1]; creg c2[1];" parsed = qiskit.qasm2.loads(program) qregs = [QuantumRegister(3, "q1"), QuantumRegister(1, "q2")] cregs = [ClassicalRegister(2, "c1"), ClassicalRegister(1, "c2")] self.assertEqual(list(parsed.qregs), qregs) self.assertEqual(list(parsed.cregs), cregs) def test_registers_after_gate(self): program = "qreg before[2]; CX before[0], before[1]; qreg after[2]; CX after[0], after[1];" parsed = qiskit.qasm2.loads(program) before = QuantumRegister(2, "before") after = QuantumRegister(2, "after") qc = QuantumCircuit(before, after) qc.cx(before[0], before[1]) qc.cx(after[0], after[1]) self.assertEqual(parsed, qc) def test_empty_registers(self): program = "qreg q[0]; creg c[0];" parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(0, "q"), ClassicalRegister(0, "c")) self.assertEqual(parsed, qc) @ddt.ddt class TestGateApplication(QiskitTestCase): def test_builtin_single(self): program = """ qreg q[2]; U(0, 0, 0) q[0]; CX q[0], q[1]; """ parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.u(0, 0, 0, 0) qc.cx(0, 1) self.assertEqual(parsed, qc) def test_builtin_1q_broadcast(self): program = "qreg q[2]; U(0, 0, 0) q;" parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.u(0, 0, 0, 0) qc.u(0, 0, 0, 1) self.assertEqual(parsed, qc) def test_builtin_2q_broadcast(self): program = """ qreg q1[2]; qreg q2[2]; CX q1[0], q2; barrier; CX q1, q2[1]; barrier; CX q1, q2; """ parsed = qiskit.qasm2.loads(program) q1 = QuantumRegister(2, "q1") q2 = QuantumRegister(2, "q2") qc = QuantumCircuit(q1, q2) qc.cx(q1[0], q2[0]) qc.cx(q1[0], q2[1]) qc.barrier() qc.cx(q1[0], q2[1]) qc.cx(q1[1], q2[1]) qc.barrier() qc.cx(q1[0], q2[0]) qc.cx(q1[1], q2[1]) self.assertEqual(parsed, qc) def test_3q_broadcast(self): program = """ include "qelib1.inc"; qreg q1[2]; qreg q2[2]; qreg q3[2]; ccx q1, q2[0], q3[1]; ccx q1[1], q2, q3[0]; ccx q1[0], q2[1], q3; barrier; ccx q1, q2, q3[1]; ccx q1[1], q2, q3; ccx q1, q2[1], q3; barrier; ccx q1, q2, q3; """ parsed = qiskit.qasm2.loads(program) q1 = QuantumRegister(2, "q1") q2 = QuantumRegister(2, "q2") q3 = QuantumRegister(2, "q3") qc = QuantumCircuit(q1, q2, q3) qc.ccx(q1[0], q2[0], q3[1]) qc.ccx(q1[1], q2[0], q3[1]) qc.ccx(q1[1], q2[0], q3[0]) qc.ccx(q1[1], q2[1], q3[0]) qc.ccx(q1[0], q2[1], q3[0]) qc.ccx(q1[0], q2[1], q3[1]) qc.barrier() qc.ccx(q1[0], q2[0], q3[1]) qc.ccx(q1[1], q2[1], q3[1]) qc.ccx(q1[1], q2[0], q3[0]) qc.ccx(q1[1], q2[1], q3[1]) qc.ccx(q1[0], q2[1], q3[0]) qc.ccx(q1[1], q2[1], q3[1]) qc.barrier() qc.ccx(q1[0], q2[0], q3[0]) qc.ccx(q1[1], q2[1], q3[1]) self.assertEqual(parsed, qc) @ddt.data(True, False) def test_broadcast_against_empty_register(self, conditioned): cond = "if (cond == 0) " if conditioned else "" program = f""" OPENQASM 2; include "qelib1.inc"; qreg q1[1]; qreg q2[1]; qreg empty1[0]; qreg empty2[0]; qreg empty3[0]; creg cond[1]; // None of the following statements should produce any gate applications. {cond}h empty1; {cond}cx q1[0], empty1; {cond}cx empty1, q2[0]; {cond}cx empty1, empty2; {cond}ccx empty1, q1[0], q2[0]; {cond}ccx q1[0], empty2, q2[0]; {cond}ccx q1[0], q2[0], empty3; {cond}ccx empty1, empty2, q1[0]; {cond}ccx empty1, q1[0], empty2; {cond}ccx q1[0], empty1, empty2; {cond}ccx empty1, empty2, empty3; """ parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit( QuantumRegister(1, "q1"), QuantumRegister(1, "q2"), QuantumRegister(0, "empty1"), QuantumRegister(0, "empty2"), QuantumRegister(0, "empty3"), ClassicalRegister(1, "cond"), ) self.assertEqual(parsed, qc) def test_conditioned(self): program = """ qreg q[2]; creg cond[1]; if (cond == 0) U(0, 0, 0) q[0]; if (cond == 1) CX q[1], q[0]; """ parsed = qiskit.qasm2.loads(program) cond = ClassicalRegister(1, "cond") qc = QuantumCircuit(QuantumRegister(2, "q"), cond) qc.u(0, 0, 0, 0).c_if(cond, 0) qc.cx(1, 0).c_if(cond, 1) self.assertEqual(parsed, qc) def test_conditioned_broadcast(self): program = """ qreg q1[2]; qreg q2[2]; creg cond[1]; if (cond == 0) U(0, 0, 0) q1; if (cond == 1) CX q1[0], q2; """ parsed = qiskit.qasm2.loads(program) cond = ClassicalRegister(1, "cond") q1 = QuantumRegister(2, "q1") q2 = QuantumRegister(2, "q2") qc = QuantumCircuit(q1, q2, cond) qc.u(0, 0, 0, q1[0]).c_if(cond, 0) qc.u(0, 0, 0, q1[1]).c_if(cond, 0) qc.cx(q1[0], q2[0]).c_if(cond, 1) qc.cx(q1[0], q2[1]).c_if(cond, 1) self.assertEqual(parsed, qc) def test_constant_folding(self): # Most expression-related things are tested in `test_expression.py` instead. program = """ qreg q[1]; U(4 + 3 * 2 ^ 2, cos(pi) * (1 - ln(1)), 2 ^ 3 ^ 2) q[0]; """ parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(1, "q")) qc.u(16.0, -1.0, 512.0, 0) self.assertEqual(parsed, qc) def test_call_defined_gate(self): program = """ gate my_gate a { U(0, 0, 0) a; } qreg q[2]; my_gate q[0]; my_gate q; """ parsed = qiskit.qasm2.loads(program) my_gate_def = QuantumCircuit([Qubit()]) my_gate_def.u(0, 0, 0, 0) my_gate = gate_builder("my_gate", [], my_gate_def) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.append(my_gate(), [0]) qc.append(my_gate(), [0]) qc.append(my_gate(), [1]) self.assertEqual(parsed, qc) def test_parameterless_gates_accept_parentheses(self): program = """ qreg q[2]; CX q[0], q[1]; CX() q[1], q[0]; """ parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.cx(0, 1) qc.cx(1, 0) self.assertEqual(parsed, qc) class TestGateDefinition(QiskitTestCase): def test_simple_definition(self): program = """ gate not_bell a, b { U(0, 0, 0) a; CX a, b; } qreg q[2]; not_bell q[0], q[1]; """ parsed = qiskit.qasm2.loads(program) not_bell_def = QuantumCircuit([Qubit(), Qubit()]) not_bell_def.u(0, 0, 0, 0) not_bell_def.cx(0, 1) not_bell = gate_builder("not_bell", [], not_bell_def) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.append(not_bell(), [0, 1]) self.assertEqual(parsed, qc) def test_conditioned(self): program = """ gate not_bell a, b { U(0, 0, 0) a; CX a, b; } qreg q[2]; creg cond[1]; if (cond == 0) not_bell q[0], q[1]; """ parsed = qiskit.qasm2.loads(program) not_bell_def = QuantumCircuit([Qubit(), Qubit()]) not_bell_def.u(0, 0, 0, 0) not_bell_def.cx(0, 1) not_bell = gate_builder("not_bell", [], not_bell_def) cond = ClassicalRegister(1, "cond") qc = QuantumCircuit(QuantumRegister(2, "q"), cond) qc.append(not_bell().c_if(cond, 0), [0, 1]) self.assertEqual(parsed, qc) def test_constant_folding_in_definition(self): program = """ gate bell a, b { U(pi/2, 0, pi) a; CX a, b; } qreg q[2]; bell q[0], q[1]; """ parsed = qiskit.qasm2.loads(program) bell_def = QuantumCircuit([Qubit(), Qubit()]) bell_def.u(math.pi / 2, 0, math.pi, 0) bell_def.cx(0, 1) bell = gate_builder("bell", [], bell_def) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.append(bell(), [0, 1]) self.assertEqual(parsed, qc) def test_parameterised_gate(self): # Most of the tests of deep parameter expressions are in `test_expression.py`. program = """ gate my_gate(a, b) c { U(a, b, a + 2 * b) c; } qreg q[1]; my_gate(0.25, 0.5) q[0]; my_gate(0.5, 0.25) q[0]; """ parsed = qiskit.qasm2.loads(program) a, b = Parameter("a"), Parameter("b") my_gate_def = QuantumCircuit([Qubit()]) my_gate_def.u(a, b, a + 2 * b, 0) my_gate = gate_builder("my_gate", [a, b], my_gate_def) qc = QuantumCircuit(QuantumRegister(1, "q")) qc.append(my_gate(0.25, 0.5), [0]) qc.append(my_gate(0.5, 0.25), [0]) self.assertEqual(parsed, qc) # Also check the decomposition has come out exactly as expected. The floating-point # assertions are safe as exact equality checks because there are no lossy operations with # these parameters, and the answer should be exact. decomposed = qc.decompose() self.assertEqual(decomposed.data[0].operation.name, "u") self.assertEqual(list(decomposed.data[0].operation.params), [0.25, 0.5, 1.25]) self.assertEqual(decomposed.data[1].operation.name, "u") self.assertEqual(list(decomposed.data[1].operation.params), [0.5, 0.25, 1.0]) def test_parameterless_gate_with_parentheses(self): program = """ gate my_gate() a { U(0, 0, 0) a; } qreg q[1]; my_gate q[0]; my_gate() q[0]; """ parsed = qiskit.qasm2.loads(program) my_gate_def = QuantumCircuit([Qubit()]) my_gate_def.u(0, 0, 0, 0) my_gate = gate_builder("my_gate", [], my_gate_def) qc = QuantumCircuit(QuantumRegister(1, "q")) qc.append(my_gate(), [0]) qc.append(my_gate(), [0]) self.assertEqual(parsed, qc) def test_access_includes_in_definition(self): program = """ include "qelib1.inc"; gate bell a, b { h a; cx a, b; } qreg q[2]; bell q[0], q[1]; """ parsed = qiskit.qasm2.loads(program) bell_def = QuantumCircuit([Qubit(), Qubit()]) bell_def.h(0) bell_def.cx(0, 1) bell = gate_builder("bell", [], bell_def) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.append(bell(), [0, 1]) self.assertEqual(parsed, qc) def test_access_previous_defined_gate(self): program = """ include "qelib1.inc"; gate bell a, b { h a; cx a, b; } gate second_bell a, b { bell b, a; } qreg q[2]; second_bell q[0], q[1]; """ parsed = qiskit.qasm2.loads(program) bell_def = QuantumCircuit([Qubit(), Qubit()]) bell_def.h(0) bell_def.cx(0, 1) bell = gate_builder("bell", [], bell_def) second_bell_def = QuantumCircuit([Qubit(), Qubit()]) second_bell_def.append(bell(), [1, 0]) second_bell = gate_builder("second_bell", [], second_bell_def) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.append(second_bell(), [0, 1]) self.assertEqual(parsed, qc) def test_qubits_lookup_differently_to_gates(self): # The spec is somewhat unclear on this, and this leads to super weird text, but it's # technically unambiguously resolvable and this is more permissive. program = """ include "qelib1.inc"; gate bell h, cx { h h; cx h, cx; } qreg q[2]; bell q[0], q[1]; """ parsed = qiskit.qasm2.loads(program) bell_def = QuantumCircuit([Qubit(), Qubit()]) bell_def.h(0) bell_def.cx(0, 1) bell = gate_builder("bell", [], bell_def) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.append(bell(), [0, 1]) self.assertEqual(parsed, qc) def test_parameters_lookup_differently_to_gates(self): # The spec is somewhat unclear on this, and this leads to super weird text, but it's # technically unambiguously resolvable and this is more permissive. program = """ include "qelib1.inc"; gate shadow(rx, rz) a { rz(rz) a; rx(rx) a; } qreg q[1]; shadow(0.5, 2.0) q[0]; """ parsed = qiskit.qasm2.loads(program) rx, rz = Parameter("rx"), Parameter("rz") shadow_def = QuantumCircuit([Qubit()]) shadow_def.rz(rz, 0) shadow_def.rx(rx, 0) shadow = gate_builder("shadow", [rx, rz], shadow_def) qc = QuantumCircuit(QuantumRegister(1, "q")) qc.append(shadow(0.5, 2.0), [0]) self.assertEqual(parsed, qc) def test_unused_parameters_convert_correctly(self): # The main risk here is that there might be lazy application in the gate definition # bindings, and we might accidentally try and bind parameters that aren't actually in the # definition. program = """ gate my_gate(p) q { U(0, 0, 0) q; } qreg q[1]; my_gate(0.5) q[0]; """ parsed = qiskit.qasm2.loads(program) # No top-level circuit equality test here, because all the internals of gate application are # an implementation detail, and we don't want to tie the tests and implementation together # too closely. self.assertEqual(list(parsed.qregs), [QuantumRegister(1, "q")]) self.assertEqual(list(parsed.cregs), []) self.assertEqual(len(parsed.data), 1) self.assertEqual(parsed.data[0].qubits, (parsed.qubits[0],)) self.assertEqual(parsed.data[0].clbits, ()) self.assertEqual(parsed.data[0].operation.name, "my_gate") self.assertEqual(list(parsed.data[0].operation.params), [0.5]) decomposed = QuantumCircuit(QuantumRegister(1, "q")) decomposed.u(0, 0, 0, 0) self.assertEqual(parsed.decompose(), decomposed) def test_qubit_barrier_in_definition(self): program = """ gate my_gate a, b { barrier a; barrier b; barrier a, b; } qreg q[2]; my_gate q[0], q[1]; """ parsed = qiskit.qasm2.loads(program) my_gate_def = QuantumCircuit([Qubit(), Qubit()]) my_gate_def.barrier(0) my_gate_def.barrier(1) my_gate_def.barrier([0, 1]) my_gate = gate_builder("my_gate", [], my_gate_def) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.append(my_gate(), [0, 1]) self.assertEqual(parsed, qc) def test_bare_barrier_in_definition(self): program = """ gate my_gate a, b { barrier; } qreg q[2]; my_gate q[0], q[1]; """ parsed = qiskit.qasm2.loads(program) my_gate_def = QuantumCircuit([Qubit(), Qubit()]) my_gate_def.barrier(my_gate_def.qubits) my_gate = gate_builder("my_gate", [], my_gate_def) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.append(my_gate(), [0, 1]) self.assertEqual(parsed, qc) def test_duplicate_barrier_in_definition(self): program = """ gate my_gate a, b { barrier a, a; barrier b, a, b; } qreg q[2]; my_gate q[0], q[1]; """ parsed = qiskit.qasm2.loads(program) my_gate_def = QuantumCircuit([Qubit(), Qubit()]) my_gate_def.barrier(0) my_gate_def.barrier([1, 0]) my_gate = gate_builder("my_gate", [], my_gate_def) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.append(my_gate(), [0, 1]) self.assertEqual(parsed, qc) def test_pickleable(self): program = """ include "qelib1.inc"; gate my_gate(a) b, c { rz(2 * a) b; h b; cx b, c; } qreg q[2]; my_gate(0.5) q[0], q[1]; my_gate(0.25) q[1], q[0]; """ parsed = qiskit.qasm2.loads(program) a = Parameter("a") my_gate_def = QuantumCircuit([Qubit(), Qubit()]) my_gate_def.rz(2 * a, 0) my_gate_def.h(0) my_gate_def.cx(0, 1) my_gate = gate_builder("my_gate", [a], my_gate_def) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.append(my_gate(0.5), [0, 1]) qc.append(my_gate(0.25), [1, 0]) self.assertEqual(parsed, qc) with io.BytesIO() as fptr: pickle.dump(parsed, fptr) fptr.seek(0) loaded = pickle.load(fptr) self.assertEqual(parsed, loaded) def test_qpy_single_call_roundtrip(self): program = """ include "qelib1.inc"; gate my_gate(a) b, c { rz(2 * a) b; h b; cx b, c; } qreg q[2]; my_gate(0.5) q[0], q[1]; """ parsed = qiskit.qasm2.loads(program) # QPY won't persist custom gates by design choice, so instead let us check against the # explicit form it uses. my_gate_def = QuantumCircuit([Qubit(), Qubit()]) my_gate_def.rz(1.0, 0) my_gate_def.h(0) my_gate_def.cx(0, 1) my_gate = Gate("my_gate", 2, [0.5]) my_gate.definition = my_gate_def qc = QuantumCircuit(QuantumRegister(2, "q")) qc.append(my_gate, [0, 1]) with io.BytesIO() as fptr: qpy.dump(parsed, fptr) fptr.seek(0) loaded = qpy.load(fptr)[0] self.assertEqual(loaded, qc) # See https://github.com/Qiskit/qiskit-terra/issues/8941 @unittest.expectedFailure def test_qpy_double_call_roundtrip(self): program = """ include "qelib1.inc"; gate my_gate(a) b, c { rz(2 * a) b; h b; cx b, c; } qreg q[2]; my_gate(0.5) q[0], q[1]; my_gate(0.25) q[1], q[0]; """ parsed = qiskit.qasm2.loads(program) my_gate1_def = QuantumCircuit([Qubit(), Qubit()]) my_gate1_def.rz(1.0, 0) my_gate1_def.h(0) my_gate1_def.cx(0, 1) my_gate1 = Gate("my_gate", 2, [0.5]) my_gate1.definition = my_gate1_def my_gate2_def = QuantumCircuit([Qubit(), Qubit()]) my_gate2_def.rz(0.5, 0) my_gate2_def.h(0) my_gate2_def.cx(0, 1) my_gate2 = Gate("my_gate", 2, [0.25]) my_gate2.definition = my_gate2_def qc = QuantumCircuit(QuantumRegister(2, "q")) qc.append(my_gate1, [0, 1]) qc.append(my_gate2, [1, 0]) with io.BytesIO() as fptr: qpy.dump(parsed, fptr) fptr.seek(0) loaded = qpy.load(fptr)[0] self.assertEqual(loaded, qc) class TestOpaque(QiskitTestCase): def test_simple(self): program = """ opaque my_gate a; opaque my_gate2() a; qreg q[2]; my_gate q[0]; my_gate() q[1]; my_gate2 q[0]; my_gate2() q[1]; """ parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.append(Gate("my_gate", 1, []), [0]) qc.append(Gate("my_gate", 1, []), [1]) qc.append(Gate("my_gate2", 1, []), [0]) qc.append(Gate("my_gate2", 1, []), [1]) self.assertEqual(parsed, qc) def test_parameterised(self): program = """ opaque my_gate(a, b) c, d; qreg q[2]; my_gate(0.5, 0.25) q[1], q[0]; """ parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.append(Gate("my_gate", 2, [0.5, 0.25]), [1, 0]) self.assertEqual(parsed, qc) class TestBarrier(QiskitTestCase): def test_single_register_argument(self): program = """ qreg first[3]; qreg second[3]; barrier first; barrier second; """ parsed = qiskit.qasm2.loads(program) first = QuantumRegister(3, "first") second = QuantumRegister(3, "second") qc = QuantumCircuit(first, second) qc.barrier(first) qc.barrier(second) self.assertEqual(parsed, qc) def test_single_qubit_argument(self): program = """ qreg first[3]; qreg second[3]; barrier first[1]; barrier second[0]; """ parsed = qiskit.qasm2.loads(program) first = QuantumRegister(3, "first") second = QuantumRegister(3, "second") qc = QuantumCircuit(first, second) qc.barrier(first[1]) qc.barrier(second[0]) self.assertEqual(parsed, qc) def test_empty_circuit_empty_arguments(self): program = "barrier;" parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit() self.assertEqual(parsed, qc) def test_one_register_circuit_empty_arguments(self): program = "qreg q1[2]; barrier;" parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(2, "q1")) qc.barrier(qc.qubits) self.assertEqual(parsed, qc) def test_multi_register_circuit_empty_arguments(self): program = "qreg q1[2]; qreg q2[3]; qreg q3[1]; barrier;" parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit( QuantumRegister(2, "q1"), QuantumRegister(3, "q2"), QuantumRegister(1, "q3") ) qc.barrier(qc.qubits) self.assertEqual(parsed, qc) def test_include_empty_register(self): program = """ qreg q[2]; qreg empty[0]; barrier empty; barrier q, empty; barrier; """ parsed = qiskit.qasm2.loads(program) q = QuantumRegister(2, "q") qc = QuantumCircuit(q, QuantumRegister(0, "empty")) qc.barrier(q) qc.barrier(qc.qubits) self.assertEqual(parsed, qc) def test_allows_duplicate_arguments(self): # There's nothing in the paper that implies this should be forbidden. program = """ qreg q1[3]; qreg q2[2]; barrier q1, q1; barrier q1[0], q1; barrier q1, q1[0]; barrier q1, q2, q1; """ parsed = qiskit.qasm2.loads(program) q1 = QuantumRegister(3, "q1") q2 = QuantumRegister(2, "q2") qc = QuantumCircuit(q1, q2) qc.barrier(q1) qc.barrier(q1) qc.barrier(q1) qc.barrier(q1, q2) self.assertEqual(parsed, qc) class TestMeasure(QiskitTestCase): def test_single(self): program = """ qreg q[1]; creg c[1]; measure q[0] -> c[0]; """ parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(1, "q"), ClassicalRegister(1, "c")) qc.measure(0, 0) self.assertEqual(parsed, qc) def test_broadcast(self): program = """ qreg q[2]; creg c[2]; measure q -> c; """ parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(2, "q"), ClassicalRegister(2, "c")) qc.measure(0, 0) qc.measure(1, 1) self.assertEqual(parsed, qc) def test_conditioned(self): program = """ qreg q[2]; creg c[2]; creg cond[1]; if (cond == 0) measure q[0] -> c[0]; if (cond == 1) measure q -> c; """ parsed = qiskit.qasm2.loads(program) cond = ClassicalRegister(1, "cond") qc = QuantumCircuit(QuantumRegister(2, "q"), ClassicalRegister(2, "c"), cond) qc.measure(0, 0).c_if(cond, 0) qc.measure(0, 0).c_if(cond, 1) qc.measure(1, 1).c_if(cond, 1) self.assertEqual(parsed, qc) def test_broadcast_against_empty_register(self): program = """ qreg q_empty[0]; creg c_empty[0]; measure q_empty -> c_empty; """ parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(0, "q_empty"), ClassicalRegister(0, "c_empty")) self.assertEqual(parsed, qc) def test_conditioned_broadcast_against_empty_register(self): program = """ qreg q_empty[0]; creg c_empty[0]; creg cond[1]; if (cond == 0) measure q_empty -> c_empty; """ parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit( QuantumRegister(0, "q_empty"), ClassicalRegister(0, "c_empty"), ClassicalRegister(1, "cond"), ) self.assertEqual(parsed, qc) class TestReset(QiskitTestCase): def test_single(self): program = """ qreg q[1]; reset q[0]; """ parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(1, "q")) qc.reset(0) self.assertEqual(parsed, qc) def test_broadcast(self): program = """ qreg q[2]; reset q; """ parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.reset(0) qc.reset(1) self.assertEqual(parsed, qc) def test_conditioned(self): program = """ qreg q[2]; creg cond[1]; if (cond == 0) reset q[0]; if (cond == 1) reset q; """ parsed = qiskit.qasm2.loads(program) cond = ClassicalRegister(1, "cond") qc = QuantumCircuit(QuantumRegister(2, "q"), cond) qc.reset(0).c_if(cond, 0) qc.reset(0).c_if(cond, 1) qc.reset(1).c_if(cond, 1) self.assertEqual(parsed, qc) def test_broadcast_against_empty_register(self): program = """ qreg empty[0]; reset empty; """ parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(0, "empty")) self.assertEqual(parsed, qc) def test_conditioned_broadcast_against_empty_register(self): program = """ qreg empty[0]; creg cond[1]; if (cond == 0) reset empty; """ parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(0, "empty"), ClassicalRegister(1, "cond")) self.assertEqual(parsed, qc) class TestInclude(QiskitTestCase): def setUp(self): super().setUp() self.tmp_dir = pathlib.Path(tempfile.mkdtemp()) def tearDown(self): # Doesn't really matter if the removal fails, since this was a tempdir anyway; it'll get # cleaned up by the OS at some point. shutil.rmtree(self.tmp_dir, ignore_errors=True) super().tearDown() def test_qelib1_include(self): program = """ include "qelib1.inc"; qreg q[3]; u3(0.5, 0.25, 0.125) q[0]; u2(0.5, 0.25) q[0]; u1(0.5) q[0]; cx q[0], q[1]; id q[0]; x q[0]; y q[0]; z q[0]; h q[0]; s q[0]; sdg q[0]; t q[0]; tdg q[0]; rx(0.5) q[0]; ry(0.5) q[0]; rz(0.5) q[0]; cz q[0], q[1]; cy q[0], q[1]; ch q[0], q[1]; ccx q[0], q[1], q[2]; crz(0.5) q[0], q[1]; cu1(0.5) q[0], q[1]; cu3(0.5, 0.25, 0.125) q[0], q[1]; """ parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(3, "q")) qc.append(lib.U3Gate(0.5, 0.25, 0.125), [0]) qc.append(lib.U2Gate(0.5, 0.25), [0]) qc.append(lib.U1Gate(0.5), [0]) qc.append(lib.CXGate(), [0, 1]) qc.append(lib.UGate(0, 0, 0), [0]) # Stand-in for id. qc.append(lib.XGate(), [0]) qc.append(lib.YGate(), [0]) qc.append(lib.ZGate(), [0]) qc.append(lib.HGate(), [0]) qc.append(lib.SGate(), [0]) qc.append(lib.SdgGate(), [0]) qc.append(lib.TGate(), [0]) qc.append(lib.TdgGate(), [0]) qc.append(lib.RXGate(0.5), [0]) qc.append(lib.RYGate(0.5), [0]) qc.append(lib.RZGate(0.5), [0]) qc.append(lib.CZGate(), [0, 1]) qc.append(lib.CYGate(), [0, 1]) qc.append(lib.CHGate(), [0, 1]) qc.append(lib.CCXGate(), [0, 1, 2]) qc.append(lib.CRZGate(0.5), [0, 1]) qc.append(lib.CU1Gate(0.5), [0, 1]) qc.append(lib.CU3Gate(0.5, 0.25, 0.125), [0, 1]) self.assertEqual(parsed, qc) def test_qelib1_after_gate_definition(self): program = """ gate bell a, b { U(pi/2, 0, pi) a; CX a, b; } include "qelib1.inc"; qreg q[2]; bell q[0], q[1]; rx(0.5) q[0]; bell q[1], q[0]; """ parsed = qiskit.qasm2.loads(program) bell_def = QuantumCircuit([Qubit(), Qubit()]) bell_def.u(math.pi / 2, 0, math.pi, 0) bell_def.cx(0, 1) bell = gate_builder("bell", [], bell_def) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.append(bell(), [0, 1]) qc.rx(0.5, 0) qc.append(bell(), [1, 0]) self.assertEqual(parsed, qc) def test_include_can_define_version(self): include = """ OPENQASM 2.0; qreg inner_q[2]; """ with open(self.tmp_dir / "include.qasm", "w") as fp: fp.write(include) program = """ OPENQASM 2.0; include "include.qasm"; """ parsed = qiskit.qasm2.loads(program, include_path=(self.tmp_dir,)) qc = QuantumCircuit(QuantumRegister(2, "inner_q")) self.assertEqual(parsed, qc) def test_can_define_gates(self): include = """ gate bell a, b { h a; cx a, b; } """ with open(self.tmp_dir / "include.qasm", "w") as fp: fp.write(include) program = """ OPENQASM 2.0; include "qelib1.inc"; include "include.qasm"; qreg q[2]; bell q[0], q[1]; """ parsed = qiskit.qasm2.loads(program, include_path=(self.tmp_dir,)) bell_def = QuantumCircuit([Qubit(), Qubit()]) bell_def.h(0) bell_def.cx(0, 1) bell = gate_builder("bell", [], bell_def) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.append(bell(), [0, 1]) self.assertEqual(parsed, qc) def test_nested_include(self): inner = "creg c[2];" with open(self.tmp_dir / "inner.qasm", "w") as fp: fp.write(inner) outer = """ qreg q[2]; include "inner.qasm"; """ with open(self.tmp_dir / "outer.qasm", "w") as fp: fp.write(outer) program = """ OPENQASM 2.0; include "outer.qasm"; """ parsed = qiskit.qasm2.loads(program, include_path=(self.tmp_dir,)) qc = QuantumCircuit(QuantumRegister(2, "q"), ClassicalRegister(2, "c")) self.assertEqual(parsed, qc) def test_first_hit_is_used(self): empty = self.tmp_dir / "empty" empty.mkdir() first = self.tmp_dir / "first" first.mkdir() with open(first / "include.qasm", "w") as fp: fp.write("qreg q[1];") second = self.tmp_dir / "second" second.mkdir() with open(second / "include.qasm", "w") as fp: fp.write("qreg q[2];") program = 'include "include.qasm";' parsed = qiskit.qasm2.loads(program, include_path=(empty, first, second)) qc = QuantumCircuit(QuantumRegister(1, "q")) self.assertEqual(parsed, qc) def test_qelib1_ignores_search_path(self): with open(self.tmp_dir / "qelib1.inc", "w") as fp: fp.write("qreg not_used[2];") program = 'include "qelib1.inc";' parsed = qiskit.qasm2.loads(program, include_path=(self.tmp_dir,)) qc = QuantumCircuit() self.assertEqual(parsed, qc) def test_include_from_current_directory(self): include = """ qreg q[2]; """ with open(self.tmp_dir / "include.qasm", "w") as fp: fp.write(include) program = """ OPENQASM 2.0; include "include.qasm"; """ prevdir = os.getcwd() os.chdir(self.tmp_dir) try: parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(2, "q")) self.assertEqual(parsed, qc) finally: os.chdir(prevdir) def test_load_searches_source_directory(self): with open(self.tmp_dir / "include.qasm", "w") as fp: fp.write("qreg q[2];") program = 'include "include.qasm";' with open(self.tmp_dir / "program.qasm", "w") as fp: fp.write(program) parsed = qiskit.qasm2.load(self.tmp_dir / "program.qasm") qc = QuantumCircuit(QuantumRegister(2, "q")) self.assertEqual(parsed, qc) def test_load_searches_source_directory_last(self): first = self.tmp_dir / "first" first.mkdir() with open(first / "include.qasm", "w") as fp: fp.write("qreg q[2];") with open(self.tmp_dir / "include.qasm", "w") as fp: fp.write("qreg not_used[2];") program = 'include "include.qasm";' with open(self.tmp_dir / "program.qasm", "w") as fp: fp.write(program) parsed = qiskit.qasm2.load(self.tmp_dir / "program.qasm", include_path=(first,)) qc = QuantumCircuit(QuantumRegister(2, "q")) self.assertEqual(parsed, qc) def test_load_searches_source_directory_prepend(self): first = self.tmp_dir / "first" first.mkdir() with open(first / "include.qasm", "w") as fp: fp.write("qreg not_used[2];") with open(self.tmp_dir / "include.qasm", "w") as fp: fp.write("qreg q[2];") program = 'include "include.qasm";' with open(self.tmp_dir / "program.qasm", "w") as fp: fp.write(program) parsed = qiskit.qasm2.load( self.tmp_dir / "program.qasm", include_path=(first,), include_input_directory="prepend" ) qc = QuantumCircuit(QuantumRegister(2, "q")) self.assertEqual(parsed, qc) def test_load_can_ignore_source_directory(self): with open(self.tmp_dir / "include.qasm", "w") as fp: fp.write("qreg q[2];") program = 'include "include.qasm";' with open(self.tmp_dir / "program.qasm", "w") as fp: fp.write(program) with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "unable to find 'include.qasm'"): qiskit.qasm2.load(self.tmp_dir / "program.qasm", include_input_directory=None) @ddt.ddt class TestCustomInstructions(QiskitTestCase): def test_qelib1_include_overridden(self): program = """ OPENQASM 2.0; include "qelib1.inc"; qreg q[3]; u3(0.5, 0.25, 0.125) q[0]; u2(0.5, 0.25) q[0]; u1(0.5) q[0]; cx q[0], q[1]; id q[0]; x q[0]; y q[0]; z q[0]; h q[0]; s q[0]; sdg q[0]; t q[0]; tdg q[0]; rx(0.5) q[0]; ry(0.5) q[0]; rz(0.5) q[0]; cz q[0], q[1]; cy q[0], q[1]; ch q[0], q[1]; ccx q[0], q[1], q[2]; crz(0.5) q[0], q[1]; cu1(0.5) q[0], q[1]; cu3(0.5, 0.25, 0.125) q[0], q[1]; """ parsed = qiskit.qasm2.loads( program, custom_instructions=qiskit.qasm2.LEGACY_CUSTOM_INSTRUCTIONS ) qc = QuantumCircuit(QuantumRegister(3, "q")) qc.append(lib.U3Gate(0.5, 0.25, 0.125), [0]) qc.append(lib.U2Gate(0.5, 0.25), [0]) qc.append(lib.U1Gate(0.5), [0]) qc.append(lib.CXGate(), [0, 1]) qc.append(lib.IGate(), [0]) qc.append(lib.XGate(), [0]) qc.append(lib.YGate(), [0]) qc.append(lib.ZGate(), [0]) qc.append(lib.HGate(), [0]) qc.append(lib.SGate(), [0]) qc.append(lib.SdgGate(), [0]) qc.append(lib.TGate(), [0]) qc.append(lib.TdgGate(), [0]) qc.append(lib.RXGate(0.5), [0]) qc.append(lib.RYGate(0.5), [0]) qc.append(lib.RZGate(0.5), [0]) qc.append(lib.CZGate(), [0, 1]) qc.append(lib.CYGate(), [0, 1]) qc.append(lib.CHGate(), [0, 1]) qc.append(lib.CCXGate(), [0, 1, 2]) qc.append(lib.CRZGate(0.5), [0, 1]) qc.append(lib.CU1Gate(0.5), [0, 1]) qc.append(lib.CU3Gate(0.5, 0.25, 0.125), [0, 1]) self.assertEqual(parsed, qc) # Also test that the output matches what Qiskit puts out. from_qiskit = QuantumCircuit.from_qasm_str(program) self.assertEqual(parsed, from_qiskit) def test_qelib1_sparse_overrides(self): """Test that the qelib1 special import still works as expected when a couple of gates in the middle of it are custom. As long as qelib1 is handled specially, there is a risk that this handling will break in weird ways when custom instructions overlap it.""" program = """ include "qelib1.inc"; qreg q[3]; u3(0.5, 0.25, 0.125) q[0]; u2(0.5, 0.25) q[0]; u1(0.5) q[0]; cx q[0], q[1]; id q[0]; x q[0]; y q[0]; z q[0]; h q[0]; s q[0]; sdg q[0]; t q[0]; tdg q[0]; rx(0.5) q[0]; ry(0.5) q[0]; rz(0.5) q[0]; cz q[0], q[1]; cy q[0], q[1]; ch q[0], q[1]; ccx q[0], q[1], q[2]; crz(0.5) q[0], q[1]; cu1(0.5) q[0], q[1]; cu3(0.5, 0.25, 0.125) q[0], q[1]; """ parsed = qiskit.qasm2.loads( program, custom_instructions=[ qiskit.qasm2.CustomInstruction("id", 0, 1, lib.IGate), qiskit.qasm2.CustomInstruction("h", 0, 1, lib.HGate), qiskit.qasm2.CustomInstruction("crz", 1, 2, lib.CRZGate), ], ) qc = QuantumCircuit(QuantumRegister(3, "q")) qc.append(lib.U3Gate(0.5, 0.25, 0.125), [0]) qc.append(lib.U2Gate(0.5, 0.25), [0]) qc.append(lib.U1Gate(0.5), [0]) qc.append(lib.CXGate(), [0, 1]) qc.append(lib.IGate(), [0]) qc.append(lib.XGate(), [0]) qc.append(lib.YGate(), [0]) qc.append(lib.ZGate(), [0]) qc.append(lib.HGate(), [0]) qc.append(lib.SGate(), [0]) qc.append(lib.SdgGate(), [0]) qc.append(lib.TGate(), [0]) qc.append(lib.TdgGate(), [0]) qc.append(lib.RXGate(0.5), [0]) qc.append(lib.RYGate(0.5), [0]) qc.append(lib.RZGate(0.5), [0]) qc.append(lib.CZGate(), [0, 1]) qc.append(lib.CYGate(), [0, 1]) qc.append(lib.CHGate(), [0, 1]) qc.append(lib.CCXGate(), [0, 1, 2]) qc.append(lib.CRZGate(0.5), [0, 1]) qc.append(lib.CU1Gate(0.5), [0, 1]) qc.append(lib.CU3Gate(0.5, 0.25, 0.125), [0, 1]) self.assertEqual(parsed, qc) def test_user_gate_after_overidden_qelib1(self): program = """ include "qelib1.inc"; qreg q[1]; opaque my_gate q; my_gate q[0]; """ parsed = qiskit.qasm2.loads( program, custom_instructions=qiskit.qasm2.LEGACY_CUSTOM_INSTRUCTIONS ) qc = QuantumCircuit(QuantumRegister(1, "q")) qc.append(Gate("my_gate", 1, []), [0]) self.assertEqual(parsed, qc) def test_qiskit_extra_builtins(self): program = """ qreg q[5]; u(0.5 ,0.25, 0.125) q[0]; p(0.5) q[0]; sx q[0]; sxdg q[0]; swap q[0], q[1]; cswap q[0], q[1], q[2]; crx(0.5) q[0], q[1]; cry(0.5) q[0], q[1]; cp(0.5) q[0], q[1]; csx q[0], q[1]; cu(0.5, 0.25, 0.125, 0.0625) q[0], q[1]; rxx(0.5) q[0], q[1]; rzz(0.5) q[0], q[1]; rccx q[0], q[1], q[2]; rc3x q[0], q[1], q[2], q[3]; c3x q[0], q[1], q[2], q[3]; c3sqrtx q[0], q[1], q[2], q[3]; c4x q[0], q[1], q[2], q[3], q[4]; """ parsed = qiskit.qasm2.loads( program, custom_instructions=qiskit.qasm2.LEGACY_CUSTOM_INSTRUCTIONS ) qc = QuantumCircuit(QuantumRegister(5, "q")) qc.append(lib.UGate(0.5, 0.25, 0.125), [0]) qc.append(lib.PhaseGate(0.5), [0]) qc.append(lib.SXGate(), [0]) qc.append(lib.SXdgGate(), [0]) qc.append(lib.SwapGate(), [0, 1]) qc.append(lib.CSwapGate(), [0, 1, 2]) qc.append(lib.CRXGate(0.5), [0, 1]) qc.append(lib.CRYGate(0.5), [0, 1]) qc.append(lib.CPhaseGate(0.5), [0, 1]) qc.append(lib.CSXGate(), [0, 1]) qc.append(lib.CUGate(0.5, 0.25, 0.125, 0.0625), [0, 1]) qc.append(lib.RXXGate(0.5), [0, 1]) qc.append(lib.RZZGate(0.5), [0, 1]) qc.append(lib.RCCXGate(), [0, 1, 2]) qc.append(lib.RC3XGate(), [0, 1, 2, 3]) qc.append(lib.C3XGate(), [0, 1, 2, 3]) qc.append(lib.C3SXGate(), [0, 1, 2, 3]) qc.append(lib.C4XGate(), [0, 1, 2, 3, 4]) self.assertEqual(parsed, qc) # There's also the 'u0' gate, but this is weird so we don't wildly care what its definition # is and it has no Qiskit equivalent, so we'll just test that it using it doesn't produce an # error. parsed = qiskit.qasm2.loads( "qreg q[1]; u0(1) q[0];", custom_instructions=qiskit.qasm2.LEGACY_CUSTOM_INSTRUCTIONS ) self.assertEqual(parsed.data[0].operation.name, "u0") def test_qiskit_override_delay_opaque(self): program = """ opaque delay(t) q; qreg q[1]; delay(1) q[0]; """ parsed = qiskit.qasm2.loads( program, custom_instructions=qiskit.qasm2.LEGACY_CUSTOM_INSTRUCTIONS ) qc = QuantumCircuit(QuantumRegister(1, "q")) qc.delay(1, 0, unit="dt") self.assertEqual(parsed, qc) def test_qiskit_override_u0_opaque(self): program = """ opaque u0(n) q; qreg q[1]; u0(2) q[0]; """ parsed = qiskit.qasm2.loads( program, custom_instructions=qiskit.qasm2.LEGACY_CUSTOM_INSTRUCTIONS ) qc = QuantumCircuit(QuantumRegister(1, "q")) qc.id(0) qc.id(0) self.assertEqual(parsed.decompose(), qc) def test_can_override_u(self): program = """ qreg q[1]; U(0.5, 0.25, 0.125) q[0]; """ class MyGate(Gate): def __init__(self, a, b, c): super().__init__("u", 1, [a, b, c]) parsed = qiskit.qasm2.loads( program, custom_instructions=[qiskit.qasm2.CustomInstruction("U", 3, 1, MyGate, builtin=True)], ) qc = QuantumCircuit(QuantumRegister(1, "q")) qc.append(MyGate(0.5, 0.25, 0.125), [0]) self.assertEqual(parsed, qc) def test_can_override_cx(self): program = """ qreg q[2]; CX q[0], q[1]; """ class MyGate(Gate): def __init__(self): super().__init__("cx", 2, []) parsed = qiskit.qasm2.loads( program, custom_instructions=[qiskit.qasm2.CustomInstruction("CX", 0, 2, MyGate, builtin=True)], ) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.append(MyGate(), [0, 1]) self.assertEqual(parsed, qc) @ddt.data(lambda x: x, reversed) def test_can_override_both_builtins_with_other_gates(self, order): program = """ gate unimportant q {} qreg q[2]; U(0.5, 0.25, 0.125) q[0]; CX q[0], q[1]; """ class MyUGate(Gate): def __init__(self, a, b, c): super().__init__("u", 1, [a, b, c]) class MyCXGate(Gate): def __init__(self): super().__init__("cx", 2, []) custom = [ qiskit.qasm2.CustomInstruction("unused", 0, 1, lambda: Gate("unused", 1, [])), qiskit.qasm2.CustomInstruction("U", 3, 1, MyUGate, builtin=True), qiskit.qasm2.CustomInstruction("CX", 0, 2, MyCXGate, builtin=True), ] custom = order(custom) parsed = qiskit.qasm2.loads(program, custom_instructions=custom) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.append(MyUGate(0.5, 0.25, 0.125), [0]) qc.append(MyCXGate(), [0, 1]) self.assertEqual(parsed, qc) def test_custom_builtin_gate(self): program = """ qreg q[1]; builtin(0.5) q[0]; """ class MyGate(Gate): def __init__(self, a): super().__init__("builtin", 1, [a]) parsed = qiskit.qasm2.loads( program, custom_instructions=[ qiskit.qasm2.CustomInstruction("builtin", 1, 1, MyGate, builtin=True) ], ) qc = QuantumCircuit(QuantumRegister(1, "q")) qc.append(MyGate(0.5), [0]) self.assertEqual(parsed, qc) def test_can_define_builtin_as_gate(self): program = """ qreg q[1]; gate builtin(t) q {} builtin(0.5) q[0]; """ class MyGate(Gate): def __init__(self, a): super().__init__("builtin", 1, [a]) parsed = qiskit.qasm2.loads( program, custom_instructions=[ qiskit.qasm2.CustomInstruction("builtin", 1, 1, MyGate, builtin=True) ], ) qc = QuantumCircuit(QuantumRegister(1, "q")) qc.append(MyGate(0.5), [0]) self.assertEqual(parsed, qc) def test_can_define_builtin_as_opaque(self): program = """ qreg q[1]; opaque builtin(t) q; builtin(0.5) q[0]; """ class MyGate(Gate): def __init__(self, a): super().__init__("builtin", 1, [a]) parsed = qiskit.qasm2.loads( program, custom_instructions=[ qiskit.qasm2.CustomInstruction("builtin", 1, 1, MyGate, builtin=True) ], ) qc = QuantumCircuit(QuantumRegister(1, "q")) qc.append(MyGate(0.5), [0]) self.assertEqual(parsed, qc) def test_can_define_custom_as_gate(self): program = """ qreg q[1]; gate my_gate(t) q {} my_gate(0.5) q[0]; """ class MyGate(Gate): def __init__(self, a): super().__init__("my_gate", 1, [a]) parsed = qiskit.qasm2.loads( program, custom_instructions=[qiskit.qasm2.CustomInstruction("my_gate", 1, 1, MyGate)] ) qc = QuantumCircuit(QuantumRegister(1, "q")) qc.append(MyGate(0.5), [0]) self.assertEqual(parsed, qc) def test_can_define_custom_as_opaque(self): program = """ qreg q[1]; opaque my_gate(t) q; my_gate(0.5) q[0]; """ class MyGate(Gate): def __init__(self, a): super().__init__("my_gate", 1, [a]) parsed = qiskit.qasm2.loads( program, custom_instructions=[qiskit.qasm2.CustomInstruction("my_gate", 1, 1, MyGate)] ) qc = QuantumCircuit(QuantumRegister(1, "q")) qc.append(MyGate(0.5), [0]) self.assertEqual(parsed, qc) class TestCustomClassical(QiskitTestCase): def test_qiskit_extensions(self): program = """ include "qelib1.inc"; qreg q[1]; rx(asin(0.3)) q[0]; ry(acos(0.3)) q[0]; rz(atan(0.3)) q[0]; """ parsed = qiskit.qasm2.loads(program, custom_classical=qiskit.qasm2.LEGACY_CUSTOM_CLASSICAL) qc = QuantumCircuit(QuantumRegister(1, "q")) qc.rx(math.asin(0.3), 0) qc.ry(math.acos(0.3), 0) qc.rz(math.atan(0.3), 0) self.assertEqual(parsed, qc) def test_zero_parameter_custom(self): program = """ qreg q[1]; U(f(), 0, 0) q[0]; """ parsed = qiskit.qasm2.loads( program, custom_classical=[qiskit.qasm2.CustomClassical("f", 0, lambda: 0.2)] ) qc = QuantumCircuit(QuantumRegister(1, "q")) qc.u(0.2, 0, 0, 0) self.assertEqual(parsed, qc) def test_multi_parameter_custom(self): program = """ qreg q[1]; U(f(0.2), g(0.4, 0.1), h(1, 2, 3)) q[0]; """ parsed = qiskit.qasm2.loads( program, custom_classical=[ qiskit.qasm2.CustomClassical("f", 1, lambda x: 1 + x), qiskit.qasm2.CustomClassical("g", 2, math.atan2), qiskit.qasm2.CustomClassical("h", 3, lambda x, y, z: z - y + x), ], ) qc = QuantumCircuit(QuantumRegister(1, "q")) qc.u(1.2, math.atan2(0.4, 0.1), 2, 0) self.assertEqual(parsed, qc) def test_use_in_gate_definition(self): # pylint: disable=invalid-name program = """ gate my_gate(a, b) q { U(f(a, b), g(f(b, f(b, a))), b) q; } qreg q[1]; my_gate(0.5, 0.25) q[0]; my_gate(0.25, 0.5) q[0]; """ f = lambda x, y: x - y g = lambda x: 2 * x parsed = qiskit.qasm2.loads( program, custom_classical=[ qiskit.qasm2.CustomClassical("f", 2, f), qiskit.qasm2.CustomClassical("g", 1, g), ], ) first_gate = parsed.data[0].operation second_gate = parsed.data[1].operation self.assertEqual(list(first_gate.params), [0.5, 0.25]) self.assertEqual(list(second_gate.params), [0.25, 0.5]) self.assertEqual( list(first_gate.definition.data[0].operation.params), [ f(0.5, 0.25), g(f(0.25, f(0.25, 0.5))), 0.25, ], ) self.assertEqual( list(second_gate.definition.data[0].operation.params), [ f(0.25, 0.5), g(f(0.5, f(0.5, 0.25))), 0.5, ], ) @ddt.ddt class TestStrict(QiskitTestCase): @ddt.data( "gate my_gate(p0, p1$) q0, q1 {}", "gate my_gate(p0, p1) q0, q1$ {}", "opaque my_gate(p0, p1$) q0, q1;", "opaque my_gate(p0, p1) q0, q1$;", 'include "qelib1.inc"; qreg q[2]; cu3(0.5, 0.25, 0.125$) q[0], q[1];', 'include "qelib1.inc"; qreg q[2]; cu3(0.5, 0.25, 0.125) q[0], q[1]$;', "qreg q[2]; barrier q[0], q[1]$;", 'include "qelib1.inc"; qreg q[1]; rx(sin(pi$)) q[0];', ) def test_trailing_comma(self, program): without = qiskit.qasm2.loads("OPENQASM 2.0;\n" + program.replace("$", ""), strict=True) with_ = qiskit.qasm2.loads(program.replace("$", ","), strict=False) self.assertEqual(with_, without) def test_trailing_semicolon_after_gate(self): program = """ include "qelib1.inc"; gate bell a, b { h a; cx a, b; }; // <- the important bit of the test qreg q[2]; bell q[0], q[1]; """ parsed = qiskit.qasm2.loads(program) bell_def = QuantumCircuit([Qubit(), Qubit()]) bell_def.h(0) bell_def.cx(0, 1) bell = gate_builder("bell", [], bell_def) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.append(bell(), [0, 1]) self.assertEqual(parsed, qc) def test_empty_statement(self): # This is allowed more as a side-effect of allowing the trailing semicolon after gate # definitions. program = """ OPENQASM 2.0; include "qelib1.inc"; qreg q[2]; h q[0]; ; cx q[0], q[1]; ;;;; """ parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(2, "q")) qc.h(0) qc.cx(0, 1) self.assertEqual(parsed, qc) def test_single_quoted_path(self): program = """ include 'qelib1.inc'; qreg q[1]; h q[0]; """ parsed = qiskit.qasm2.loads(program) qc = QuantumCircuit(QuantumRegister(1, "q")) qc.h(0) self.assertEqual(parsed, qc)
https://github.com/swe-train/qiskit__qiskit
swe-train
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__