• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

Qiskit / qiskit / 13502462770

24 Feb 2025 03:33PM UTC coverage: 87.971% (-0.1%) from 88.112%
13502462770

push

github

web-flow
Remove condition/c_if, duration, and unit from instructions (#13506)

* Remove condition/c_if, duration, and unit from instructions

This commit removes the per instruction attributes for condition,
duration, and unit. These attributes were deprecated in 1.3.0. Besides
the label these attributes were the only mutable state for singleton
instructions and removing them simplifies what needs to be tracked for
instructions in both Python and rust. The associated methods and classes
that were previously dependent on these attributes are also removed as
they no longer serve a purpose. The removal of condition in particular
removes a lot of logic from Qiskit especially from the transpiler
because it was a something that needed to be checked outside of the
normal data model for every operation.

This PR simplifies the representation of this extra mutable state in
Rust by removing the `ExtraInstructionAttributes` struct and replacing
it with a `Option<Box<String>>`. The `Option<Box<String>>` is used
instead of the simpler `Option<String>` because this this reduces the
size of the label field from 24 bytes for `Option<String>` to 8 bytes
for `Option<Box<String>>` with an extra layer of pointer indirection
and a second heap allocation. This will have runtime overhead when
labels are set, but because the vast majority of operations don't set
labels the tradeoff for optimizing for the None case makes more sense.
Another option would have been to use `Box<str>` here which is the
equivalent of `Box<[u8]>` (where `String` is the equivalent to
`Vec<u8>`) and from a runtime memory tradeoff would be a better
choice for this application if labels were commonly used as labels
aren't growable. But that requires 16 bytes instead of 8 and we'd be
wasting an additional 8 bytes for each instruction in the circuit which
isn't worth the cost.

* Update random_circuit

* Update more tests

* Fix new scheduling pass implementation

* Fix clippy::redundant_closure

* Add release no... (continued)

382 of 439 new or added lines in 80 files covered. (87.02%)

189 existing lines in 28 files now uncovered.

77749 of 88380 relevant lines covered (87.97%)

359318.33 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

21.28
/qiskit/visualization/timeline/interface.py
1
# This code is part of Qiskit.
2
#
3
# (C) Copyright IBM 2020.
4
#
5
# This code is licensed under the Apache License, Version 2.0. You may
6
# obtain a copy of this license in the LICENSE.txt file in the root directory
7
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
8
#
9
# Any modifications or derivative works of this code must retain this
10
# copyright notice, and modified files need to carry a notice indicating
11
# that they have been altered from the originals.
12

13
"""Qiskit timeline drawer.
14

15
This module provides a common user interface to the timeline drawer.
16
The `draw` function takes a scheduled circuit to visualize, as well as a style sheet
17
along with several control arguments.
18
The drawer canvas object is internally initialized from the input data and
19
the configured canvas is passed to one of the plotter APIs to generate a visualization data.
20
"""
21

22
from typing import Optional, Dict, Any, List, Tuple
1✔
23

24
from qiskit import circuit
1✔
25
from qiskit.transpiler.target import Target
1✔
26
from qiskit.exceptions import MissingOptionalLibraryError
1✔
27
from qiskit.visualization.exceptions import VisualizationError
1✔
28
from qiskit.visualization.timeline import types, core, stylesheet
1✔
29
from qiskit.utils import deprecate_arg
1✔
30

31

32
@deprecate_arg("show_idle", new_alias="idle_wires", since="1.1.0", pending=True)
1✔
33
@deprecate_arg("show_barriers", new_alias="plot_barriers", since="1.1.0", pending=True)
1✔
34
def draw(
1✔
35
    program: circuit.QuantumCircuit,
36
    style: Optional[Dict[str, Any]] = None,
37
    time_range: Tuple[int, int] = None,
38
    disable_bits: List[types.Bits] = None,
39
    show_clbits: Optional[bool] = None,
40
    idle_wires: Optional[bool] = None,
41
    plot_barriers: Optional[bool] = None,
42
    show_delays: Optional[bool] = None,
43
    show_labels: bool = True,
44
    plotter: Optional[str] = types.Plotter.MPL.value,
45
    axis: Optional[Any] = None,
46
    filename: Optional[str] = None,
47
    target: Optional[Target] = None,
48
    *,
49
    show_idle: Optional[bool] = None,
50
    show_barriers: Optional[bool] = None,
51
):
52
    r"""Generate visualization data for scheduled circuit programs.
53

54
    .. deprecated:: 1.3
55
       The ``target`` parameter needs to be specified in Qiskit 2.0 in order to get the
56
       instruction durations.
57

58
    Args:
59
        program: Program to visualize. This program should be a `QuantumCircuit` which is
60
            transpiled with a scheduling_method, thus containing gate time information.
61
        style: Stylesheet options. This can be dictionary or preset stylesheet classes. See
62
            :py:class:`~qiskit.visualization.timeline.stylesheets.IQXStandard`,
63
            :py:class:`~qiskit.visualization.timeline.stylesheets.IQXSimple`, and
64
            :py:class:`~qiskit.visualization.timeline.stylesheets.IQXDebugging` for details of
65
            preset stylesheets. See also the stylesheet section for details of configuration keys.
66
        time_range: Set horizontal axis limit.
67
        disable_bits: List of qubits of classical bits not shown in the output image.
68
        show_clbits: A control property to show classical bits.
69
            Set `True` to show classical bits.
70
        idle_wires: A control property to show idle timeline.
71
            Set `True` to show timeline without gates.
72
        plot_barriers: A control property to show barrier instructions.
73
            Set `True` to show barrier instructions.
74
        show_delays: A control property to show delay instructions.
75
            Set `True` to show delay instructions.
76
        show_labels: A control property to show annotations, i.e. name, of gates.
77
            Set `True` to show annotations.
78
        plotter: Name of plotter API to generate an output image.
79
            One of following APIs should be specified::
80

81
                mpl: Matplotlib API
82
                    Matplotlib API to generate 2D image. Timelines are placed along y axis with
83
                    vertical offset. This API takes matplotlib.axes.Axes as `axis` input.
84

85
            `axis` and `style` kwargs may depend on the plotter.
86
        axis: Arbitrary object passed to the plotter. If this object is provided,
87
            the plotters uses given `axis` instead of internally initializing a figure object.
88
            This object format depends on the plotter. See plotters section for details.
89
        filename: If provided the output image is dumped into a file under the filename.
90
        target: The target for the backend the timeline is being generated for.
91
        show_idle: DEPRECATED.
92
        show_barriers: DEPRECATED.
93

94
    Returns:
95
        Visualization output data.
96

97
        The returned data type depends on the `plotter`.
98
        If matplotlib family is specified, this will be a `matplotlib.pyplot.Figure` data.
99
        The returned data is generated by the `.get_image` method of the specified plotter API.
100

101
    Raises:
102
        MissingOptionalLibraryError: When required visualization package is not installed.
103
        VisualizationError: When invalid plotter API is specified.
104

105
    .. _style-dict-doc:
106

107
    **Style Dict Details**
108

109
    The stylesheet kwarg contains numerous options that define the style of the
110
    output timeline visualization.
111
    The stylesheet options can be classified into `formatter`, `generator` and `layout`.
112
    Those options available in the stylesheet are defined below:
113

114
    Args:
115
        formatter.general.fig_width: Width of output image (default `14`).
116
        formatter.general.fig_unit_height: Height of output image per timeline.
117
            The sum of all timeline becomes the height of the output image (default `0.8`).
118
        formatter.general.dpi: Dot per inch of image if `filename` is set (default `150`).
119
        formatter.margin.top: Margin from the top boundary of the figure canvas to
120
            the zero line of the first time slot (default `0.5`).
121
        formatter.margin.bottom: Margin from the bottom boundary of the figure canvas to
122
            the zero lien of the last time slot (default `0.5`).
123
        formatter.margin.left_percent:  Margin from the left boundary of the figure canvas to
124
            the left limit of the horizontal axis. The value is in units of percentage of
125
            the whole program duration. If the duration is 100 and the value of 0.5 is set,
126
            this keeps left margin of 5 (default `0.02`).
127
        formatter.margin.right_percent: Margin from the right boundary of the figure canvas to
128
            the right limit of the horizontal axis. The value is in units of percentage of
129
            the whole program duration. If the duration is 100 and the value of 0.5 is set,
130
            this keeps right margin of 5 (default `0.02`).
131
        formatter.margin.link_interval_percent: Allowed overlap of gate links.
132
            If multiple gate links are drawing within this range, links are horizontally
133
            shifted not to overlap with each other. The value is in units of percentage of
134
            the whole program duration (default `0.01`).
135
        formatter.time_bucket.edge_dt: The length of round edge of gate boxes. Gate boxes are
136
            smoothly faded in and out from the zero line. This value is in units of
137
            the system cycle time dt (default `10`).
138
        formatter.margin.minimum_duration: Minimum scheduled circuit duration.
139
            If the duration of input circuit is below this value, horizontal limit is
140
            set based on this value. This value is in units of
141
            the system cycle time dt (default `50`).
142
        formatter.color.background: Color code of the face color of canvas (default `#FFFFFF`).
143
        formatter.color.timeslot: Face color of the time slot box (default `#DDDDDD`).
144
        formatter.color.gate_name: Text color of the gate name annotations (default `#000000`).
145
        formatter.color.bit_name: Text color of the bit label annotations (default `#000000`).
146
        formatter.color.barrier: Line color of barriers (default `#222222`).
147
        formatter.color.gates: A dictionary of the gate box or gate symbol colors
148
            to use for each element type in the output visualization. The default
149
            values are::
150

151
                {
152
                    'u0': '#FA74A6',
153
                    'u1': '#000000',
154
                    'u2': '#FA74A6',
155
                    'u3': '#FA74A6',
156
                    'id': '#05BAB6',
157
                    'sx': '#FA74A6',
158
                    'sxdg': '#FA74A6',
159
                    'x': '#05BAB6',
160
                    'y': '#05BAB6',
161
                    'z': '#05BAB6',
162
                    'h': '#6FA4FF',
163
                    'cx': '#6FA4FF',
164
                    'cy': '#6FA4FF',
165
                    'cz': '#6FA4FF',
166
                    'swap': '#6FA4FF',
167
                    's': '#6FA4FF',
168
                    'sdg': '#6FA4FF',
169
                    'dcx': '#6FA4FF',
170
                    'iswap': '#6FA4FF',
171
                    't': '#BB8BFF',
172
                    'tdg': '#BB8BFF',
173
                    'r': '#BB8BFF',
174
                    'rx': '#BB8BFF',
175
                    'ry': '#BB8BFF',
176
                    'rz': '#000000',
177
                    'reset': '#808080',
178
                    'measure': '#808080'
179
                }
180

181
            You must specify all the necessary values if using this. If a gate name is not
182
            specified, the color in `formatter.color.default_gate` is applied.
183
        formatter.color.default_gate: Default gate color. This color is applied when
184
            a gate name to visualize is not contained in the dictionary of
185
            `formatter.color.gates` (default `#BB8BFF`).
186
        formatter.latex_symbol.gates: A dictionary of latex representation of gate names
187
            to use for each element type in the output visualization. The default
188
            values are::
189

190
                {
191
                    'u0': r'{\rm U}_0',
192
                    'u1': r'{\rm U}_1',
193
                    'u2': r'{\rm U}_2',
194
                    'u3': r'{\rm U}_3',
195
                    'id': r'{\rm Id}',
196
                    'x': r'{\rm X}',
197
                    'y': r'{\rm Y}',
198
                    'z': r'{\rm Z}',
199
                    'h': r'{\rm H}',
200
                    'cx': r'{\rm CX}',
201
                    'cy': r'{\rm CY}',
202
                    'cz': r'{\rm CZ}',
203
                    'swap': r'{\rm SWAP}',
204
                    's': r'{\rm S}',
205
                    'sdg': r'{\rm S}^\dagger',
206
                    'sx': r'{\rm √X}',
207
                    'sxdg': r'{\rm √X}^\dagger',
208
                    'dcx': r'{\rm DCX}',
209
                    'iswap': r'{\rm iSWAP}',
210
                    't': r'{\rm T}',
211
                    'tdg': r'{\rm T}^\dagger',
212
                    'r': r'{\rm R}',
213
                    'rx': r'{\rm R}_x',
214
                    'ry': r'{\rm R}_y',
215
                    'rz': r'{\rm R}_z',
216
                    'reset': r'|0\rangle',
217
                    'measure': r'{\rm Measure}'
218
                }
219

220
            You must specify all the necessary values if using this. There is
221
            no provision for passing an incomplete dict in.
222
        formatter.latex_symbol.frame_change: Latex representation of
223
            the frame change symbol (default r`\circlearrowleft`).
224
        formatter.unicode_symbol.frame_change: Unicode representation of
225
            the frame change symbol (default u'\u21BA').
226
        formatter.box_height.gate: Height of gate box (default `0.5`).
227
        formatter.box_height.timeslot: Height of time slot (default `0.6`).
228
        formatter.layer.gate: Layer index of gate boxes. Larger number comes
229
            in the front of the output image (default `3`).
230
        formatter.layer.timeslot: Layer index of time slots. Larger number comes
231
            in the front of the output image (default `0`).
232
        formatter.layer.gate_name: Layer index of gate name annotations. Larger number comes
233
            in the front of the output image (default `5`).
234
        formatter.layer.bit_name: Layer index of bit labels. Larger number comes
235
            in the front of the output image (default `5`).
236
        formatter.layer.frame_change: Layer index of frame change symbols. Larger number comes
237
            in the front of the output image (default `4`).
238
        formatter.layer.barrier: Layer index of barrier lines. Larger number comes
239
            in the front of the output image (default `1`).
240
        formatter.layer.gate_link: Layer index of gate link lines. Larger number comes
241
            in the front of the output image (default `2`).
242
        formatter.alpha.gate: Transparency of gate boxes. A value in the range from
243
            `0` to `1`. The value `0` gives completely transparent boxes (default `1.0`).
244
        formatter.alpha.timeslot: Transparency of time slots. A value in the range from
245
            `0` to `1`. The value `0` gives completely transparent boxes (default `0.7`).
246
        formatter.alpha.barrier: Transparency of barrier lines. A value in the range from
247
            `0` to `1`. The value `0` gives completely transparent lines (default `0.5`).
248
        formatter.alpha.gate_link: Transparency of gate link lines. A value in the range from
249
            `0` to `1`. The value `0` gives completely transparent lines (default `0.8`).
250
        formatter.line_width.gate: Line width of the fringe of gate boxes (default `0`).
251
        formatter.line_width.timeslot: Line width of the fringe of time slots (default `0`).
252
        formatter.line_width.barrier: Line width of barrier lines (default `3`).
253
        formatter.line_width.gate_link: Line width of gate links (default `3`).
254
        formatter.line_style.barrier: Line style of barrier lines. This
255
            conforms to the line style spec of matplotlib (default `'-'`).
256
        formatter.line_style.gate_link: Line style of gate link lines. This
257
            conforms to the line style spec of matplotlib (default `'-'`).
258
        formatter.text_size.gate_name: Text size of gate name annotations (default `12`).
259
        formatter.text_size.bit_name: Text size of bit labels (default `15`).
260
        formatter.text_size.frame_change: Text size of frame change symbols (default `18`).
261
        formatter.text_size.axis_label: Text size of axis labels (default `13`).
262
        formatter.label_offset.frame_change: Offset of zero duration gate name annotations
263
            from the zero line of time slot (default `0.25`).
264
        formatter.control.show_idle: Set `True` to show time slots without gate (default `True`).
265
        formatter.control.show_clbits: Set `True` to show time slots of
266
            classical bits (default `True`).
267
        formatter.control.show_barriers: Set `True` to show barriers (default `True`).
268
        formatter.control.show_delays: Set `True` to show delay boxes (default `True`).
269
        generator.gates: List of callback functions that generates drawings
270
            for gates. Arbitrary callback functions satisfying the generator format
271
            can be set here. There are some default generators in the timeline drawer. See
272
            :py:mod:`~qiskit.visualization.timeline.generators` for more details.
273
            No default generator is set (default `[]`).
274
        generator.bits: List of callback functions that generates drawings for bit labels
275
            and time slots. Arbitrary callback functions satisfying the generator format
276
            can be set here. There are some default generators in the timeline drawer. See
277
            :py:mod:`~qiskit.visualization.timeline.generators` for more details.
278
            No default generator is set (default `[]`).
279
        generator.barriers: List of callback functions that generates drawings
280
            for barriers. Arbitrary callback functions satisfying the generator format
281
            can be set here. There are some default generators in the timeline drawer. See
282
            :py:mod:`~qiskit.visualization.timeline.generators` for more details.
283
            No default generator is set (default `[]`).
284
        generator.gate_links: List of callback functions that generates drawings
285
            for gate links. Arbitrary callback functions satisfying the generator format
286
            can be set here. There are some default generators in the timeline drawer. See
287
            :py:mod:`~qiskit.visualization.timeline.generators` for more details.
288
            No default generator is set (default `[]`).
289
        layout.bit_arrange: Callback function that sorts bits. See
290
            :py:mod:`~qiskit.visualization.timeline.layouts` for more details.
291
            No default layout is set. (default `None`).
292
        layout.time_axis_map: Callback function that determines the layout of
293
            horizontal axis labels. See :py:mod:`~qiskit.visualization.timeline.layouts`
294
            for more details. No default layout is set. (default `None`).
295

296
    Examples:
297
        To visualize a scheduled circuit program, you can call this function with a set of
298
        control arguments. Most of the appearance of the output image can be controlled by the
299
        stylesheet.
300

301
        Drawing with the default stylesheet.
302

303
        .. plot::
304
           :alt: Output from the previous code.
305
           :include-source:
306

307
            from qiskit import QuantumCircuit, transpile
308
            from qiskit.visualization.timeline import draw
309
            from qiskit.providers.fake_provider import GenericBackendV2
310

311
            qc = QuantumCircuit(2)
312
            qc.h(0)
313
            qc.cx(0,1)
314

315
            backend = GenericBackendV2(5)
316

317
            qc = transpile(qc, backend, scheduling_method='alap', layout_method='trivial')
318
            draw(qc, target=backend.target)
319

320
        Drawing with the simple stylesheet.
321

322
        .. plot::
323
           :alt: Output from the previous code.
324
           :include-source:
325

326
            from qiskit import QuantumCircuit, transpile
327
            from qiskit.visualization.timeline import draw, IQXSimple
328
            from qiskit.providers.fake_provider import GenericBackendV2
329

330
            qc = QuantumCircuit(2)
331
            qc.h(0)
332
            qc.cx(0,1)
333

334
            backend = GenericBackendV2(5)
335

336
            qc = transpile(qc, backend, scheduling_method='alap', layout_method='trivial')
337
            draw(qc, style=IQXSimple(), target=backend.target)
338

339
        Drawing with the stylesheet suited for program debugging.
340

341
        .. plot::
342
           :alt: Output from the previous code.
343
           :include-source:
344

345
            from qiskit import QuantumCircuit, transpile
346
            from qiskit.visualization.timeline import draw, IQXDebugging
347
            from qiskit.providers.fake_provider import GenericBackendV2
348

349
            qc = QuantumCircuit(2)
350
            qc.h(0)
351
            qc.cx(0,1)
352

353
            backend = GenericBackendV2(5)
354
            qc = transpile(qc, backend, scheduling_method='alap', layout_method='trivial')
355
            draw(qc, style=IQXDebugging(), target=backend.target)
356

357
        You can partially customize a preset stylesheet when call it::
358

359
            my_style = {
360
                'formatter.general.fig_width': 16,
361
                'formatter.general.fig_unit_height': 1
362
            }
363
            style = IQXStandard(**my_style)
364

365
            # draw
366
            draw(qc, style=style)
367

368
        In the same way as above, you can create custom generator or layout functions
369
        and update existing stylesheet with custom functions.
370
        This feature enables you to control the most of the appearance of the output image
371
        without modifying the codebase of the scheduled circuit drawer.
372
    """
373
    del show_idle
×
374
    del show_barriers
×
375
    # update stylesheet
376
    temp_style = stylesheet.QiskitTimelineStyle()
×
377
    temp_style.update(style or stylesheet.IQXStandard())
×
378

379
    if target is None:
×
NEW
380
        raise VisualizationError(
×
381
            "No target is specified, this is required to get the duration of instructions."
382
        )
383

384
    # update control properties
385
    if idle_wires is not None:
×
386
        temp_style["formatter.control.show_idle"] = idle_wires
×
387

388
    if show_clbits is not None:
×
389
        temp_style["formatter.control.show_clbits"] = show_clbits
×
390

391
    if plot_barriers is not None:
×
392
        temp_style["formatter.control.show_barriers"] = plot_barriers
×
393

394
    if show_delays is not None:
×
395
        temp_style["formatter.control.show_delays"] = show_delays
×
396

397
    # create empty canvas and load program
398
    canvas = core.DrawerCanvas(stylesheet=temp_style)
×
NEW
399
    canvas.load_program(program=program, target=target)
×
400

401
    #
402
    # update configuration
403
    #
404

405
    # time range
406
    if time_range:
×
407
        canvas.set_time_range(*time_range)
×
408

409
    # bits not shown
410
    if disable_bits:
×
411
        for bit in disable_bits:
×
412
            canvas.set_disable_bits(bit, remove=True)
×
413

414
    # show labels
415
    if not show_labels:
×
416
        labels = [types.LabelType.DELAY, types.LabelType.GATE_PARAM, types.LabelType.GATE_NAME]
×
417
        for label in labels:
×
418
            canvas.set_disable_type(label, remove=True)
×
419

420
    canvas.update()
×
421

422
    #
423
    # Call plotter API and generate image
424
    #
425

426
    if plotter == types.Plotter.MPL.value:
×
427
        try:
×
428
            from qiskit.visualization.timeline.plotters import MplPlotter
×
429
        except ImportError as ex:
×
430
            raise MissingOptionalLibraryError(
×
431
                libname="Matplotlib",
432
                name="timeline drawer",
433
                pip_install="pip install matplotlib",
434
            ) from ex
435
        plotter_api = MplPlotter(canvas=canvas, axis=axis)
×
436
        plotter_api.draw()
×
437
    else:
438
        raise VisualizationError(f"Plotter API {plotter} is not supported.")
×
439

440
    # save figure
441
    if filename:
×
442
        plotter_api.save_file(filename=filename)
×
443

444
    return plotter_api.get_image()
×
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc