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

Qiskit / qiskit / 13498664887

24 Feb 2025 01:02PM UTC coverage: 88.13% (-0.1%) from 88.253%
13498664887

Pull #13863

github

web-flow
Merge 5892e8d6c into e4048320d
Pull Request #13863: The unused parameter dag in DAGNode constructor is removed

78403 of 88963 relevant lines covered (88.13%)

349134.48 hits per line

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

22.92
/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
import warnings
1✔
24

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

32

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

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

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

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

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

95
    Returns:
96
        Visualization output data.
97

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

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

106
    .. _style-dict-doc:
107

108
    **Style Dict Details**
109

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

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

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

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

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

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

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

302
        Drawing with the default stylesheet.
303

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

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

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

316
            qc = transpile(qc, GenericBackendV2(5), scheduling_method='alap', layout_method='trivial')
317
            draw(qc)
318

319
        Drawing with the simple stylesheet.
320

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

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

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

333
            qc = transpile(qc, GenericBackendV2(5), scheduling_method='alap', layout_method='trivial')
334
            draw(qc, style=IQXSimple())
335

336
        Drawing with the stylesheet suited for program debugging.
337

338
        .. plot::
339
           :alt: Output from the previous code.
340
           :include-source:
341

342
            from qiskit import QuantumCircuit, transpile
343
            from qiskit.visualization.timeline import draw, IQXDebugging
344
            from qiskit.providers.fake_provider import GenericBackendV2
345

346
            qc = QuantumCircuit(2)
347
            qc.h(0)
348
            qc.cx(0,1)
349

350
            qc = transpile(qc, GenericBackendV2(5), scheduling_method='alap', layout_method='trivial')
351
            draw(qc, style=IQXDebugging())
352

353
        You can partially customize a preset stylesheet when call it::
354

355
            my_style = {
356
                'formatter.general.fig_width': 16,
357
                'formatter.general.fig_unit_height': 1
358
            }
359
            style = IQXStandard(**my_style)
360

361
            # draw
362
            draw(qc, style=style)
363

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

375
    if target is None:
×
376
        warnings.warn(
×
377
            "Target is not specified. In Qiskit 2.0.0 this will be required to get the duration of "
378
            "instructions.",
379
            PendingDeprecationWarning,
380
            stacklevel=2,
381
        )
382

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

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

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

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

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

400
    #
401
    # update configuration
402
    #
403

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

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

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

419
    canvas.update()
×
420

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

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

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

443
    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