/
schedule.py
1861 lines (1477 loc) · 71.3 KB
/
schedule.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=cyclic-import
"""
=========
Schedules
=========
.. currentmodule:: qiskit.pulse
Schedules are Pulse programs. They describe instruction sequences for the control hardware.
The Schedule is one of the most fundamental objects to this pulse-level programming module.
A ``Schedule`` is a representation of a *program* in Pulse. Each schedule tracks the time of each
instruction occuring in parallel over multiple signal *channels*.
.. autosummary::
:toctree: ../stubs/
Schedule
ScheduleBlock
"""
from __future__ import annotations
import abc
import copy
import functools
import itertools
import multiprocessing as mp
import sys
import warnings
from collections.abc import Callable, Iterable
from typing import List, Tuple, Union, Dict, Any, Sequence
import numpy as np
import rustworkx as rx
from qiskit.circuit import ParameterVector
from qiskit.circuit.parameter import Parameter
from qiskit.circuit.parameterexpression import ParameterExpression, ParameterValueType
from qiskit.pulse.channels import Channel
from qiskit.pulse.exceptions import PulseError, UnassignedReferenceError
from qiskit.pulse.instructions import Instruction, Reference
from qiskit.pulse.utils import instruction_duration_validation
from qiskit.pulse.reference_manager import ReferenceManager
from qiskit.utils.multiprocessing import is_main_process
from qiskit.utils import deprecate_arg
Interval = Tuple[int, int]
"""An interval type is a tuple of a start time (inclusive) and an end time (exclusive)."""
TimeSlots = Dict[Channel, List[Interval]]
"""List of timeslots occupied by instructions for each channel."""
class Schedule:
"""A quantum program *schedule* with exact time constraints for its instructions, operating
over all input signal *channels* and supporting special syntaxes for building.
Pulse program representation for the original Qiskit Pulse model [1].
Instructions are not allowed to overlap in time
on the same channel. This overlap constraint is immediately
evaluated when a new instruction is added to the ``Schedule`` object.
It is necessary to specify the absolute start time and duration
for each instruction so as to deterministically fix its execution time.
The ``Schedule`` program supports some syntax sugar for easier programming.
- Appending an instruction to the end of a channel
.. code-block:: python
sched = Schedule()
sched += Play(Gaussian(160, 0.1, 40), DriveChannel(0))
- Appending an instruction shifted in time by a given amount
.. code-block:: python
sched = Schedule()
sched += Play(Gaussian(160, 0.1, 40), DriveChannel(0)) << 30
- Merge two schedules
.. code-block:: python
sched1 = Schedule()
sched1 += Play(Gaussian(160, 0.1, 40), DriveChannel(0))
sched2 = Schedule()
sched2 += Play(Gaussian(160, 0.1, 40), DriveChannel(1))
sched2 = sched1 | sched2
A :obj:`.PulseError` is immediately raised when the overlap constraint is violated.
In the schedule representation, we cannot parametrize the duration of instructions.
Thus, we need to create a new schedule object for each duration.
To parametrize an instruction's duration, the :class:`~qiskit.pulse.ScheduleBlock`
representation may be used instead.
References:
[1]: https://arxiv.org/abs/2004.06755
"""
# Prefix to use for auto naming.
prefix = "sched"
# Counter to count instance number.
instances_counter = itertools.count()
def __init__(
self,
*schedules: "ScheduleComponent" | tuple[int, "ScheduleComponent"],
name: str | None = None,
metadata: dict | None = None,
):
"""Create an empty schedule.
Args:
*schedules: Child Schedules of this parent Schedule. May either be passed as
the list of schedules, or a list of ``(start_time, schedule)`` pairs.
name: Name of this schedule. Defaults to an autogenerated string if not provided.
metadata: Arbitrary key value metadata to associate with the schedule. This gets
stored as free-form data in a dict in the
:attr:`~qiskit.pulse.Schedule.metadata` attribute. It will not be directly
used in the schedule.
Raises:
TypeError: if metadata is not a dict.
"""
from qiskit.pulse.parameter_manager import ParameterManager
if name is None:
name = self.prefix + str(next(self.instances_counter))
if sys.platform != "win32" and not is_main_process():
name += f"-{mp.current_process().pid}"
self._name = name
self._parameter_manager = ParameterManager()
if not isinstance(metadata, dict) and metadata is not None:
raise TypeError("Only a dictionary or None is accepted for schedule metadata")
self._metadata = metadata or {}
self._duration = 0
# These attributes are populated by ``_mutable_insert``
self._timeslots: TimeSlots = {}
self._children: list[tuple[int, "ScheduleComponent"]] = []
for sched_pair in schedules:
try:
time, sched = sched_pair
except TypeError:
# recreate as sequence starting at 0.
time, sched = 0, sched_pair
self._mutable_insert(time, sched)
@classmethod
def initialize_from(cls, other_program: Any, name: str | None = None) -> "Schedule":
"""Create new schedule object with metadata of another schedule object.
Args:
other_program: Qiskit program that provides metadata to new object.
name: Name of new schedule. Name of ``schedule`` is used by default.
Returns:
New schedule object with name and metadata.
Raises:
PulseError: When `other_program` does not provide necessary information.
"""
try:
name = name or other_program.name
if other_program.metadata:
metadata = other_program.metadata.copy()
else:
metadata = None
return cls(name=name, metadata=metadata)
except AttributeError as ex:
raise PulseError(
f"{cls.__name__} cannot be initialized from the program data "
f"{other_program.__class__.__name__}."
) from ex
@property
def name(self) -> str:
"""Name of this Schedule"""
return self._name
@property
def metadata(self) -> dict[str, Any]:
"""The user provided metadata associated with the schedule.
User provided ``dict`` of metadata for the schedule.
The metadata contents do not affect the semantics of the program
but are used to influence the execution of the schedule. It is expected
to be passed between all transforms of the schedule and that providers
will associate any schedule metadata with the results it returns from the
execution of that schedule.
"""
return self._metadata
@metadata.setter
def metadata(self, metadata):
"""Update the schedule metadata"""
if not isinstance(metadata, dict) and metadata is not None:
raise TypeError("Only a dictionary or None is accepted for schedule metadata")
self._metadata = metadata or {}
@property
def timeslots(self) -> TimeSlots:
"""Time keeping attribute."""
return self._timeslots
@property
def duration(self) -> int:
"""Duration of this schedule."""
return self._duration
@property
def start_time(self) -> int:
"""Starting time of this schedule."""
return self.ch_start_time(*self.channels)
@property
def stop_time(self) -> int:
"""Stopping time of this schedule."""
return self.duration
@property
def channels(self) -> tuple[Channel, ...]:
"""Returns channels that this schedule uses."""
return tuple(self._timeslots.keys())
@property
def children(self) -> tuple[tuple[int, "ScheduleComponent"], ...]:
"""Return the child schedule components of this ``Schedule`` in the
order they were added to the schedule.
Notes:
Nested schedules are returned as-is. If you want to collect only instructions,
use py:meth:`~Schedule.instructions` instead.
Returns:
A tuple, where each element is a two-tuple containing the initial
scheduled time of each ``NamedValue`` and the component
itself.
"""
return tuple(self._children)
@property
def instructions(self) -> tuple[tuple[int, Instruction], ...]:
"""Get the time-ordered instructions from self."""
def key(time_inst_pair):
inst = time_inst_pair[1]
return time_inst_pair[0], inst.duration, sorted(chan.name for chan in inst.channels)
return tuple(sorted(self._instructions(), key=key))
@property
def parameters(self) -> set[Parameter]:
"""Parameters which determine the schedule behavior."""
return self._parameter_manager.parameters
def ch_duration(self, *channels: Channel) -> int:
"""Return the time of the end of the last instruction over the supplied channels.
Args:
*channels: Channels within ``self`` to include.
"""
return self.ch_stop_time(*channels)
def ch_start_time(self, *channels: Channel) -> int:
"""Return the time of the start of the first instruction over the supplied channels.
Args:
*channels: Channels within ``self`` to include.
"""
try:
chan_intervals = (self._timeslots[chan] for chan in channels if chan in self._timeslots)
return min(intervals[0][0] for intervals in chan_intervals)
except ValueError:
# If there are no instructions over channels
return 0
def ch_stop_time(self, *channels: Channel) -> int:
"""Return maximum start time over supplied channels.
Args:
*channels: Channels within ``self`` to include.
"""
try:
chan_intervals = (self._timeslots[chan] for chan in channels if chan in self._timeslots)
return max(intervals[-1][1] for intervals in chan_intervals)
except ValueError:
# If there are no instructions over channels
return 0
def _instructions(self, time: int = 0):
"""Iterable for flattening Schedule tree.
Args:
time: Shifted time due to parent.
Yields:
Iterable[Tuple[int, Instruction]]: Tuple containing the time each
:class:`~qiskit.pulse.Instruction`
starts at and the flattened :class:`~qiskit.pulse.Instruction` s.
"""
for insert_time, child_sched in self.children:
yield from child_sched._instructions(time + insert_time)
def shift(self, time: int, name: str | None = None, inplace: bool = False) -> "Schedule":
"""Return a schedule shifted forward by ``time``.
Args:
time: Time to shift by.
name: Name of the new schedule. Defaults to the name of self.
inplace: Perform operation inplace on this schedule. Otherwise
return a new ``Schedule``.
"""
if inplace:
return self._mutable_shift(time)
return self._immutable_shift(time, name=name)
def _immutable_shift(self, time: int, name: str | None = None) -> "Schedule":
"""Return a new schedule shifted forward by `time`.
Args:
time: Time to shift by
name: Name of the new schedule if call was mutable. Defaults to name of self
"""
shift_sched = Schedule.initialize_from(self, name)
shift_sched.insert(time, self, inplace=True)
return shift_sched
def _mutable_shift(self, time: int) -> "Schedule":
"""Return this schedule shifted forward by `time`.
Args:
time: Time to shift by
Raises:
PulseError: if ``time`` is not an integer.
"""
if not isinstance(time, int):
raise PulseError("Schedule start time must be an integer.")
timeslots = {}
for chan, ch_timeslots in self._timeslots.items():
timeslots[chan] = [(ts[0] + time, ts[1] + time) for ts in ch_timeslots]
_check_nonnegative_timeslot(timeslots)
self._duration = self._duration + time
self._timeslots = timeslots
self._children = [(orig_time + time, child) for orig_time, child in self.children]
return self
def insert(
self,
start_time: int,
schedule: "ScheduleComponent",
name: str | None = None,
inplace: bool = False,
) -> "Schedule":
"""Return a new schedule with ``schedule`` inserted into ``self`` at ``start_time``.
Args:
start_time: Time to insert the schedule.
schedule: Schedule to insert.
name: Name of the new schedule. Defaults to the name of self.
inplace: Perform operation inplace on this schedule. Otherwise
return a new ``Schedule``.
"""
if inplace:
return self._mutable_insert(start_time, schedule)
return self._immutable_insert(start_time, schedule, name=name)
def _mutable_insert(self, start_time: int, schedule: "ScheduleComponent") -> "Schedule":
"""Mutably insert `schedule` into `self` at `start_time`.
Args:
start_time: Time to insert the second schedule.
schedule: Schedule to mutably insert.
"""
self._add_timeslots(start_time, schedule)
self._children.append((start_time, schedule))
self._parameter_manager.update_parameter_table(schedule)
return self
def _immutable_insert(
self,
start_time: int,
schedule: "ScheduleComponent",
name: str | None = None,
) -> "Schedule":
"""Return a new schedule with ``schedule`` inserted into ``self`` at ``start_time``.
Args:
start_time: Time to insert the schedule.
schedule: Schedule to insert.
name: Name of the new ``Schedule``. Defaults to name of ``self``.
"""
new_sched = Schedule.initialize_from(self, name)
new_sched._mutable_insert(0, self)
new_sched._mutable_insert(start_time, schedule)
return new_sched
def append(
self, schedule: "ScheduleComponent", name: str | None = None, inplace: bool = False
) -> "Schedule":
r"""Return a new schedule with ``schedule`` inserted at the maximum time over
all channels shared between ``self`` and ``schedule``.
.. math::
t = \textrm{max}(\texttt{x.stop_time} |\texttt{x} \in
\texttt{self.channels} \cap \texttt{schedule.channels})
Args:
schedule: Schedule to be appended.
name: Name of the new ``Schedule``. Defaults to name of ``self``.
inplace: Perform operation inplace on this schedule. Otherwise
return a new ``Schedule``.
"""
common_channels = set(self.channels) & set(schedule.channels)
time = self.ch_stop_time(*common_channels)
return self.insert(time, schedule, name=name, inplace=inplace)
def filter(
self,
*filter_funcs: Callable,
channels: Iterable[Channel] | None = None,
instruction_types: Iterable[abc.ABCMeta] | abc.ABCMeta = None,
time_ranges: Iterable[tuple[int, int]] | None = None,
intervals: Iterable[Interval] | None = None,
check_subroutine: bool = True,
) -> "Schedule":
"""Return a new ``Schedule`` with only the instructions from this ``Schedule`` which pass
though the provided filters; i.e. an instruction will be retained iff every function in
``filter_funcs`` returns ``True``, the instruction occurs on a channel type contained in
``channels``, the instruction type is contained in ``instruction_types``, and the period
over which the instruction operates is *fully* contained in one specified in
``time_ranges`` or ``intervals``.
If no arguments are provided, ``self`` is returned.
Args:
filter_funcs: A list of Callables which take a (int, Union['Schedule', Instruction])
tuple and return a bool.
channels: For example, ``[DriveChannel(0), AcquireChannel(0)]``.
instruction_types: For example, ``[PulseInstruction, AcquireInstruction]``.
time_ranges: For example, ``[(0, 5), (6, 10)]``.
intervals: For example, ``[(0, 5), (6, 10)]``.
check_subroutine: Set `True` to individually filter instructions inside of a subroutine
defined by the :py:class:`~qiskit.pulse.instructions.Call` instruction.
"""
from qiskit.pulse.filters import composite_filter, filter_instructions
filters = composite_filter(channels, instruction_types, time_ranges, intervals)
filters.extend(filter_funcs)
return filter_instructions(
self, filters=filters, negate=False, recurse_subroutines=check_subroutine
)
def exclude(
self,
*filter_funcs: Callable,
channels: Iterable[Channel] | None = None,
instruction_types: Iterable[abc.ABCMeta] | abc.ABCMeta = None,
time_ranges: Iterable[tuple[int, int]] | None = None,
intervals: Iterable[Interval] | None = None,
check_subroutine: bool = True,
) -> "Schedule":
"""Return a ``Schedule`` with only the instructions from this Schedule *failing*
at least one of the provided filters.
This method is the complement of py:meth:`~self.filter`, so that::
self.filter(args) | self.exclude(args) == self
Args:
filter_funcs: A list of Callables which take a (int, Union['Schedule', Instruction])
tuple and return a bool.
channels: For example, ``[DriveChannel(0), AcquireChannel(0)]``.
instruction_types: For example, ``[PulseInstruction, AcquireInstruction]``.
time_ranges: For example, ``[(0, 5), (6, 10)]``.
intervals: For example, ``[(0, 5), (6, 10)]``.
check_subroutine: Set `True` to individually filter instructions inside of a subroutine
defined by the :py:class:`~qiskit.pulse.instructions.Call` instruction.
"""
from qiskit.pulse.filters import composite_filter, filter_instructions
filters = composite_filter(channels, instruction_types, time_ranges, intervals)
filters.extend(filter_funcs)
return filter_instructions(
self, filters=filters, negate=True, recurse_subroutines=check_subroutine
)
def _add_timeslots(self, time: int, schedule: "ScheduleComponent") -> None:
"""Update all time tracking within this schedule based on the given schedule.
Args:
time: The time to insert the schedule into self.
schedule: The schedule to insert into self.
Raises:
PulseError: If timeslots overlap or an invalid start time is provided.
"""
if not np.issubdtype(type(time), np.integer):
raise PulseError("Schedule start time must be an integer.")
other_timeslots = _get_timeslots(schedule)
self._duration = max(self._duration, time + schedule.duration)
for channel in schedule.channels:
if channel not in self._timeslots:
if time == 0:
self._timeslots[channel] = copy.copy(other_timeslots[channel])
else:
self._timeslots[channel] = [
(i[0] + time, i[1] + time) for i in other_timeslots[channel]
]
continue
for idx, interval in enumerate(other_timeslots[channel]):
if interval[0] + time >= self._timeslots[channel][-1][1]:
# Can append the remaining intervals
self._timeslots[channel].extend(
[(i[0] + time, i[1] + time) for i in other_timeslots[channel][idx:]]
)
break
try:
interval = (interval[0] + time, interval[1] + time)
index = _find_insertion_index(self._timeslots[channel], interval)
self._timeslots[channel].insert(index, interval)
except PulseError as ex:
raise PulseError(
"Schedule(name='{new}') cannot be inserted into Schedule(name='{old}') at "
"time {time} because its instruction on channel {ch} scheduled from time "
"{t0} to {tf} overlaps with an existing instruction."
"".format(
new=schedule.name or "",
old=self.name or "",
time=time,
ch=channel,
t0=interval[0],
tf=interval[1],
)
) from ex
_check_nonnegative_timeslot(self._timeslots)
def _remove_timeslots(self, time: int, schedule: "ScheduleComponent"):
"""Delete the timeslots if present for the respective schedule component.
Args:
time: The time to remove the timeslots for the ``schedule`` component.
schedule: The schedule to insert into self.
Raises:
PulseError: If timeslots overlap or an invalid start time is provided.
"""
if not isinstance(time, int):
raise PulseError("Schedule start time must be an integer.")
for channel in schedule.channels:
if channel not in self._timeslots:
raise PulseError(f"The channel {channel} is not present in the schedule")
channel_timeslots = self._timeslots[channel]
other_timeslots = _get_timeslots(schedule)
for interval in other_timeslots[channel]:
if channel_timeslots:
interval = (interval[0] + time, interval[1] + time)
index = _interval_index(channel_timeslots, interval)
if channel_timeslots[index] == interval:
channel_timeslots.pop(index)
continue
raise PulseError(
"Cannot find interval ({t0}, {tf}) to remove from "
"channel {ch} in Schedule(name='{name}').".format(
ch=channel, t0=interval[0], tf=interval[1], name=schedule.name
)
)
if not channel_timeslots:
self._timeslots.pop(channel)
def _replace_timeslots(self, time: int, old: "ScheduleComponent", new: "ScheduleComponent"):
"""Replace the timeslots of ``old`` if present with the timeslots of ``new``.
Args:
time: The time to remove the timeslots for the ``schedule`` component.
old: Instruction to replace.
new: Instruction to replace with.
"""
self._remove_timeslots(time, old)
self._add_timeslots(time, new)
def _renew_timeslots(self):
"""Regenerate timeslots based on current instructions."""
self._timeslots.clear()
for t0, inst in self.instructions:
self._add_timeslots(t0, inst)
def replace(
self,
old: "ScheduleComponent",
new: "ScheduleComponent",
inplace: bool = False,
) -> "Schedule":
"""Return a ``Schedule`` with the ``old`` instruction replaced with a ``new``
instruction.
The replacement matching is based on an instruction equality check.
.. code-block::
from qiskit import pulse
d0 = pulse.DriveChannel(0)
sched = pulse.Schedule()
old = pulse.Play(pulse.Constant(100, 1.0), d0)
new = pulse.Play(pulse.Constant(100, 0.1), d0)
sched += old
sched = sched.replace(old, new)
assert sched == pulse.Schedule(new)
Only matches at the top-level of the schedule tree. If you wish to
perform this replacement over all instructions in the schedule tree.
Flatten the schedule prior to running::
.. code-block::
sched = pulse.Schedule()
sched += pulse.Schedule(old)
sched = sched.flatten()
sched = sched.replace(old, new)
assert sched == pulse.Schedule(new)
Args:
old: Instruction to replace.
new: Instruction to replace with.
inplace: Replace instruction by mutably modifying this ``Schedule``.
Returns:
The modified schedule with ``old`` replaced by ``new``.
Raises:
PulseError: If the ``Schedule`` after replacements will has a timing overlap.
"""
from qiskit.pulse.parameter_manager import ParameterManager
new_children = []
new_parameters = ParameterManager()
for time, child in self.children:
if child == old:
new_children.append((time, new))
new_parameters.update_parameter_table(new)
else:
new_children.append((time, child))
new_parameters.update_parameter_table(child)
if inplace:
self._children = new_children
self._parameter_manager = new_parameters
self._renew_timeslots()
return self
else:
try:
new_sched = Schedule.initialize_from(self)
for time, inst in new_children:
new_sched.insert(time, inst, inplace=True)
return new_sched
except PulseError as err:
raise PulseError(
f"Replacement of {old} with {new} results in overlapping instructions."
) from err
def is_parameterized(self) -> bool:
"""Return True iff the instruction is parameterized."""
return self._parameter_manager.is_parameterized()
def assign_parameters(
self,
value_dict: dict[
ParameterExpression | ParameterVector, ParameterValueType | Sequence[ParameterValueType]
],
inplace: bool = True,
) -> "Schedule":
"""Assign the parameters in this schedule according to the input.
Args:
value_dict: A mapping from parameters (parameter vectors) to either
numeric values (list of numeric values)
or another Parameter expression (list of Parameter expressions).
inplace: Set ``True`` to override this instance with new parameter.
Returns:
Schedule with updated parameters.
"""
if not inplace:
new_schedule = copy.deepcopy(self)
return new_schedule.assign_parameters(value_dict, inplace=True)
return self._parameter_manager.assign_parameters(pulse_program=self, value_dict=value_dict)
def get_parameters(self, parameter_name: str) -> list[Parameter]:
"""Get parameter object bound to this schedule by string name.
Because different ``Parameter`` objects can have the same name,
this method returns a list of ``Parameter`` s for the provided name.
Args:
parameter_name: Name of parameter.
Returns:
Parameter objects that have corresponding name.
"""
return self._parameter_manager.get_parameters(parameter_name)
def __len__(self) -> int:
"""Return number of instructions in the schedule."""
return len(self.instructions)
def __add__(self, other: "ScheduleComponent") -> "Schedule":
"""Return a new schedule with ``other`` inserted within ``self`` at ``start_time``."""
return self.append(other)
def __or__(self, other: "ScheduleComponent") -> "Schedule":
"""Return a new schedule which is the union of `self` and `other`."""
return self.insert(0, other)
def __lshift__(self, time: int) -> "Schedule":
"""Return a new schedule which is shifted forward by ``time``."""
return self.shift(time)
def __eq__(self, other: object) -> bool:
"""Test if two Schedule are equal.
Equality is checked by verifying there is an equal instruction at every time
in ``other`` for every instruction in this ``Schedule``.
.. warning::
This does not check for logical equivalency. Ie.,
```python
>>> Delay(10, DriveChannel(0)) + Delay(10, DriveChannel(0))
== Delay(20, DriveChannel(0))
False
```
"""
# 0. type check, we consider Instruction is a subtype of schedule
if not isinstance(other, (type(self), Instruction)):
return False
# 1. channel check
if set(self.channels) != set(other.channels):
return False
# 2. size check
if len(self.instructions) != len(other.instructions):
return False
# 3. instruction check
return all(
self_inst == other_inst
for self_inst, other_inst in zip(self.instructions, other.instructions)
)
def __repr__(self) -> str:
name = format(self._name) if self._name else ""
instructions = ", ".join([repr(instr) for instr in self.instructions[:50]])
if len(self.instructions) > 25:
instructions += ", ..."
return f'{self.__class__.__name__}({instructions}, name="{name}")'
def _require_schedule_conversion(function: Callable) -> Callable:
"""A method decorator to convert schedule block to pulse schedule.
This conversation is performed for backward compatibility only if all durations are assigned.
"""
@functools.wraps(function)
def wrapper(self, *args, **kwargs):
from qiskit.pulse.transforms import block_to_schedule
return function(block_to_schedule(self), *args, **kwargs)
return wrapper
class ScheduleBlock:
"""Time-ordered sequence of instructions with alignment context.
:class:`.ScheduleBlock` supports lazy scheduling of context instructions,
i.e. their timeslots is always generated at runtime.
This indicates we can parametrize instruction durations as well as
other parameters. In contrast to :class:`.Schedule` being somewhat static,
:class:`.ScheduleBlock` is a dynamic representation of a pulse program.
.. rubric:: Pulse Builder
The Qiskit pulse builder is a domain specific language that is developed on top of
the schedule block. Use of the builder syntax will improve the workflow of
pulse programming. See :ref:`pulse_builder` for a user guide.
.. rubric:: Alignment contexts
A schedule block is always relatively scheduled.
Instead of taking individual instructions with absolute execution time ``t0``,
the schedule block defines a context of scheduling and instructions
under the same context are scheduled in the same manner (alignment).
Several contexts are available in :ref:`pulse_alignments`.
A schedule block is instantiated with one of these alignment contexts.
The default context is :class:`AlignLeft`, for which all instructions are left-justified,
in other words, meaning they use as-soon-as-possible scheduling.
If you need an absolute-time interval in between instructions, you can explicitly
insert :class:`~qiskit.pulse.instructions.Delay` instructions.
.. rubric:: Nested blocks
A schedule block can contain other nested blocks with different alignment contexts.
This enables advanced scheduling, where a subset of instructions is
locally scheduled in a different manner.
Note that a :class:`.Schedule` instance cannot be directly added to a schedule block.
To add a :class:`.Schedule` instance, wrap it in a :class:`.Call` instruction.
This is implicitly performed when a schedule is added through the :ref:`pulse_builder`.
.. rubric:: Unsupported operations
Because the schedule block representation lacks timeslots, it cannot
perform particular :class:`.Schedule` operations such as :meth:`insert` or :meth:`shift` that
require instruction start time ``t0``.
In addition, :meth:`exclude` and :meth:`filter` methods are not supported
because these operations may identify the target instruction with ``t0``.
Except for these operations, :class:`.ScheduleBlock` provides full compatibility
with :class:`.Schedule`.
.. rubric:: Subroutine
The timeslots-free representation offers much greater flexibility for writing pulse programs.
Because :class:`.ScheduleBlock` only cares about the ordering of the child blocks
we can add an undefined pulse sequence as a subroutine of the main program.
If your program contains the same sequence multiple times, this representation may
reduce the memory footprint required by the program construction.
Such a subroutine is realized by the special compiler directive
:class:`~qiskit.pulse.instructions.Reference` that is defined by
a unique set of reference key strings to the subroutine.
The (executable) subroutine is separately stored in the main program.
Appended reference directives are resolved when the main program is executed.
Subroutines must be assigned through :meth:`assign_references` before execution.
One way to reference a subroutine in a schedule is to use the pulse
builder's :func:`~qiskit.pulse.builder.reference` function to declare an
unassigned reference. In this example, the program is called with the
reference key "grand_child". You can call a subroutine without specifying
a substantial program.
.. code-block::
from qiskit import pulse
from qiskit.circuit.parameter import Parameter
amp1 = Parameter("amp1")
amp2 = Parameter("amp2")
with pulse.build() as sched_inner:
pulse.play(pulse.Constant(100, amp1), pulse.DriveChannel(0))
with pulse.build() as sched_outer:
with pulse.align_right():
pulse.reference("grand_child")
pulse.play(pulse.Constant(200, amp2), pulse.DriveChannel(0))
Now you assign the inner pulse program to this reference.
.. code-block::
sched_outer.assign_references({("grand_child", ): sched_inner})
print(sched_outer.parameters)
.. parsed-literal::
{Parameter(amp1), Parameter(amp2)}
The outer program now has the parameter ``amp2`` from the inner program,
indicating that the inner program's data has been made available to the
outer program.
The program calling the "grand_child" has a reference program description
which is accessed through :attr:`ScheduleBlock.references`.
.. code-block::
print(sched_outer.references)
.. parsed-literal::
ReferenceManager:
- ('grand_child',): ScheduleBlock(Play(Constant(duration=100, amp=amp1,...
Finally, you may want to call this program from another program.
Here we try a different approach to define subroutine. Namely, we call
a subroutine from the root program with the actual program ``sched2``.
.. code-block::
amp3 = Parameter("amp3")
with pulse.build() as main:
pulse.play(pulse.Constant(300, amp3), pulse.DriveChannel(0))
pulse.call(sched_outer, name="child")
print(main.parameters)
.. parsed-literal::
{Parameter(amp1), Parameter(amp2), Parameter(amp3}
This implicitly creates a reference named "child" within
the root program and assigns ``sched_outer`` to it.
Note that the root program is only aware of its direct references.
.. code-block::
print(main.references)
.. parsed-literal::
ReferenceManager:
- ('child',): ScheduleBlock(ScheduleBlock(ScheduleBlock(Play(Con...
As you can see the main program cannot directly assign a subroutine to the "grand_child" because
this subroutine is not called within the root program, i.e. it is indirectly called by "child".
However, the returned :class:`.ReferenceManager` is a dict-like object, and you can still
reach to "grand_child" via the "child" program with the following chained dict access.
.. code-block::
main.references[("child", )].references[("grand_child", )]
Note that :attr:`ScheduleBlock.parameters` still collects all parameters
also from the subroutine once it's assigned.
"""
__slots__ = (
"_parent",
"_name",
"_reference_manager",
"_parameter_manager",
"_alignment_context",
"_blocks",
"_metadata",
)
# Prefix to use for auto naming.
prefix = "block"
# Counter to count instance number.
instances_counter = itertools.count()
def __init__(
self, name: str | None = None, metadata: dict | None = None, alignment_context=None
):
"""Create an empty schedule block.