def measure(qubits: List[int], backend=None, inst_map: Optional[InstructionScheduleMap] = None, meas_map: Optional[Union[List[List[int]], Dict[int, List[int]]]] = None, qubit_mem_slots: Optional[Dict[int, int]] = None, measure_name: str = 'measure') -> Schedule: """Return a schedule which measures the requested qubits according to the given instruction mapping and measure map, or by using the defaults provided by the backend. By default, the measurement results for each qubit are trivially mapped to the qubit index. This behavior is overridden by qubit_mem_slots. For instance, to measure qubit 0 into MemorySlot(1), qubit_mem_slots can be provided as {0: 1}. Args: qubits: List of qubits to be measured. backend (Union[Backend, BaseBackend]): A backend instance, which contains hardware-specific data required for scheduling. inst_map: Mapping of circuit operations to pulse schedules. If None, defaults to the ``instruction_schedule_map`` of ``backend``. meas_map: List of sets of qubits that must be measured together. If None, defaults to the ``meas_map`` of ``backend``. qubit_mem_slots: Mapping of measured qubit index to classical bit index. measure_name: Name of the measurement schedule. Returns: A measurement schedule corresponding to the inputs provided. Raises: PulseError: If both ``inst_map`` or ``meas_map``, and ``backend`` is None. """ schedule = Schedule( name="Default measurement schedule for qubits {}".format(qubits)) try: inst_map = inst_map or backend.defaults().instruction_schedule_map meas_map = meas_map or backend.configuration().meas_map except AttributeError: raise exceptions.PulseError( 'inst_map or meas_map, and backend cannot be None simultaneously') if isinstance(meas_map, list): meas_map = utils.format_meas_map(meas_map) measure_groups = set() for qubit in qubits: measure_groups.add(tuple(meas_map[qubit])) for measure_group_qubits in measure_groups: if qubit_mem_slots is not None: unused_mem_slots = set(measure_group_qubits) - set( qubit_mem_slots.values()) try: default_sched = inst_map.get(measure_name, measure_group_qubits) except exceptions.PulseError: raise exceptions.PulseError( "We could not find a default measurement schedule called '{}'. " "Please provide another name using the 'measure_name' keyword " "argument. For assistance, the instructions which are defined are: " "{}".format(measure_name, inst_map.instructions)) for time, inst in default_sched.instructions: if qubit_mem_slots and isinstance(inst, instructions.Acquire): if inst.channel.index in qubit_mem_slots: mem_slot = channels.MemorySlot( qubit_mem_slots[inst.channel.index]) else: mem_slot = channels.MemorySlot(unused_mem_slots.pop()) schedule = schedule.insert( time, instructions.Acquire(inst.duration, inst.channel, mem_slot=mem_slot)) elif qubit_mem_slots is None and isinstance( inst, instructions.Acquire): schedule = schedule.insert(time, inst) # Measurement pulses should only be added if its qubit was measured by the user elif inst.channels[0].index in qubits: schedule = schedule.insert(time, inst) return schedule
def align_measures( schedules: Iterable[ScheduleComponent], inst_map: Optional[InstructionScheduleMap] = None, cal_gate: str = "u3", max_calibration_duration: Optional[int] = None, align_time: Optional[int] = None, align_all: Optional[bool] = True, ) -> List[Schedule]: """Return new schedules where measurements occur at the same physical time. This transformation will align the first :class:`.Acquire` on every channel to occur at the same time. Minimum measurement wait time (to allow for calibration pulses) is enforced and may be set with ``max_calibration_duration``. By default only instructions containing a :class:`.AcquireChannel` or :class:`.MeasureChannel` will be shifted. If you wish to keep the relative timing of all instructions in the schedule set ``align_all=True``. This method assumes that ``MeasureChannel(i)`` and ``AcquireChannel(i)`` correspond to the same qubit and the acquire/play instructions should be shifted together on these channels. .. jupyter-kernel:: python3 :id: align_measures .. jupyter-execute:: from qiskit import pulse from qiskit.pulse import transforms d0 = pulse.DriveChannel(0) m0 = pulse.MeasureChannel(0) a0 = pulse.AcquireChannel(0) mem0 = pulse.MemorySlot(0) sched = pulse.Schedule() sched.append(pulse.Play(pulse.Constant(10, 0.5), d0), inplace=True) sched.append(pulse.Play(pulse.Constant(10, 1.), m0).shift(sched.duration), inplace=True) sched.append(pulse.Acquire(20, a0, mem0).shift(sched.duration), inplace=True) sched_shifted = sched << 20 aligned_sched, aligned_sched_shifted = transforms.align_measures([sched, sched_shifted]) assert aligned_sched == aligned_sched_shifted If it is desired to only shift acquisition and measurement stimulus instructions set the flag ``align_all=False``: .. jupyter-execute:: aligned_sched, aligned_sched_shifted = transforms.align_measures( [sched, sched_shifted], align_all=False, ) assert aligned_sched != aligned_sched_shifted Args: schedules: Collection of schedules to be aligned together inst_map: Mapping of circuit operations to pulse schedules cal_gate: The name of the gate to inspect for the calibration time max_calibration_duration: If provided, inst_map and cal_gate will be ignored align_time: If provided, this will be used as final align time. align_all: Shift all instructions in the schedule such that they maintain their relative alignment with the shifted acquisition instruction. If ``False`` only the acquisition and measurement pulse instructions will be shifted. Returns: The input list of schedules transformed to have their measurements aligned. Raises: PulseError: If the provided alignment time is negative. """ def get_first_acquire_times(schedules): """Return a list of first acquire times for each schedule.""" acquire_times = [] for schedule in schedules: visited_channels = set() qubit_first_acquire_times = defaultdict(lambda: None) for time, inst in schedule.instructions: if isinstance(inst, instructions.Acquire ) and inst.channel not in visited_channels: visited_channels.add(inst.channel) qubit_first_acquire_times[inst.channel.index] = time acquire_times.append(qubit_first_acquire_times) return acquire_times def get_max_calibration_duration(inst_map, cal_gate): """Return the time needed to allow for readout discrimination calibration pulses.""" # TODO (qiskit-terra #5472): fix behavior of this. max_calibration_duration = 0 for qubits in inst_map.qubits_with_instruction(cal_gate): cmd = inst_map.get(cal_gate, qubits, np.pi, 0, np.pi) max_calibration_duration = max(cmd.duration, max_calibration_duration) return max_calibration_duration if align_time is not None and align_time < 0: raise exceptions.PulseError("Align time cannot be negative.") first_acquire_times = get_first_acquire_times(schedules) # Extract the maximum acquire in every schedule across all acquires in the schedule. # If there are no acquires in the schedule default to 0. max_acquire_times = [ max(0, *times.values()) for times in first_acquire_times ] if align_time is None: if max_calibration_duration is None: if inst_map: max_calibration_duration = get_max_calibration_duration( inst_map, cal_gate) else: max_calibration_duration = 0 align_time = max(max_calibration_duration, *max_acquire_times) # Shift acquires according to the new scheduled time new_schedules = [] for sched_idx, schedule in enumerate(schedules): new_schedule = Schedule.initialize_from(schedule) stop_time = schedule.stop_time if align_all: if first_acquire_times[sched_idx]: shift = align_time - max_acquire_times[sched_idx] else: shift = align_time - stop_time else: shift = 0 for time, inst in schedule.instructions: measurement_channels = { chan.index for chan in inst.channels if isinstance(chan, (chans.MeasureChannel, chans.AcquireChannel)) } if measurement_channels: sched_first_acquire_times = first_acquire_times[sched_idx] max_start_time = max(sched_first_acquire_times[chan] for chan in measurement_channels if chan in sched_first_acquire_times) shift = align_time - max_start_time if shift < 0: warnings.warn( "The provided alignment time is scheduling an acquire instruction " "earlier than it was scheduled for in the original Schedule. " "This may result in an instruction being scheduled before t=0 and " "an error being raised.") new_schedule.insert(time + shift, inst, inplace=True) new_schedules.append(new_schedule) return new_schedules
def align_measures(schedules: Iterable[interfaces.ScheduleComponent], inst_map: Optional[InstructionScheduleMap] = None, cal_gate: str = 'u3', max_calibration_duration: Optional[int] = None, align_time: Optional[int] = None) -> List[Schedule]: """Return new schedules where measurements occur at the same physical time. Minimum measurement wait time (to allow for calibration pulses) is enforced. This is only defined for schedules that are acquire-less or acquire-final per channel: a schedule with pulses or acquires occurring on a channel which has already had a measurement will throw an error. Args: schedules: Collection of schedules to be aligned together inst_map: Mapping of circuit operations to pulse schedules cal_gate: The name of the gate to inspect for the calibration time max_calibration_duration: If provided, inst_map and cal_gate will be ignored align_time: If provided, this will be used as final align time. Returns: The input list of schedules transformed to have their measurements aligned. Raises: PulseError: if an acquire or pulse is encountered on a channel that has already been part of an acquire, or if align_time is negative """ def calculate_align_time(): """Return the the max between the duration of the calibration time and the absolute time of the latest scheduled acquire. """ nonlocal max_calibration_duration if max_calibration_duration is None: max_calibration_duration = get_max_calibration_duration() align_time = max_calibration_duration for schedule in schedules: last_acquire = 0 acquire_times = [ time for time, inst in schedule.instructions if isinstance(inst, (instructions.Acquire, commands.AcquireInstruction)) ] if acquire_times: last_acquire = max(acquire_times) align_time = max(align_time, last_acquire) return align_time def get_max_calibration_duration(): """Return the time needed to allow for readout discrimination calibration pulses.""" max_calibration_duration = 0 for qubits in inst_map.qubits_with_instruction(cal_gate): cmd = inst_map.get(cal_gate, qubits, np.pi, 0, np.pi) max_calibration_duration = max(cmd.duration, max_calibration_duration) return max_calibration_duration if align_time is None and max_calibration_duration is None and inst_map is None: raise exceptions.PulseError( "Must provide a inst_map, an alignment time, " "or a calibration duration.") if align_time is not None and align_time < 0: raise exceptions.PulseError("Align time cannot be negative.") if align_time is None: align_time = calculate_align_time() # Shift acquires according to the new scheduled time new_schedules = [] for schedule in schedules: new_schedule = Schedule(name=schedule.name) acquired_channels = set() measured_channels = set() for time, inst in schedule.instructions: for chan in inst.channels: if isinstance(chan, chans.MeasureChannel): if chan.index in measured_channels: raise exceptions.PulseError( "Multiple measurements are " "not supported by this " "rescheduling pass.") elif chan.index in acquired_channels: raise exceptions.PulseError("Pulse encountered on channel " "{0} after acquire on " "same channel.".format( chan.index)) if isinstance(inst, (instructions.Acquire, commands.AcquireInstruction)): if time > align_time: warnings.warn( "You provided an align_time which is scheduling an acquire " "sooner than it was scheduled for in the original Schedule." ) new_schedule |= inst << align_time acquired_channels.add(inst.channel.index) elif isinstance(inst.channels[0], chans.MeasureChannel): new_schedule |= inst << align_time measured_channels.update({a.index for a in inst.channels}) else: new_schedule |= inst << time new_schedules.append(new_schedule) return new_schedules