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

Qiskit / qiskit / 23295070105

19 Mar 2026 12:06PM UTC coverage: 87.238% (-0.005%) from 87.243%
23295070105

push

github

web-flow
Add barrier_label_len option to circuit drawers (#15776)

* Add barrier_label_len option to circuit drawers

* Switch to default value of 16

* consistency

* add comment

* move barrier_label_len to end

* add mpl test

* add ref fig

* Fix comment on LaTeX spaces

---------

Co-authored-by: Jake Lishman <jake@binhbar.com>

10 of 13 new or added lines in 4 files covered. (76.92%)

14 existing lines in 5 files now uncovered.

102004 of 116926 relevant lines covered (87.24%)

1152851.86 hits per line

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

47.92
/qiskit/visualization/circuit/matplotlib.py
1
# This code is part of Qiskit.
2
#
3
# (C) Copyright IBM 2017, 2018.
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 https://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

14
"""mpl circuit visualization backend."""
15

16
import collections
1✔
17
import itertools
1✔
18
import re
1✔
19
from io import StringIO
1✔
20

21
import numpy as np
1✔
22

23
from qiskit.circuit import (
1✔
24
    QuantumCircuit,
25
    Qubit,
26
    Clbit,
27
    ClassicalRegister,
28
    ControlledGate,
29
    Measure,
30
    ControlFlowOp,
31
    BoxOp,
32
    WhileLoopOp,
33
    IfElseOp,
34
    ForLoopOp,
35
    SwitchCaseOp,
36
    CircuitError,
37
)
38
from qiskit.circuit.controlflow import condition_resources
1✔
39
from qiskit.circuit.classical import expr
1✔
40
from qiskit.circuit.annotated_operation import _canonicalize_modifiers, ControlModifier
1✔
41
from qiskit.circuit.library import Initialize
1✔
42
from qiskit.circuit.library.standard_gates import (
1✔
43
    SwapGate,
44
    RZZGate,
45
    U1Gate,
46
    PhaseGate,
47
    XGate,
48
    ZGate,
49
)
50
from qiskit.qasm3 import ast
1✔
51
from qiskit.qasm3.exporter import _ExprBuilder
1✔
52
from qiskit.qasm3.printer import BasicPrinter
1✔
53

54
from qiskit.circuit.tools.pi_check import pi_check
1✔
55
from qiskit.utils import optionals as _optionals
1✔
56

57
from qiskit.visualization.style import load_style
1✔
58
from qiskit.visualization.circuit.qcstyle import MPLDefaultStyle, MPLStyleDict
1✔
59
from ._utils import (
1✔
60
    get_gate_ctrl_text,
61
    get_param_str,
62
    get_wire_map,
63
    get_bit_register,
64
    get_bit_reg_index,
65
    get_wire_label,
66
    get_condition_label_val,
67
    _get_layered_instructions,
68
)
69
from ..utils import matplotlib_close_if_inline
1✔
70

71
# Default gate width and height
72
WID = 0.65
1✔
73
HIG = 0.65
1✔
74

75
# Z dimension order for different drawing types
76
PORDER_REGLINE = 1
1✔
77
PORDER_FLOW = 3
1✔
78
PORDER_MASK = 4
1✔
79
PORDER_LINE = 6
1✔
80
PORDER_LINE_PLUS = 7
1✔
81
PORDER_BARRIER = 8
1✔
82
PORDER_GATE = 10
1✔
83
PORDER_GATE_PLUS = 11
1✔
84
PORDER_TEXT = 13
1✔
85

86
INFINITE_FOLD = 10000000
1✔
87

88

89
@_optionals.HAS_MATPLOTLIB.require_in_instance
1✔
90
@_optionals.HAS_PYLATEX.require_in_instance
1✔
91
class MatplotlibDrawer:
1✔
92
    """Matplotlib drawer class called from circuit_drawer"""
93

94
    _mathmode_regex = re.compile(r"(?<!\\)\$(.*)(?<!\\)\$")
1✔
95

96
    def __init__(
1✔
97
        self,
98
        qubits,
99
        clbits,
100
        nodes,
101
        circuit,
102
        scale=None,
103
        style=None,
104
        reverse_bits=False,
105
        plot_barriers=True,
106
        fold=25,
107
        ax=None,
108
        initial_state=False,
109
        cregbundle=None,
110
        with_layout=False,
111
        expr_len=30,
112
        measure_arrows=None,
113
        barrier_label_len=16,
114
    ):
115
        self._circuit = circuit
1✔
116
        self._qubits = qubits
1✔
117
        self._clbits = clbits
1✔
118
        self._nodes = nodes
1✔
119
        self._scale = 1.0 if scale is None else scale
1✔
120

121
        self._style = style
1✔
122

123
        self._plot_barriers = plot_barriers
1✔
124
        self._reverse_bits = reverse_bits
1✔
125
        if with_layout:
1✔
126
            if self._circuit._layout:
1✔
127
                self._layout = self._circuit._layout.initial_layout
×
128
            else:
129
                self._layout = None
1✔
130
        else:
131
            self._layout = None
×
132

133
        self._fold = fold
1✔
134
        if self._fold < 2:
1✔
135
            self._fold = -1
×
136

137
        self._ax = ax
1✔
138

139
        self._initial_state = initial_state
1✔
140
        self._global_phase = self._circuit.global_phase
1✔
141
        self._expr_len = expr_len
1✔
142
        self._barrier_label_len = barrier_label_len
1✔
143
        self._cregbundle = cregbundle
1✔
144
        self._measure_arrows = measure_arrows
1✔
145

146
        self._lwidth1 = 1.0
1✔
147
        self._lwidth15 = 1.5
1✔
148
        self._lwidth2 = 2.0
1✔
149
        self._lwidth3 = 3.0
1✔
150
        self._lwidth4 = 4.0
1✔
151

152
        # Class instances of MatplotlibDrawer for each flow gate - If/Else, For, While, Switch
153
        self._flow_drawers = {}
1✔
154

155
        # Set if gate is inside a flow gate
156
        self._flow_parent = None
1✔
157
        self._flow_wire_map = {}
1✔
158

159
        # _char_list for finding text_width of names, labels, and params
160
        self._char_list = {
1✔
161
            " ": (0.0958, 0.0583),
162
            "!": (0.1208, 0.0729),
163
            '"': (0.1396, 0.0875),
164
            "#": (0.2521, 0.1562),
165
            "$": (0.1917, 0.1167),
166
            "%": (0.2854, 0.1771),
167
            "&": (0.2333, 0.1458),
168
            "'": (0.0833, 0.0521),
169
            "(": (0.1167, 0.0729),
170
            ")": (0.1167, 0.0729),
171
            "*": (0.15, 0.0938),
172
            "+": (0.25, 0.1562),
173
            ",": (0.0958, 0.0583),
174
            "-": (0.1083, 0.0667),
175
            ".": (0.0958, 0.0604),
176
            "/": (0.1021, 0.0625),
177
            "0": (0.1875, 0.1167),
178
            "1": (0.1896, 0.1167),
179
            "2": (0.1917, 0.1188),
180
            "3": (0.1917, 0.1167),
181
            "4": (0.1917, 0.1188),
182
            "5": (0.1917, 0.1167),
183
            "6": (0.1896, 0.1167),
184
            "7": (0.1917, 0.1188),
185
            "8": (0.1896, 0.1188),
186
            "9": (0.1917, 0.1188),
187
            ":": (0.1021, 0.0604),
188
            ";": (0.1021, 0.0604),
189
            "<": (0.25, 0.1542),
190
            "=": (0.25, 0.1562),
191
            ">": (0.25, 0.1542),
192
            "?": (0.1583, 0.0979),
193
            "@": (0.2979, 0.1854),
194
            "A": (0.2062, 0.1271),
195
            "B": (0.2042, 0.1271),
196
            "C": (0.2083, 0.1292),
197
            "D": (0.2312, 0.1417),
198
            "E": (0.1875, 0.1167),
199
            "F": (0.1708, 0.1062),
200
            "G": (0.2312, 0.1438),
201
            "H": (0.225, 0.1396),
202
            "I": (0.0875, 0.0542),
203
            "J": (0.0875, 0.0542),
204
            "K": (0.1958, 0.1208),
205
            "L": (0.1667, 0.1042),
206
            "M": (0.2583, 0.1604),
207
            "N": (0.225, 0.1396),
208
            "O": (0.2354, 0.1458),
209
            "P": (0.1812, 0.1125),
210
            "Q": (0.2354, 0.1458),
211
            "R": (0.2083, 0.1292),
212
            "S": (0.1896, 0.1188),
213
            "T": (0.1854, 0.1125),
214
            "U": (0.2208, 0.1354),
215
            "V": (0.2062, 0.1271),
216
            "W": (0.2958, 0.1833),
217
            "X": (0.2062, 0.1271),
218
            "Y": (0.1833, 0.1125),
219
            "Z": (0.2042, 0.1271),
220
            "[": (0.1167, 0.075),
221
            "\\": (0.1021, 0.0625),
222
            "]": (0.1167, 0.0729),
223
            "^": (0.2521, 0.1562),
224
            "_": (0.1521, 0.0938),
225
            "`": (0.15, 0.0938),
226
            "a": (0.1854, 0.1146),
227
            "b": (0.1917, 0.1167),
228
            "c": (0.1646, 0.1021),
229
            "d": (0.1896, 0.1188),
230
            "e": (0.1854, 0.1146),
231
            "f": (0.1042, 0.0667),
232
            "g": (0.1896, 0.1188),
233
            "h": (0.1896, 0.1188),
234
            "i": (0.0854, 0.0521),
235
            "j": (0.0854, 0.0521),
236
            "k": (0.1729, 0.1083),
237
            "l": (0.0854, 0.0521),
238
            "m": (0.2917, 0.1812),
239
            "n": (0.1896, 0.1188),
240
            "o": (0.1833, 0.1125),
241
            "p": (0.1917, 0.1167),
242
            "q": (0.1896, 0.1188),
243
            "r": (0.125, 0.0771),
244
            "s": (0.1562, 0.0958),
245
            "t": (0.1167, 0.0729),
246
            "u": (0.1896, 0.1188),
247
            "v": (0.1771, 0.1104),
248
            "w": (0.2458, 0.1521),
249
            "x": (0.1771, 0.1104),
250
            "y": (0.1771, 0.1104),
251
            "z": (0.1562, 0.0979),
252
            "{": (0.1917, 0.1188),
253
            "|": (0.1, 0.0604),
254
            "}": (0.1896, 0.1188),
255
        }
256

257
    def draw(self, filename=None):
1✔
258
        """Main entry point to 'matplotlib' ('mpl') drawer. Called from
259
        ``visualization.circuit_drawer`` and from ``QuantumCircuit.draw`` through circuit_drawer.
260
        """
261

262
        # Import matplotlib and load all the figure, window, and style info
263
        from matplotlib import patches
1✔
264
        from matplotlib import pyplot as plt
1✔
265

266
        # glob_data contains global values used throughout, "n_lines", "x_offset", "next_x_index",
267
        # "patches_mod", "subfont_factor"
268
        glob_data = {}
1✔
269

270
        glob_data["patches_mod"] = patches
1✔
271
        plt_mod = plt
1✔
272

273
        self._style, def_font_ratio = load_style(
1✔
274
            self._style,
275
            style_dict=MPLStyleDict,
276
            default_style=MPLDefaultStyle(),
277
            user_config_opt="circuit_mpl_style",
278
            user_config_path_opt="circuit_mpl_style_path",
279
        )
280

281
        # If font/subfont ratio changes from default, have to scale width calculations for
282
        # subfont. Font change is auto scaled in the mpl_figure.set_size_inches call in draw()
283
        glob_data["subfont_factor"] = self._style["sfs"] * def_font_ratio / self._style["fs"]
1✔
284

285
        # if no user ax, setup default figure. Else use the user figure.
286
        if self._ax is None:
1✔
287
            is_user_ax = False
1✔
288
            mpl_figure = plt.figure()
1✔
289
            mpl_figure.patch.set_facecolor(color=self._style["bg"])
1✔
290
            self._ax = mpl_figure.add_subplot(111)
1✔
291
        else:
292
            is_user_ax = True
×
293
            mpl_figure = self._ax.get_figure()
×
294
        self._ax.axis("off")
1✔
295
        self._ax.set_aspect("equal")
1✔
296
        self._ax.tick_params(labelbottom=False, labeltop=False, labelleft=False, labelright=False)
1✔
297

298
        # All information for the drawing is first loaded into node_data for the gates and into
299
        # qubits_dict, clbits_dict, and wire_map for the qubits, clbits, and wires,
300
        # followed by the coordinates for each gate.
301

302
        # load the wire map
303
        wire_map = get_wire_map(self._circuit, self._qubits + self._clbits, self._cregbundle)
1✔
304

305
        # node_data per node filled with class NodeData attributes
306
        node_data = {}
1✔
307

308
        # dicts for the names and locations of register/bit labels
309
        qubits_dict = {}
1✔
310
        clbits_dict = {}
1✔
311

312
        # load the _qubit_dict and _clbit_dict with register info
313
        self._set_bit_reg_info(wire_map, qubits_dict, clbits_dict, glob_data)
1✔
314

315
        # get layer widths - flow gates are initialized here
316
        layer_widths = self._get_layer_widths(node_data, wire_map, self._circuit, glob_data)
1✔
317

318
        # load the coordinates for each top level gate and compute number of folds.
319
        # coordinates for flow gates are loaded before draw_ops
320
        max_x_index = self._get_coords(
1✔
321
            node_data, wire_map, self._circuit, layer_widths, qubits_dict, clbits_dict, glob_data
322
        )
323
        num_folds = max(0, max_x_index - 1) // self._fold if self._fold > 0 else 0
1✔
324

325
        # The window size limits are computed, followed by one of the four possible ways
326
        # of scaling the drawing.
327

328
        # compute the window size
329
        if max_x_index > self._fold > 0:
1✔
330
            xmax = self._fold + glob_data["x_offset"] + 0.1
×
331
            ymax = (num_folds + 1) * (glob_data["n_lines"] + 1) - 1
×
332
        else:
333
            x_incr = 0.4 if not self._nodes else 0.9
1✔
334
            xmax = max_x_index + 1 + glob_data["x_offset"] - x_incr
1✔
335
            ymax = glob_data["n_lines"]
1✔
336

337
        xl = -self._style["margin"][0]
1✔
338
        xr = xmax + self._style["margin"][1]
1✔
339
        yb = -ymax - self._style["margin"][2] + 0.5
1✔
340
        yt = self._style["margin"][3] + 0.5
1✔
341
        self._ax.set_xlim(xl, xr)
1✔
342
        self._ax.set_ylim(yb, yt)
1✔
343

344
        # update figure size and, for backward compatibility,
345
        # need to scale by a default value equal to (self._style["fs"] * 3.01 / 72 / 0.65)
346
        base_fig_w = (xr - xl) * 0.8361111
1✔
347
        base_fig_h = (yt - yb) * 0.8361111
1✔
348
        scale = self._scale
1✔
349

350
        # if user passes in an ax, this size takes priority over any other settings
351
        if is_user_ax:
1✔
352
            # from stackoverflow #19306510, get the bbox size for the ax and then reset scale
353
            bbox = self._ax.get_window_extent().transformed(mpl_figure.dpi_scale_trans.inverted())
×
354
            scale = bbox.width / base_fig_w / 0.8361111
×
355

356
        # if scale not 1.0, use this scale factor
357
        elif self._scale != 1.0:
1✔
358
            mpl_figure.set_size_inches(base_fig_w * self._scale, base_fig_h * self._scale)
×
359

360
        # if "figwidth" style param set, use this to scale
361
        elif self._style["figwidth"] > 0.0:
1✔
362
            # in order to get actual inches, need to scale by factor
363
            adj_fig_w = self._style["figwidth"] * 1.282736
×
364
            mpl_figure.set_size_inches(adj_fig_w, adj_fig_w * base_fig_h / base_fig_w)
×
365
            scale = adj_fig_w / base_fig_w
×
366

367
        # otherwise, display default size
368
        else:
369
            mpl_figure.set_size_inches(base_fig_w, base_fig_h)
1✔
370

371
        # drawing will scale with 'set_size_inches', but fonts and linewidths do not
372
        if scale != 1.0:
1✔
373
            self._style["fs"] *= scale
×
374
            self._style["sfs"] *= scale
×
375
            self._lwidth1 = 1.0 * scale
×
376
            self._lwidth15 = 1.5 * scale
×
377
            self._lwidth2 = 2.0 * scale
×
378
            self._lwidth3 = 3.0 * scale
×
379
            self._lwidth4 = 4.0 * scale
×
380

381
        # Once the scaling factor has been determined, the global phase, register names
382
        # and numbers, wires, and gates are drawn
383
        if self._global_phase:
1✔
384
            plt_mod.text(xl, yt, f"Global Phase: {pi_check(self._global_phase, output='mpl')}")
×
385
        self._draw_regs_wires(num_folds, xmax, max_x_index, qubits_dict, clbits_dict, glob_data)
1✔
386
        self._draw_ops(
1✔
387
            self._nodes,
388
            node_data,
389
            wire_map,
390
            self._circuit,
391
            layer_widths,
392
            qubits_dict,
393
            clbits_dict,
394
            glob_data,
395
        )
396
        if filename:
1✔
397
            mpl_figure.savefig(
×
398
                filename,
399
                dpi=self._style["dpi"],
400
                bbox_inches="tight",
401
                facecolor=mpl_figure.get_facecolor(),
402
            )
403
        if not is_user_ax:
1✔
404
            matplotlib_close_if_inline(mpl_figure)
1✔
405
            return mpl_figure
1✔
406

407
    def _get_layer_widths(self, node_data, wire_map, outer_circuit, glob_data):
1✔
408
        """Compute the layer_widths for the layers"""
409

410
        layer_widths = {}
1✔
411
        for layer_num, layer in enumerate(self._nodes):
1✔
412
            widest_box = WID
1✔
413
            for i, node in enumerate(layer):
1✔
414
                # Put the layer_num in the first node in the layer and put -1 in the rest
415
                # so that layer widths are not counted more than once
416
                if i != 0:
1✔
417
                    layer_num = -1
×
418
                layer_widths[node] = [1, layer_num, self._flow_parent]
1✔
419

420
                op = node.op
1✔
421
                node_data[node] = NodeData()
1✔
422
                node_data[node].width = WID
1✔
423
                num_ctrl_qubits = getattr(op, "num_ctrl_qubits", 0)
1✔
424
                if (
1✔
425
                    getattr(op, "_directive", False) and (not op.label or not self._plot_barriers)
426
                ) or (self._measure_arrows and isinstance(op, Measure)):
427
                    node_data[node].raw_gate_text = op.name
×
428
                    continue
×
429

430
                base_type = getattr(op, "base_gate", None)
1✔
431
                gate_text, ctrl_text, raw_gate_text = get_gate_ctrl_text(
1✔
432
                    op, "mpl", style=self._style
433
                )
434
                node_data[node].gate_text = gate_text
1✔
435
                node_data[node].ctrl_text = ctrl_text
1✔
436
                # Measure doesn't use raw_gate_text since it displays a dial
437
                if not isinstance(op, Measure):
1✔
438
                    node_data[node].raw_gate_text = raw_gate_text
1✔
439
                node_data[node].param_text = ""
1✔
440

441
                # if single qubit, no params, and no labels, layer_width is 1
442
                if (
1✔
443
                    (len(node.qargs) - num_ctrl_qubits) == 1
444
                    and len(gate_text) < 3
445
                    and len(getattr(op, "params", [])) == 0
446
                    and ctrl_text is None
447
                ):
448
                    continue
1✔
449

450
                if isinstance(op, SwapGate) or isinstance(base_type, SwapGate):
1✔
451
                    continue
×
452

453
                # small increments at end of the 3 _get_text_width calls are for small
454
                # spacing adjustments between gates
455
                ctrl_width = (
1✔
456
                    self._get_text_width(ctrl_text, glob_data, fontsize=self._style["sfs"]) - 0.05
457
                )
458
                # get param_width, but 0 for gates with array params or circuits in params
459
                if (
1✔
460
                    len(getattr(op, "params", [])) > 0
461
                    and not any(isinstance(param, np.ndarray) for param in op.params)
462
                    and not any(isinstance(param, QuantumCircuit) for param in op.params)
463
                ):
464
                    param_text = get_param_str(op, "mpl", ndigits=3)
×
465
                    if isinstance(op, Initialize):
×
466
                        param_text = f"$[{param_text.replace('$', '')}]$"
×
467
                    node_data[node].param_text = param_text
×
468
                    raw_param_width = self._get_text_width(
×
469
                        param_text, glob_data, fontsize=self._style["sfs"], param=True
470
                    )
471
                    param_width = raw_param_width + 0.08
×
472
                else:
473
                    param_width = raw_param_width = 0.0
1✔
474

475
                # get gate_width for sidetext symmetric gates
476
                if isinstance(op, RZZGate) or isinstance(base_type, (U1Gate, PhaseGate, RZZGate)):
1✔
477
                    if isinstance(base_type, PhaseGate):
×
478
                        gate_text = "P"
×
479
                    raw_gate_width = (
×
480
                        self._get_text_width(
481
                            gate_text + " ()", glob_data, fontsize=self._style["sfs"]
482
                        )
483
                        + raw_param_width
484
                    )
485
                    gate_width = (raw_gate_width + 0.08) * 1.58
×
486

487
                # Check if a ControlFlowOp - node_data load for these gates is done here
488
                elif isinstance(node.op, ControlFlowOp):
1✔
489
                    self._flow_drawers[node] = []
×
490
                    node_data[node].width = []
×
491
                    node_data[node].nest_depth = 0
×
492
                    gate_width = 0.0
×
493
                    expr_width = 0.0
×
494

495
                    if (isinstance(op, SwitchCaseOp) and isinstance(op.target, expr.Expr)) or (
×
496
                        getattr(op, "condition", None) and isinstance(op.condition, expr.Expr)
497
                    ):
498

499
                        def lookup_var(var):
×
500
                            """Look up a classical-expression variable or register/bit in our
501
                            internal symbol table, and return an OQ3-like identifier."""
502
                            # We don't attempt to disambiguate anything like register/var naming
503
                            # collisions; we already don't really show classical variables.
504
                            if isinstance(var, expr.Var):
×
505
                                return ast.Identifier(var.name)
×
506
                            if isinstance(var, ClassicalRegister):
×
507
                                return ast.Identifier(var.name)
×
508
                            # Single clbit.  This is not actually the correct way to lookup a bit on
509
                            # the circuit (it doesn't handle bit bindings fully), but the mpl
510
                            # drawer doesn't completely track inner-outer _bit_ bindings, only
511
                            # inner-indices, so we can't fully recover the information losslessly.
512
                            # Since most control-flow uses the control-flow builders, we should
513
                            # decay to something usable most of the time.
514
                            try:
×
515
                                register, bit_index, reg_index = get_bit_reg_index(
×
516
                                    outer_circuit, var
517
                                )
518
                            except CircuitError:
×
519
                                # We failed to find the bit due to binding problems - fall back to
520
                                # something that's probably wrong, but at least disambiguating.
521
                                return ast.Identifier(f"bit{wire_map[var]}")
×
522
                            if register is None:
×
523
                                return ast.Identifier(f"bit{bit_index}")
×
524
                            return ast.SubscriptedIdentifier(
×
525
                                register.name, ast.IntegerLiteral(reg_index)
526
                            )
527

528
                        condition = op.target if isinstance(op, SwitchCaseOp) else op.condition
×
529
                        stream = StringIO()
×
530
                        BasicPrinter(stream, indent="  ").visit(
×
531
                            condition.accept(_ExprBuilder(lookup_var))
532
                        )
533
                        expr_text = stream.getvalue()
×
534
                        # Truncate expr_text so that first gate is no more than about 3 x_index's over
535
                        if len(expr_text) > self._expr_len:
×
536
                            expr_text = expr_text[: self._expr_len] + "..."
×
537
                        node_data[node].expr_text = expr_text
×
538

539
                        expr_width = self._get_text_width(
×
540
                            node_data[node].expr_text, glob_data, fontsize=self._style["sfs"]
541
                        )
542
                        node_data[node].expr_width = int(expr_width)
×
543

544
                    # Get the list of circuits to iterate over from the blocks
545
                    circuit_list = list(node.op.blocks)
×
546

547
                    # params is [indexset, loop_param, circuit] for for_loop,
548
                    # op.cases_specifier() returns jump tuple and circuit for switch/case
549
                    if isinstance(op, ForLoopOp):
×
550
                        node_data[node].indexset = op.params[0]
×
551
                    elif isinstance(op, SwitchCaseOp):
×
552
                        node_data[node].jump_values = []
×
553
                        cases = list(op.cases_specifier())
×
554

555
                        # Create an empty circuit at the head of the circuit_list if a Switch box
556
                        circuit_list.insert(0, cases[0][1].copy_empty_like())
×
557
                        for jump_values, _ in cases:
×
558
                            node_data[node].jump_values.append(jump_values)
×
559

560
                    # Now process the circuits inside the ControlFlowOps
561
                    for circ_num, circuit in enumerate(circuit_list):
×
562
                        # Only add expr_width for if, while, and switch
563
                        raw_gate_width = expr_width if circ_num == 0 else 0.0
×
564

565
                        # Depth of nested ControlFlowOp used for color of box
566
                        if self._flow_parent is not None:
×
567
                            node_data[node].nest_depth = node_data[self._flow_parent].nest_depth + 1
×
568

569
                        # Build the wire_map to be used by this flow op
570
                        flow_wire_map = wire_map.copy()
×
571
                        flow_wire_map.update(
×
572
                            {
573
                                inner: wire_map[outer]
574
                                for outer, inner in zip(node.qargs, circuit.qubits)
575
                            }
576
                        )
577
                        for outer, inner in zip(node.cargs, circuit.clbits):
×
578
                            if self._cregbundle and (
×
579
                                (in_reg := get_bit_register(outer_circuit, inner)) is not None
580
                            ):
581
                                out_reg = get_bit_register(outer_circuit, outer)
×
582
                                flow_wire_map.update({in_reg: wire_map[out_reg]})
×
583
                            else:
584
                                flow_wire_map.update({inner: wire_map[outer]})
×
585

586
                        # Get the layered node lists and instantiate a new drawer class for
587
                        # the circuit inside the ControlFlowOp.
588
                        qubits, clbits, flow_nodes = _get_layered_instructions(
×
589
                            circuit, wire_map=flow_wire_map, measure_arrows=self._measure_arrows
590
                        )
591
                        flow_drawer = MatplotlibDrawer(
×
592
                            qubits,
593
                            clbits,
594
                            flow_nodes,
595
                            circuit,
596
                            style=self._style,
597
                            plot_barriers=self._plot_barriers,
598
                            fold=self._fold,
599
                            cregbundle=self._cregbundle,
600
                        )
601

602
                        # flow_parent is the parent of the new class instance
603
                        flow_drawer._flow_parent = node
×
604
                        flow_drawer._flow_wire_map = flow_wire_map
×
605
                        self._flow_drawers[node].append(flow_drawer)
×
606

607
                        # Recursively call _get_layer_widths for the circuit inside the ControlFlowOp
608
                        flow_widths = flow_drawer._get_layer_widths(
×
609
                            node_data, flow_wire_map, outer_circuit, glob_data
610
                        )
611
                        layer_widths.update(flow_widths)
×
612

613
                        for flow_layer in flow_nodes:
×
614
                            for flow_node in flow_layer:
×
615
                                node_data[flow_node].circ_num = circ_num
×
616

617
                        # Add up the width values of the same flow_parent that are not -1
618
                        # to get the raw_gate_width
619
                        for width, layer_num, flow_parent in flow_widths.values():
×
620
                            if layer_num != -1 and flow_parent == flow_drawer._flow_parent:
×
621
                                raw_gate_width += width
×
622
                                # This is necessary to prevent 1 being added to the width of a
623
                                # BoxOp in layer_widths at the end of this method
624
                                if isinstance(node.op, BoxOp):
×
625
                                    raw_gate_width -= 0.001
×
626

627
                        # Need extra incr of 1.0 for else and case boxes
628
                        gate_width += raw_gate_width + (1.0 if circ_num > 0 else 0.0)
×
629

630
                        # Minor adjustment so else and case section gates align with indexes
631
                        if circ_num > 0:
×
632
                            raw_gate_width += 0.045
×
633

634
                        # If expr_width has a value, remove the decimal portion from raw_gate_widthl
635
                        if not isinstance(op, ForLoopOp) and circ_num == 0:
×
636
                            node_data[node].width.append(raw_gate_width - (expr_width % 1))
×
637
                        else:
638
                            node_data[node].width.append(raw_gate_width)
×
639

640
                # If measure_arrows is False, this section gets the layer width for a measure
641
                # based on the width of register_bit and puts it into the param_width. If the
642
                # register_bit is small enough, the gate will just use the WID width.
643
                elif not self._measure_arrows and isinstance(op, Measure):
1✔
644
                    register, _, reg_index = get_bit_reg_index(outer_circuit, node.cargs[0])
×
645
                    if register is not None:
×
646
                        param_text = f"{register.name}_{reg_index}"
×
647
                    else:
648
                        param_text = f"{reg_index}"
×
649
                    raw_param_width = self._get_text_width(
×
650
                        param_text, glob_data, fontsize=self._style["sfs"], param=True
651
                    )
652
                    param_width = raw_param_width
×
653
                    raw_gate_width = gate_width = ctrl_width = 0.0
×
654

655
                # Otherwise, standard gate or multiqubit gate
656
                else:
657
                    raw_gate_width = self._get_text_width(
1✔
658
                        gate_text, glob_data, fontsize=self._style["fs"]
659
                    )
660
                    gate_width = raw_gate_width + 0.10
1✔
661
                    # add .21 for the qubit numbers on the left of the multibit gates
662
                    if len(node.qargs) - num_ctrl_qubits > 1:
1✔
663
                        gate_width += 0.21
×
664

665
                box_width = max(gate_width, ctrl_width, param_width, WID)
1✔
666
                widest_box = max(widest_box, box_width)
1✔
667
                if not isinstance(node.op, ControlFlowOp):
1✔
668
                    node_data[node].width = max(raw_gate_width, raw_param_width)
1✔
669
            for node in layer:
1✔
670
                layer_widths[node][0] = int(widest_box) + 1
1✔
671

672
        return layer_widths
1✔
673

674
    def _set_bit_reg_info(self, wire_map, qubits_dict, clbits_dict, glob_data):
1✔
675
        """Get all the info for drawing bit/reg names and numbers"""
676

677
        longest_wire_label_width = 0
1✔
678
        glob_data["n_lines"] = 0
1✔
679
        initial_qbit = r" $|0\rangle$" if self._initial_state else ""
1✔
680
        initial_cbit = " 0" if self._initial_state else ""
1✔
681

682
        idx = 0
1✔
683
        pos = y_off = -len(self._qubits) + 1
1✔
684
        for ii, wire in enumerate(wire_map):
1✔
685
            # if it's a creg, register is the key and just load the index
686
            if isinstance(wire, ClassicalRegister):
1✔
687
                # If wire came from ControlFlowOp and not in clbits, don't draw it
688
                if wire[0] not in self._clbits:
×
689
                    continue
×
690
                register = wire
×
691
                index = wire_map[wire]
×
692

693
            # otherwise, get the register from find_bit and use bit_index if
694
            # it's a bit, or the index of the bit in the register if it's a reg
695
            else:
696
                # If wire came from ControlFlowOp and not in qubits or clbits, don't draw it
697
                if wire not in self._qubits + self._clbits:
1✔
698
                    continue
×
699
                register, bit_index, reg_index = get_bit_reg_index(self._circuit, wire)
1✔
700
                index = bit_index if register is None else reg_index
1✔
701

702
            wire_label = get_wire_label(
1✔
703
                "mpl", register, index, layout=self._layout, cregbundle=self._cregbundle
704
            )
705
            initial_bit = initial_qbit if isinstance(wire, Qubit) else initial_cbit
1✔
706

707
            # for cregs with cregbundle on, don't use math formatting, which means
708
            # no italics
709
            if isinstance(wire, Qubit) or register is None or not self._cregbundle:
1✔
710
                wire_label = "$" + wire_label + "$"
1✔
711
            wire_label += initial_bit
1✔
712

713
            reg_size = (
1✔
714
                0 if register is None or isinstance(wire, ClassicalRegister) else register.size
715
            )
716
            reg_remove_under = 0 if reg_size < 2 else 1
1✔
717
            text_width = (
1✔
718
                self._get_text_width(
719
                    wire_label, glob_data, self._style["fs"], reg_remove_under=reg_remove_under
720
                )
721
                * 1.15
722
            )
723
            longest_wire_label_width = max(longest_wire_label_width, text_width)
1✔
724

725
            if isinstance(wire, Qubit):
1✔
726
                pos = -ii
1✔
727
                qubits_dict[ii] = {
1✔
728
                    "y": pos,
729
                    "wire_label": wire_label,
730
                }
731
                glob_data["n_lines"] += 1
1✔
732
            else:
733
                if (
1✔
734
                    not self._cregbundle
735
                    or register is None
736
                    or (self._cregbundle and isinstance(wire, ClassicalRegister))
737
                ):
738
                    glob_data["n_lines"] += 1
1✔
739
                    idx += 1
1✔
740

741
                pos = y_off - idx
1✔
742
                clbits_dict[ii] = {
1✔
743
                    "y": pos,
744
                    "wire_label": wire_label,
745
                    "register": register,
746
                }
747
        glob_data["x_offset"] = -1.2 + longest_wire_label_width
1✔
748

749
    def _get_coords(
1✔
750
        self,
751
        node_data,
752
        wire_map,
753
        outer_circuit,
754
        layer_widths,
755
        qubits_dict,
756
        clbits_dict,
757
        glob_data,
758
        flow_parent=None,
759
    ):
760
        """Load all the coordinate info needed to place the gates on the drawing."""
761

762
        prev_x_index = -1
1✔
763
        for layer in self._nodes:
1✔
764
            curr_x_index = prev_x_index + 1
1✔
765
            l_width = []
1✔
766
            for node in layer:
1✔
767
                # For gates inside a flow op set the x_index and if it's an else or case,
768
                # increment by if/switch width. If more cases increment by width of previous cases.
769
                if flow_parent is not None:
1✔
770
                    node_data[node].inside_flow = True
×
771
                    # front_space provides a space for 'If', 'While', etc. which is not
772
                    # necessary for a BoxOp
773
                    front_space = 0 if isinstance(flow_parent.op, BoxOp) else 1
×
774
                    node_data[node].x_index = (
×
775
                        node_data[flow_parent].x_index + curr_x_index + front_space
776
                    )
777

778
                    # If an else or case
779
                    if node_data[node].circ_num > 0:
×
780
                        for width in node_data[flow_parent].width[: node_data[node].circ_num]:
×
781
                            node_data[node].x_index += int(width) + 1
×
782
                        x_index = node_data[node].x_index
×
783
                    # Add expr_width to if, while, or switch if expr used
784
                    else:
785
                        x_index = node_data[node].x_index + node_data[flow_parent].expr_width
×
786
                else:
787
                    node_data[node].inside_flow = False
1✔
788
                    x_index = curr_x_index
1✔
789

790
                # get qubit indexes
791
                q_indxs = []
1✔
792
                for qarg in node.qargs:
1✔
793
                    if qarg in self._qubits:
1✔
794
                        q_indxs.append(wire_map[qarg])
1✔
795

796
                # get clbit indexes
797
                c_indxs = []
1✔
798
                for carg in node.cargs:
1✔
799
                    if carg in self._clbits:
1✔
800
                        if self._cregbundle:
1✔
801
                            register = get_bit_register(outer_circuit, carg)
×
802
                            if register is not None:
×
803
                                c_indxs.append(wire_map[register])
×
804
                            else:
805
                                c_indxs.append(wire_map[carg])
×
806
                        else:
807
                            c_indxs.append(wire_map[carg])
1✔
808

809
                flow_op = isinstance(node.op, ControlFlowOp)
1✔
810

811
                # qubit coordinates
812
                node_data[node].q_xy = [
1✔
813
                    self._plot_coord(
814
                        x_index,
815
                        qubits_dict[ii]["y"],
816
                        layer_widths[node][0],
817
                        glob_data,
818
                        flow_op,
819
                    )
820
                    for ii in q_indxs
821
                ]
822
                # clbit coordinates
823
                node_data[node].c_xy = [
1✔
824
                    self._plot_coord(
825
                        x_index,
826
                        clbits_dict[ii]["y"],
827
                        layer_widths[node][0],
828
                        glob_data,
829
                        flow_op,
830
                    )
831
                    for ii in c_indxs
832
                ]
833

834
                # update index based on the value from plotting
835
                if flow_parent is None:
1✔
836
                    curr_x_index = glob_data["next_x_index"]
1✔
837
                l_width.append(layer_widths[node][0])
1✔
838
                node_data[node].x_index = x_index
1✔
839

840
                # Special case of default case with no ops in it, need to push end
841
                # of switch op one extra x_index
842
                if isinstance(node.op, SwitchCaseOp):
1✔
843
                    if len(node.op.blocks[-1]) == 0:
×
844
                        curr_x_index += 1
×
845

846
            # adjust the column if there have been barriers encountered, but not plotted
847
            barrier_offset = 0
1✔
848
            if not self._plot_barriers:
1✔
849
                # only adjust if everything in the layer wasn't plotted
850
                barrier_offset = (
×
851
                    -1 if all(getattr(nd.op, "_directive", False) for nd in layer) else 0
852
                )
853
            max_lwidth = max(l_width) if l_width else 0
1✔
854
            prev_x_index = curr_x_index + max_lwidth + barrier_offset - 1
1✔
855

856
        return prev_x_index + 1
1✔
857

858
    def _get_text_width(self, text, glob_data, fontsize, param=False, reg_remove_under=None):
1✔
859
        """Compute the width of a string in the default font"""
860

861
        from pylatexenc.latex2text import LatexNodes2Text
1✔
862

863
        if not text:
1✔
864
            return 0.0
1✔
865

866
        math_mode_match = self._mathmode_regex.search(text)
1✔
867
        num_underscores = 0
1✔
868
        num_carets = 0
1✔
869
        if math_mode_match:
1✔
870
            math_mode_text = math_mode_match.group(1)
1✔
871
            num_underscores = math_mode_text.count("_")
1✔
872
            num_carets = math_mode_text.count("^")
1✔
873
        text = LatexNodes2Text().latex_to_text(text.replace("$$", ""))
1✔
874

875
        # If there are subscripts or superscripts in mathtext string
876
        # we need to account for that spacing by manually removing
877
        # from text string for text length
878

879
        # if it's a register and there's a subscript at the end,
880
        # remove 1 underscore, otherwise don't remove any
881
        if reg_remove_under is not None:
1✔
882
            num_underscores = reg_remove_under
1✔
883
        if num_underscores:
1✔
884
            text = text.replace("_", "", num_underscores)
1✔
885
        if num_carets:
1✔
886
            text = text.replace("^", "", num_carets)
×
887

888
        # This changes hyphen to + to match width of math mode minus sign.
889
        if param:
1✔
890
            text = text.replace("-", "+")
×
891

892
        f = 0 if fontsize == self._style["fs"] else 1
1✔
893
        sum_text = 0.0
1✔
894
        for c in text:
1✔
895
            try:
1✔
896
                sum_text += self._char_list[c][f]
1✔
897
            except KeyError:
×
898
                # if non-ASCII char, use width of 'c', an average size
899
                sum_text += self._char_list["c"][f]
×
900
        if f == 1:
1✔
901
            sum_text *= glob_data["subfont_factor"]
×
902
        return sum_text
1✔
903

904
    def _draw_regs_wires(self, num_folds, xmax, max_x_index, qubits_dict, clbits_dict, glob_data):
1✔
905
        """Draw the register names and numbers, wires, and vertical lines at the ends"""
906

907
        for fold_num in range(num_folds + 1):
1✔
908
            # quantum registers
909
            for qubit in qubits_dict.values():
1✔
910
                qubit_label = qubit["wire_label"]
1✔
911
                y = qubit["y"] - fold_num * (glob_data["n_lines"] + 1)
1✔
912
                self._ax.text(
1✔
913
                    glob_data["x_offset"] - 0.2,
914
                    y,
915
                    qubit_label,
916
                    ha="right",
917
                    va="center",
918
                    fontsize=1.25 * self._style["fs"],
919
                    color=self._style["tc"],
920
                    clip_on=True,
921
                    zorder=PORDER_TEXT,
922
                )
923
                # draw the qubit wire
924
                self._line([glob_data["x_offset"], y], [xmax, y], zorder=PORDER_REGLINE)
1✔
925

926
            # classical registers
927
            this_clbit_dict = {}
1✔
928
            for clbit in clbits_dict.values():
1✔
929
                y = clbit["y"] - fold_num * (glob_data["n_lines"] + 1)
1✔
930
                if y not in this_clbit_dict:
1✔
931
                    this_clbit_dict[y] = {
1✔
932
                        "val": 1,
933
                        "wire_label": clbit["wire_label"],
934
                        "register": clbit["register"],
935
                    }
936
                else:
937
                    this_clbit_dict[y]["val"] += 1
×
938

939
            for y, this_clbit in this_clbit_dict.items():
1✔
940
                # cregbundle
941
                if self._cregbundle and this_clbit["register"] is not None:
1✔
942
                    self._ax.plot(
×
943
                        [glob_data["x_offset"] + 0.2, glob_data["x_offset"] + 0.3],
944
                        [y - 0.1, y + 0.1],
945
                        color=self._style["cc"],
946
                        zorder=PORDER_REGLINE,
947
                    )
948
                    self._ax.text(
×
949
                        glob_data["x_offset"] + 0.1,
950
                        y + 0.1,
951
                        str(this_clbit["register"].size),
952
                        ha="left",
953
                        va="bottom",
954
                        fontsize=0.8 * self._style["fs"],
955
                        color=self._style["tc"],
956
                        clip_on=True,
957
                        zorder=PORDER_TEXT,
958
                    )
959
                self._ax.text(
1✔
960
                    glob_data["x_offset"] - 0.2,
961
                    y,
962
                    this_clbit["wire_label"],
963
                    ha="right",
964
                    va="center",
965
                    fontsize=1.25 * self._style["fs"],
966
                    color=self._style["tc"],
967
                    clip_on=True,
968
                    zorder=PORDER_TEXT,
969
                )
970
                # draw the clbit wire
971
                self._line(
1✔
972
                    [glob_data["x_offset"], y],
973
                    [xmax, y],
974
                    lc=self._style["cc"],
975
                    ls=self._style["cline"],
976
                    zorder=PORDER_REGLINE,
977
                )
978

979
            # lf vertical line at either end
980
            feedline_r = num_folds > 0 and num_folds > fold_num
1✔
981
            feedline_l = fold_num > 0
1✔
982
            if feedline_l or feedline_r:
1✔
983
                xpos_l = glob_data["x_offset"] - 0.01
×
984
                xpos_r = self._fold + glob_data["x_offset"] + 0.1
×
985
                ypos1 = -fold_num * (glob_data["n_lines"] + 1)
×
986
                ypos2 = -(fold_num + 1) * (glob_data["n_lines"]) - fold_num + 1
×
987
                if feedline_l:
×
988
                    self._ax.plot(
×
989
                        [xpos_l, xpos_l],
990
                        [ypos1, ypos2],
991
                        color=self._style["lc"],
992
                        linewidth=self._lwidth15,
993
                        zorder=PORDER_REGLINE,
994
                    )
995
                if feedline_r:
×
996
                    self._ax.plot(
×
997
                        [xpos_r, xpos_r],
998
                        [ypos1, ypos2],
999
                        color=self._style["lc"],
1000
                        linewidth=self._lwidth15,
1001
                        zorder=PORDER_REGLINE,
1002
                    )
1003
            # Mask off any lines or boxes in the bit label area to clean up
1004
            # from folding for ControlFlow and other wrapping gates
1005
            box = glob_data["patches_mod"].Rectangle(
1✔
1006
                xy=(glob_data["x_offset"] - 0.1, -fold_num * (glob_data["n_lines"] + 1) + 0.5),
1007
                width=-25.0,
1008
                height=-(fold_num + 1) * (glob_data["n_lines"] + 1),
1009
                fc=self._style["bg"],
1010
                ec=self._style["bg"],
1011
                linewidth=self._lwidth15,
1012
                zorder=PORDER_MASK,
1013
            )
1014
            self._ax.add_patch(box)
1✔
1015

1016
        # draw index number
1017
        if self._style["index"]:
1✔
1018
            for layer_num in range(max_x_index):
×
1019
                if self._fold > 0:
×
1020
                    x_coord = layer_num % self._fold + glob_data["x_offset"] + 0.53
×
1021
                    y_coord = -(layer_num // self._fold) * (glob_data["n_lines"] + 1) + 0.65
×
1022
                else:
1023
                    x_coord = layer_num + glob_data["x_offset"] + 0.53
×
1024
                    y_coord = 0.65
×
1025
                self._ax.text(
×
1026
                    x_coord,
1027
                    y_coord,
1028
                    str(layer_num + 1),
1029
                    ha="center",
1030
                    va="center",
1031
                    fontsize=self._style["sfs"],
1032
                    color=self._style["tc"],
1033
                    clip_on=True,
1034
                    zorder=PORDER_TEXT,
1035
                )
1036

1037
    def _add_nodes_and_coords(
1✔
1038
        self,
1039
        nodes,
1040
        node_data,
1041
        wire_map,
1042
        outer_circuit,
1043
        layer_widths,
1044
        qubits_dict,
1045
        clbits_dict,
1046
        glob_data,
1047
    ):
1048
        """Add the nodes from ControlFlowOps and their coordinates to the main circuit"""
1049
        for flow_drawers in self._flow_drawers.values():
1✔
1050
            for flow_drawer in flow_drawers:
×
1051
                nodes += flow_drawer._nodes
×
1052
                flow_drawer._get_coords(
×
1053
                    node_data,
1054
                    flow_drawer._flow_wire_map,
1055
                    outer_circuit,
1056
                    layer_widths,
1057
                    qubits_dict,
1058
                    clbits_dict,
1059
                    glob_data,
1060
                    flow_parent=flow_drawer._flow_parent,
1061
                )
1062
                # Recurse for ControlFlowOps inside the flow_drawer
1063
                flow_drawer._add_nodes_and_coords(
×
1064
                    nodes,
1065
                    node_data,
1066
                    wire_map,
1067
                    outer_circuit,
1068
                    layer_widths,
1069
                    qubits_dict,
1070
                    clbits_dict,
1071
                    glob_data,
1072
                )
1073

1074
    def _draw_ops(
1✔
1075
        self,
1076
        nodes,
1077
        node_data,
1078
        wire_map,
1079
        outer_circuit,
1080
        layer_widths,
1081
        qubits_dict,
1082
        clbits_dict,
1083
        glob_data,
1084
    ):
1085
        """Draw the gates in the circuit"""
1086

1087
        # Add the nodes from all the ControlFlowOps and their coordinates to the main nodes
1088
        self._add_nodes_and_coords(
1✔
1089
            nodes,
1090
            node_data,
1091
            wire_map,
1092
            outer_circuit,
1093
            layer_widths,
1094
            qubits_dict,
1095
            clbits_dict,
1096
            glob_data,
1097
        )
1098
        prev_x_index = -1
1✔
1099
        for layer in nodes:
1✔
1100
            l_width = []
1✔
1101
            curr_x_index = prev_x_index + 1
1✔
1102

1103
            # draw the gates in this layer
1104
            for node in layer:
1✔
1105
                op = node.op
1✔
1106

1107
                self._get_colors(node, node_data)
1✔
1108

1109
                # add conditional
1110
                if getattr(op, "condition", None) or isinstance(op, SwitchCaseOp):
1✔
1111
                    cond_xy = [
×
1112
                        self._plot_coord(
1113
                            node_data[node].x_index,
1114
                            clbits_dict[ii]["y"],
1115
                            layer_widths[node][0],
1116
                            glob_data,
1117
                            isinstance(op, ControlFlowOp),
1118
                        )
1119
                        for ii in clbits_dict
1120
                    ]
1121
                    self._condition(node, node_data, wire_map, outer_circuit, cond_xy, glob_data)
×
1122

1123
                # AnnotatedOperation with ControlModifier
1124
                mod_control = None
1✔
1125
                if getattr(op, "modifiers", None):
1✔
1126
                    canonical_modifiers = _canonicalize_modifiers(op.modifiers)
×
1127
                    for modifier in canonical_modifiers:
×
1128
                        if isinstance(modifier, ControlModifier):
×
1129
                            mod_control = modifier
×
1130
                            break
×
1131

1132
                # draw measure
1133
                if isinstance(op, Measure):
1✔
1134
                    self._measure(node, node_data, outer_circuit, glob_data)
×
1135

1136
                # draw barriers, snapshots, etc.
1137
                elif getattr(op, "_directive", False):
1✔
1138
                    if self._plot_barriers:
×
1139
                        self._barrier(node, node_data, glob_data)
×
1140

1141
                # draw the box for control flow circuits
1142
                elif isinstance(op, ControlFlowOp):
1✔
1143
                    self._flow_op_gate(node, node_data, glob_data)
×
1144

1145
                # draw single qubit gates
1146
                elif len(node_data[node].q_xy) == 1 and not node.cargs:
1✔
1147
                    self._gate(node, node_data, glob_data)
1✔
1148

1149
                # draw controlled gates
1150
                elif isinstance(op, ControlledGate) or mod_control:
1✔
1151
                    self._control_gate(node, node_data, glob_data, mod_control)
×
1152

1153
                # draw multi-qubit gate as final default
1154
                else:
1155
                    self._multiqubit_gate(node, node_data, glob_data)
1✔
1156

1157
                # Determine the max width of the circuit only at the top level
1158
                if not node_data[node].inside_flow:
1✔
1159
                    l_width.append(layer_widths[node][0])
1✔
1160

1161
            # adjust the column if there have been barriers encountered, but not plotted
1162
            barrier_offset = 0
1✔
1163
            if not self._plot_barriers:
1✔
1164
                # only adjust if everything in the layer wasn't plotted
1165
                barrier_offset = (
×
1166
                    -1 if all(getattr(nd.op, "_directive", False) for nd in layer) else 0
1167
                )
1168
            prev_x_index = curr_x_index + (max(l_width) if l_width else 0) + barrier_offset - 1
1✔
1169

1170
    def _get_colors(self, node, node_data):
1✔
1171
        """Get all the colors needed for drawing the circuit"""
1172

1173
        op = node.op
1✔
1174
        base_name = getattr(getattr(op, "base_gate", None), "name", None)
1✔
1175
        color = None
1✔
1176
        if node_data[node].raw_gate_text in self._style["dispcol"]:
1✔
1177
            color = self._style["dispcol"][node_data[node].raw_gate_text]
1✔
1178
        elif op.name in self._style["dispcol"]:
1✔
1179
            color = self._style["dispcol"][op.name]
×
1180
        if color is not None:
1✔
1181
            # Backward compatibility for style dict using 'displaycolor' with
1182
            # gate color and no text color, so test for str first
1183
            if isinstance(color, str):
1✔
1184
                fc = color
×
1185
                gt = self._style["gt"]
×
1186
            else:
1187
                fc = color[0]
1✔
1188
                gt = color[1]
1✔
1189
        # Treat special case of classical gates in iqx style by making all
1190
        # controlled gates of x, dcx, and swap the classical gate color
1191
        elif self._style["name"] in ["iqp", "iqx", "iqp-dark", "iqx-dark"] and base_name in [
1✔
1192
            "x",
1193
            "dcx",
1194
            "swap",
1195
        ]:
1196
            color = self._style["dispcol"][base_name]
×
1197
            if isinstance(color, str):
×
1198
                fc = color
×
1199
                gt = self._style["gt"]
×
1200
            else:
1201
                fc = color[0]
×
1202
                gt = color[1]
×
1203
        else:
1204
            fc = self._style["gc"]
1✔
1205
            gt = self._style["gt"]
1✔
1206

1207
        if self._style["name"] == "bw":
1✔
1208
            ec = self._style["ec"]
×
1209
            lc = self._style["lc"]
×
1210
        else:
1211
            ec = fc
1✔
1212
            lc = fc
1✔
1213
        # Subtext needs to be same color as gate text
1214
        sc = gt
1✔
1215
        node_data[node].fc = fc
1✔
1216
        node_data[node].ec = ec
1✔
1217
        node_data[node].gt = gt
1✔
1218
        node_data[node].tc = self._style["tc"]
1✔
1219
        node_data[node].sc = sc
1✔
1220
        node_data[node].lc = lc
1✔
1221

1222
    def _condition(self, node, node_data, wire_map, outer_circuit, cond_xy, glob_data):
1✔
1223
        """Add a conditional to a gate"""
1224

1225
        # For SwitchCaseOp convert the target to a fully closed Clbit or register
1226
        # in condition format
1227
        if isinstance(node.op, SwitchCaseOp):
×
1228
            if isinstance(node.op.target, expr.Expr):
×
1229
                condition = node.op.target
×
1230
            elif isinstance(node.op.target, Clbit):
×
1231
                condition = (node.op.target, 1)
×
1232
            else:
1233
                condition = (node.op.target, 2 ** (node.op.target.size) - 1)
×
1234
        else:
1235
            condition = node.op.condition
×
1236

1237
        override_fc = False
×
1238
        first_clbit = len(self._qubits)
×
1239
        cond_pos = []
×
1240

1241
        if isinstance(condition, expr.Expr):
×
1242
            # If fixing this, please update the docstrings of `QuantumCircuit.draw` and
1243
            # `visualization.circuit_drawer` to remove warnings.
1244

1245
            condition_bits = condition_resources(condition).clbits
×
1246
            label = "[expr]"
×
1247
            override_fc = True
×
1248
            registers = collections.defaultdict(list)
×
1249
            for bit in condition_bits:
×
1250
                registers[get_bit_register(outer_circuit, bit)].append(bit)
×
1251
            # Registerless bits don't care whether cregbundle is set.
1252
            cond_pos.extend(cond_xy[wire_map[bit] - first_clbit] for bit in registers.pop(None, ()))
×
1253
            if self._cregbundle:
×
1254
                cond_pos.extend(cond_xy[wire_map[register] - first_clbit] for register in registers)
×
1255
            else:
1256
                cond_pos.extend(
×
1257
                    cond_xy[wire_map[bit] - first_clbit]
1258
                    for bit in itertools.chain.from_iterable(registers.values())
1259
                )
1260
            val_bits = ["1"] * len(cond_pos)
×
1261
        else:
1262
            label, val_bits = get_condition_label_val(condition, self._circuit, self._cregbundle)
×
1263
            cond_bit_reg = condition[0]
×
1264
            cond_bit_val = int(condition[1])
×
1265
            override_fc = (
×
1266
                cond_bit_val != 0
1267
                and self._cregbundle
1268
                and isinstance(cond_bit_reg, ClassicalRegister)
1269
            )
1270

1271
            # In the first case, multiple bits are indicated on the drawing. In all
1272
            # other cases, only one bit is shown.
1273
            if not self._cregbundle and isinstance(cond_bit_reg, ClassicalRegister):
×
1274
                for idx in range(cond_bit_reg.size):
×
1275
                    cond_pos.append(cond_xy[wire_map[cond_bit_reg[idx]] - first_clbit])
×
1276

1277
            # If it's a register bit and cregbundle, need to use the register to find the location
1278
            elif self._cregbundle and isinstance(cond_bit_reg, Clbit):
×
1279
                register = get_bit_register(outer_circuit, cond_bit_reg)
×
1280
                if register is not None:
×
1281
                    cond_pos.append(cond_xy[wire_map[register] - first_clbit])
×
1282
                else:
1283
                    cond_pos.append(cond_xy[wire_map[cond_bit_reg] - first_clbit])
×
1284
            else:
1285
                cond_pos.append(cond_xy[wire_map[cond_bit_reg] - first_clbit])
×
1286

1287
        xy_plot = []
×
1288
        for val_bit, xy in zip(val_bits, cond_pos):
×
1289
            fc = self._style["lc"] if override_fc or val_bit == "1" else self._style["bg"]
×
1290
            box = glob_data["patches_mod"].Circle(
×
1291
                xy=xy,
1292
                radius=WID * 0.15,
1293
                fc=fc,
1294
                ec=self._style["lc"],
1295
                linewidth=self._lwidth15,
1296
                zorder=PORDER_GATE,
1297
            )
1298
            self._ax.add_patch(box)
×
1299
            xy_plot.append(xy)
×
1300

1301
        if not xy_plot:
×
1302
            # Expression that's only on new-style `expr.Var` nodes, and doesn't need any vertical
1303
            # line drawing.
1304
            return
×
1305

1306
        qubit_b = min(node_data[node].q_xy, key=lambda xy: xy[1])
×
1307
        clbit_b = min(xy_plot, key=lambda xy: xy[1])
×
1308

1309
        # For IfElseOp, WhileLoopOp or SwitchCaseOp, place the condition line
1310
        # near the left edge of the box
1311
        if isinstance(node.op, (IfElseOp, WhileLoopOp, SwitchCaseOp)):
×
1312
            qubit_b = (qubit_b[0], qubit_b[1] - (0.5 * HIG + 0.14))
×
1313

1314
        # display the label at the bottom of the lowest conditional and draw the double line
1315
        xpos, ypos = clbit_b
×
1316
        if isinstance(node.op, Measure):
×
1317
            xpos += 0.3
×
1318
        self._ax.text(
×
1319
            xpos,
1320
            ypos - 0.3 * HIG,
1321
            label,
1322
            ha="center",
1323
            va="top",
1324
            fontsize=self._style["sfs"],
1325
            color=self._style["tc"],
1326
            clip_on=True,
1327
            zorder=PORDER_TEXT,
1328
        )
1329
        self._line(qubit_b, clbit_b, lc=self._style["cc"], ls=self._style["cline"])
×
1330

1331
    def _measure(self, node, node_data, outer_circuit, glob_data):
1✔
1332
        """Draw the measure symbol and the line to the clbit"""
1333
        qx, qy = node_data[node].q_xy[0]
×
1334
        cx, cy = node_data[node].c_xy[0]
×
1335
        register, _, reg_index = get_bit_reg_index(outer_circuit, node.cargs[0])
×
1336

1337
        # draw gate box
1338
        self._gate(node, node_data, glob_data)
×
1339

1340
        # add measure symbol
1341
        qy_adj1 = 0.15 if self._measure_arrows else 0.05
×
1342
        arc = glob_data["patches_mod"].Arc(
×
1343
            xy=(qx, qy - qy_adj1 * HIG),
1344
            width=WID * 0.7,
1345
            height=HIG * 0.7,
1346
            theta1=0,
1347
            theta2=180,
1348
            fill=False,
1349
            ec=node_data[node].gt,
1350
            linewidth=self._lwidth2,
1351
            zorder=PORDER_GATE,
1352
        )
1353
        self._ax.add_patch(arc)
×
1354
        qy_adj2 = 0.2 if self._measure_arrows else 0.3
×
1355
        self._ax.plot(
×
1356
            [qx, qx + 0.35 * WID],
1357
            [qy - qy_adj1 * HIG, qy + qy_adj2 * HIG],
1358
            color=node_data[node].gt,
1359
            linewidth=self._lwidth2,
1360
            zorder=PORDER_GATE,
1361
        )
1362
        # If measure_arrows, draw the down arrow to the clbit
1363
        if self._measure_arrows:
×
1364
            self._line(
×
1365
                node_data[node].q_xy[0],
1366
                [cx, cy + 0.35 * WID],
1367
                lc=self._style["cc"],
1368
                ls=self._style["cline"],
1369
            )
1370
            arrowhead = glob_data["patches_mod"].Polygon(
×
1371
                (
1372
                    (cx - 0.20 * WID, cy + 0.35 * WID),
1373
                    (cx + 0.20 * WID, cy + 0.35 * WID),
1374
                    (cx, cy + 0.04),
1375
                ),
1376
                fc=self._style["cc"],
1377
                ec=None,
1378
            )
1379
            self._ax.add_artist(arrowhead)
×
1380
            # target
1381
            if self._cregbundle and register is not None:
×
1382
                self._ax.text(
×
1383
                    cx + 0.25,
1384
                    cy + 0.1,
1385
                    str(reg_index),
1386
                    ha="left",
1387
                    va="bottom",
1388
                    fontsize=0.8 * self._style["fs"],
1389
                    color=self._style["tc"],
1390
                    clip_on=True,
1391
                    zorder=PORDER_TEXT,
1392
                )
1393
        else:
1394
            # If not measure_arrows, write the reg_bit into the measure box
1395
            if register is not None:
×
1396
                label = f"{register.name}_{reg_index}"
×
1397
            else:
1398
                label = f"{reg_index}"
×
1399
            self._ax.text(
×
1400
                qx,
1401
                qy - 0.42 * HIG,
1402
                label,
1403
                ha="center",
1404
                va="bottom",
1405
                fontsize=self._style["sfs"],
1406
                color=self._style["tc"],
1407
                clip_on=True,
1408
                zorder=PORDER_TEXT,
1409
            )
1410

1411
    def _barrier(self, node, node_data, glob_data):
1✔
1412
        """Draw a barrier"""
1413
        for i, xy in enumerate(node_data[node].q_xy):
×
1414
            xpos, ypos = xy
×
1415
            # For the topmost barrier, reduce the rectangle if there's a label to allow for the text.
1416
            if i == 0 and node.op.label is not None:
×
1417
                ypos_adj = -0.35
×
1418
            else:
1419
                ypos_adj = 0.0
×
1420
            self._ax.plot(
×
1421
                [xpos, xpos],
1422
                [ypos + 0.5 + ypos_adj, ypos - 0.5],
1423
                linewidth=self._lwidth1,
1424
                linestyle="dashed",
1425
                color=self._style["lc"],
1426
                zorder=PORDER_TEXT,
1427
            )
1428
            box = glob_data["patches_mod"].Rectangle(
×
1429
                xy=(xpos - (0.3 * WID), ypos - 0.5),
1430
                width=0.6 * WID,
1431
                height=1.0 + ypos_adj,
1432
                fc=self._style["bc"],
1433
                ec=None,
1434
                alpha=0.6,
1435
                linewidth=self._lwidth15,
1436
                zorder=PORDER_BARRIER,
1437
            )
1438
            self._ax.add_patch(box)
×
1439

1440
            # display the barrier label at the top if there is one
1441
            if i == 0 and node.op.label is not None:
×
NEW
1442
                label = node.op.label
×
NEW
1443
                if len(label) > self._barrier_label_len:
×
NEW
1444
                    label = label[: self._barrier_label_len] + "..."
×
1445
                dir_ypos = ypos + 0.65 * HIG
×
1446
                self._ax.text(
×
1447
                    xpos,
1448
                    dir_ypos,
1449
                    label,
1450
                    ha="center",
1451
                    va="top",
1452
                    fontsize=self._style["fs"],
1453
                    color=node_data[node].tc,
1454
                    clip_on=True,
1455
                    zorder=PORDER_TEXT,
1456
                )
1457

1458
    def _gate(self, node, node_data, glob_data, xy=None):
1✔
1459
        """Draw a 1-qubit gate"""
1460
        if xy is None:
1✔
1461
            xy = node_data[node].q_xy[0]
1✔
1462
        xpos, ypos = xy
1✔
1463
        wid = max(node_data[node].width, WID)
1✔
1464

1465
        box = glob_data["patches_mod"].Rectangle(
1✔
1466
            xy=(xpos - 0.5 * wid, ypos - 0.5 * HIG),
1467
            width=wid,
1468
            height=HIG,
1469
            fc=node_data[node].fc,
1470
            ec=node_data[node].ec,
1471
            linewidth=self._lwidth15,
1472
            zorder=PORDER_GATE,
1473
        )
1474
        self._ax.add_patch(box)
1✔
1475

1476
        if node_data[node].gate_text:
1✔
1477
            gate_ypos = ypos
1✔
1478
            if node_data[node].param_text:
1✔
1479
                gate_ypos = ypos + 0.15 * HIG
×
1480
                self._ax.text(
×
1481
                    xpos,
1482
                    ypos - 0.3 * HIG,
1483
                    node_data[node].param_text,
1484
                    ha="center",
1485
                    va="center",
1486
                    fontsize=self._style["sfs"],
1487
                    color=node_data[node].sc,
1488
                    clip_on=True,
1489
                    zorder=PORDER_TEXT,
1490
                )
1491
            self._ax.text(
1✔
1492
                xpos,
1493
                gate_ypos,
1494
                node_data[node].gate_text,
1495
                ha="center",
1496
                va="center",
1497
                fontsize=self._style["fs"],
1498
                color=node_data[node].gt,
1499
                clip_on=True,
1500
                zorder=PORDER_TEXT,
1501
            )
1502

1503
    def _multiqubit_gate(self, node, node_data, glob_data, xy=None):
1✔
1504
        """Draw a gate covering more than one qubit"""
1505
        op = node.op
1✔
1506
        if xy is None:
1✔
1507
            xy = node_data[node].q_xy
1✔
1508

1509
        # Swap gate
1510
        if isinstance(op, SwapGate):
1✔
1511
            self._swap(xy, node_data[node].lc)
×
1512
            return
×
1513

1514
        # RZZ Gate
1515
        elif isinstance(op, RZZGate):
1✔
1516
            self._symmetric_gate(node, node_data, RZZGate, glob_data)
×
1517
            return
×
1518

1519
        c_xy = node_data[node].c_xy
1✔
1520
        xpos = min(x[0] for x in xy)
1✔
1521
        ypos = min(y[1] for y in xy)
1✔
1522
        ypos_max = max(y[1] for y in xy)
1✔
1523
        if c_xy:
1✔
1524
            cxpos = min(x[0] for x in c_xy)
1✔
1525
            cypos = min(y[1] for y in c_xy)
1✔
1526
            ypos = min(ypos, cypos)
1✔
1527

1528
        wid = max(node_data[node].width + 0.21, WID)
1✔
1529
        qubit_span = abs(ypos) - abs(ypos_max)
1✔
1530
        height = HIG + qubit_span
1✔
1531

1532
        box = glob_data["patches_mod"].Rectangle(
1✔
1533
            xy=(xpos - 0.5 * wid, ypos - 0.5 * HIG),
1534
            width=wid,
1535
            height=height,
1536
            fc=node_data[node].fc,
1537
            ec=node_data[node].ec,
1538
            linewidth=self._lwidth15,
1539
            zorder=PORDER_GATE,
1540
        )
1541
        self._ax.add_patch(box)
1✔
1542

1543
        # annotate inputs
1544
        for bit, y in enumerate([x[1] for x in xy]):
1✔
1545
            self._ax.text(
1✔
1546
                xpos + 0.07 - 0.5 * wid,
1547
                y,
1548
                str(bit),
1549
                ha="left",
1550
                va="center",
1551
                fontsize=self._style["fs"],
1552
                color=node_data[node].gt,
1553
                clip_on=True,
1554
                zorder=PORDER_TEXT,
1555
            )
1556
        if c_xy:
1✔
1557
            # annotate classical inputs
1558
            for bit, y in enumerate([x[1] for x in c_xy]):
1✔
1559
                self._ax.text(
1✔
1560
                    cxpos + 0.07 - 0.5 * wid,
1561
                    y,
1562
                    str(bit),
1563
                    ha="left",
1564
                    va="center",
1565
                    fontsize=self._style["fs"],
1566
                    color=node_data[node].gt,
1567
                    clip_on=True,
1568
                    zorder=PORDER_TEXT,
1569
                )
1570
        if node_data[node].gate_text:
1✔
1571
            gate_ypos = ypos + 0.5 * qubit_span
1✔
1572
            if node_data[node].param_text:
1✔
1573
                gate_ypos = ypos + 0.4 * height
×
1574
                self._ax.text(
×
1575
                    xpos + 0.11,
1576
                    ypos + 0.2 * height,
1577
                    node_data[node].param_text,
1578
                    ha="center",
1579
                    va="center",
1580
                    fontsize=self._style["sfs"],
1581
                    color=node_data[node].sc,
1582
                    clip_on=True,
1583
                    zorder=PORDER_TEXT,
1584
                )
1585
            self._ax.text(
1✔
1586
                xpos + 0.11,
1587
                gate_ypos,
1588
                node_data[node].gate_text,
1589
                ha="center",
1590
                va="center",
1591
                fontsize=self._style["fs"],
1592
                color=node_data[node].gt,
1593
                clip_on=True,
1594
                zorder=PORDER_TEXT,
1595
            )
1596

1597
    def _flow_op_gate(self, node, node_data, glob_data):
1✔
1598
        """Draw the box for a flow op circuit"""
1599
        xy = node_data[node].q_xy
×
1600
        xpos = min(x[0] for x in xy)
×
1601
        ypos = min(y[1] for y in xy)
×
1602
        ypos_max = max(y[1] for y in xy)
×
1603

1604
        # If a BoxOp, bring the right side back tight against the gates to allow for
1605
        # better spacing
1606
        if_width = node_data[node].width[0] + (WID if not isinstance(node.op, BoxOp) else -0.19)
×
1607
        box_width = if_width
×
1608
        # Add the else and case widths to the if_width
1609
        for ewidth in node_data[node].width[1:]:
×
1610
            if ewidth > 0.0:
×
1611
                box_width += ewidth + WID + 0.3
×
1612

1613
        qubit_span = abs(ypos) - abs(ypos_max)
×
1614
        height = HIG + qubit_span
×
1615

1616
        # Cycle through box colors based on depth.
1617
        # Default - blue, purple, green, black
1618
        colors = [
×
1619
            self._style["dispcol"]["h"][0],
1620
            self._style["dispcol"]["u"][0],
1621
            self._style["dispcol"]["x"][0],
1622
            self._style["cc"],
1623
        ]
1624
        # To fold box onto next lines, draw it repeatedly, shifting
1625
        # it left by x_shift and down by y_shift
1626
        fold_level = 0
×
1627
        end_x = xpos + box_width
×
1628

1629
        while end_x > 0.0:
×
1630
            x_shift = fold_level * self._fold
×
1631
            y_shift = fold_level * (glob_data["n_lines"] + 1)
×
1632
            end_x = xpos + box_width - x_shift if self._fold > 0 else 0.0
×
1633

1634
            if isinstance(node.op, IfElseOp):
×
1635
                flow_text = "  If"
×
1636
            elif isinstance(node.op, WhileLoopOp):
×
1637
                flow_text = " While"
×
1638
            elif isinstance(node.op, ForLoopOp):
×
1639
                flow_text = " For"
×
1640
            elif isinstance(node.op, SwitchCaseOp):
×
1641
                flow_text = "Switch"
×
1642
            elif isinstance(node.op, BoxOp):
×
1643
                flow_text = ""
×
1644
            else:
1645
                raise RuntimeError(f"unhandled control-flow op: {node.name}")
1646

1647
            # Some spacers. op_spacer moves 'Switch' back a bit for alignment,
1648
            # expr_spacer moves the expr over to line up with 'Switch' and
1649
            # empty_default_spacer makes the switch box longer if the default
1650
            # case is empty so text doesn't run past end of box.
1651
            if isinstance(node.op, SwitchCaseOp):
×
1652
                op_spacer = 0.04
×
1653
                expr_spacer = 0.0
×
1654
                empty_default_spacer = 0.3 if len(node.op.blocks[-1]) == 0 else 0.0
×
1655
            elif isinstance(node.op, BoxOp):
×
1656
                # Move the X start position back for a BoxOp, since there is no
1657
                # leading text. This tightens the BoxOp with other ops.
1658
                xpos -= 0.15
×
1659
                op_spacer = 0.0
×
1660
                expr_spacer = 0.0
×
1661
                empty_default_spacer = 0.0
×
1662
            else:
1663
                op_spacer = 0.08
×
1664
                expr_spacer = 0.02
×
1665
                empty_default_spacer = 0.0
×
1666

1667
            # FancyBbox allows rounded corners
1668
            box = glob_data["patches_mod"].FancyBboxPatch(
×
1669
                xy=(xpos - x_shift, ypos - 0.5 * HIG - y_shift),
1670
                width=box_width + empty_default_spacer,
1671
                height=height,
1672
                boxstyle="round, pad=0.1",
1673
                fc="none",
1674
                ec=colors[node_data[node].nest_depth % 4],
1675
                linewidth=self._lwidth3,
1676
                zorder=PORDER_FLOW,
1677
            )
1678
            self._ax.add_patch(box)
×
1679

1680
            # Indicate type of ControlFlowOp and if expression used, print below
1681
            self._ax.text(
×
1682
                xpos - x_shift - op_spacer,
1683
                ypos_max + 0.2 - y_shift,
1684
                flow_text,
1685
                ha="left",
1686
                va="center",
1687
                fontsize=self._style["fs"],
1688
                color=node_data[node].tc,
1689
                clip_on=True,
1690
                zorder=PORDER_FLOW,
1691
            )
1692
            self._ax.text(
×
1693
                xpos - x_shift + expr_spacer,
1694
                ypos_max + 0.2 - y_shift - 0.4,
1695
                node_data[node].expr_text,
1696
                ha="left",
1697
                va="center",
1698
                fontsize=self._style["sfs"],
1699
                color=node_data[node].tc,
1700
                clip_on=True,
1701
                zorder=PORDER_FLOW,
1702
            )
1703
            if isinstance(node.op, ForLoopOp):
×
1704
                idx_set = str(node_data[node].indexset)
×
1705
                # If a range was used display 'range' and grab the range value
1706
                # to be displayed below
1707
                if "range" in idx_set:
×
1708
                    idx_set = "r(" + idx_set[6:-1] + ")"
×
1709
                else:
1710
                    # If a tuple, show first 4 elements followed by '...'
1711
                    idx_set = str(node_data[node].indexset)[1:-1].split(",")[:5]
×
1712
                    if len(idx_set) > 4:
×
1713
                        idx_set[4] = "..."
×
1714
                    idx_set = f"{','.join(idx_set)}"
×
1715
                y_spacer = 0.2 if len(node.qargs) == 1 else 0.5
×
1716
                self._ax.text(
×
1717
                    xpos - x_shift - 0.04,
1718
                    ypos_max - y_spacer - y_shift,
1719
                    idx_set,
1720
                    ha="left",
1721
                    va="center",
1722
                    fontsize=self._style["sfs"],
1723
                    color=node_data[node].tc,
1724
                    clip_on=True,
1725
                    zorder=PORDER_FLOW,
1726
                )
1727
            # If there's an else or a case draw the vertical line and the name
1728
            else_case_text = "Else" if isinstance(node.op, IfElseOp) else "Case"
×
1729
            ewidth_incr = if_width
×
1730
            for circ_num, ewidth in enumerate(node_data[node].width[1:]):
×
1731
                if ewidth > 0.0:
×
1732
                    self._ax.plot(
×
1733
                        [xpos + ewidth_incr + 0.3 - x_shift, xpos + ewidth_incr + 0.3 - x_shift],
1734
                        [ypos - 0.5 * HIG - 0.08 - y_shift, ypos + height - 0.22 - y_shift],
1735
                        color=colors[node_data[node].nest_depth % 4],
1736
                        linewidth=3.0,
1737
                        linestyle="solid",
1738
                        zorder=PORDER_FLOW,
1739
                    )
1740
                    self._ax.text(
×
1741
                        xpos + ewidth_incr + 0.4 - x_shift,
1742
                        ypos_max + 0.2 - y_shift,
1743
                        else_case_text,
1744
                        ha="left",
1745
                        va="center",
1746
                        fontsize=self._style["fs"],
1747
                        color=node_data[node].tc,
1748
                        clip_on=True,
1749
                        zorder=PORDER_FLOW,
1750
                    )
1751
                    if isinstance(node.op, SwitchCaseOp):
×
1752
                        jump_val = node_data[node].jump_values[circ_num]
×
1753
                        # If only one value, e.g. (0,)
1754
                        if len(str(jump_val)) == 4:
×
1755
                            jump_text = str(jump_val)[1]
×
1756
                        elif "default" in str(jump_val):
×
1757
                            jump_text = "default"
×
1758
                        else:
1759
                            # If a tuple, show first 4 elements followed by '...'
1760
                            jump_text = str(jump_val)[1:-1].replace(" ", "").split(",")[:5]
×
1761
                            if len(jump_text) > 4:
×
1762
                                jump_text[4] = "..."
×
1763
                            jump_text = f"{', '.join(jump_text)}"
×
1764
                        y_spacer = 0.2 if len(node.qargs) == 1 else 0.5
×
1765
                        self._ax.text(
×
1766
                            xpos + ewidth_incr + 0.4 - x_shift,
1767
                            ypos_max - y_spacer - y_shift,
1768
                            jump_text,
1769
                            ha="left",
1770
                            va="center",
1771
                            fontsize=self._style["sfs"],
1772
                            color=node_data[node].tc,
1773
                            clip_on=True,
1774
                            zorder=PORDER_FLOW,
1775
                        )
1776
                ewidth_incr += ewidth + 1
×
1777

1778
            fold_level += 1
×
1779

1780
    def _control_gate(self, node, node_data, glob_data, mod_control):
1✔
1781
        """Draw a controlled gate"""
1782
        op = node.op
×
1783
        xy = node_data[node].q_xy
×
1784
        base_type = getattr(op, "base_gate", None)
×
1785
        qubit_b = min(xy, key=lambda xy: xy[1])
×
1786
        qubit_t = max(xy, key=lambda xy: xy[1])
×
1787
        num_ctrl_qubits = mod_control.num_ctrl_qubits if mod_control else op.num_ctrl_qubits
×
1788
        num_qargs = len(xy) - num_ctrl_qubits
×
1789
        ctrl_state = mod_control.ctrl_state if mod_control else op.ctrl_state
×
1790
        self._set_ctrl_bits(
×
1791
            ctrl_state,
1792
            num_ctrl_qubits,
1793
            xy,
1794
            glob_data,
1795
            ec=node_data[node].ec,
1796
            tc=node_data[node].tc,
1797
            text=node_data[node].ctrl_text,
1798
            qargs=node.qargs,
1799
        )
1800
        self._line(qubit_b, qubit_t, lc=node_data[node].lc)
×
1801

1802
        if isinstance(op, RZZGate) or isinstance(base_type, (U1Gate, PhaseGate, ZGate, RZZGate)):
×
1803
            self._symmetric_gate(node, node_data, base_type, glob_data)
×
1804

1805
        elif num_qargs == 1 and isinstance(base_type, XGate):
×
1806
            tgt_color = self._style["dispcol"]["target"]
×
1807
            tgt = tgt_color if isinstance(tgt_color, str) else tgt_color[0]
×
1808
            self._x_tgt_qubit(xy[num_ctrl_qubits], glob_data, ec=node_data[node].ec, ac=tgt)
×
1809

1810
        elif num_qargs == 1:
×
1811
            self._gate(node, node_data, glob_data, xy[num_ctrl_qubits:][0])
×
1812

1813
        elif isinstance(base_type, SwapGate):
×
1814
            self._swap(xy[num_ctrl_qubits:], node_data[node].lc)
×
1815

1816
        else:
1817
            self._multiqubit_gate(node, node_data, glob_data, xy[num_ctrl_qubits:])
×
1818

1819
    def _set_ctrl_bits(
1✔
1820
        self, ctrl_state, num_ctrl_qubits, qbit, glob_data, ec=None, tc=None, text="", qargs=None
1821
    ):
1822
        """Determine which qubits are controls and whether they are open or closed"""
1823
        # place the control label at the top or bottom of controls
1824
        if text:
×
1825
            qlist = [self._circuit.find_bit(qubit).index for qubit in qargs]
×
1826
            ctbits = qlist[:num_ctrl_qubits]
×
1827
            qubits = qlist[num_ctrl_qubits:]
×
1828
            max_ctbit = max(ctbits)
×
1829
            min_ctbit = min(ctbits)
×
1830
            top = min(qubits) > min_ctbit
×
1831

1832
        # display the control qubits as open or closed based on ctrl_state
1833
        cstate = f"{ctrl_state:b}".rjust(num_ctrl_qubits, "0")[::-1]
×
1834
        for i in range(num_ctrl_qubits):
×
1835
            fc_open_close = ec if cstate[i] == "1" else self._style["bg"]
×
1836
            text_top = None
×
1837
            if text:
×
1838
                if top and qlist[i] == min_ctbit:
×
1839
                    text_top = True
×
1840
                elif not top and qlist[i] == max_ctbit:
×
1841
                    text_top = False
×
1842
            self._ctrl_qubit(
×
1843
                qbit[i], glob_data, fc=fc_open_close, ec=ec, tc=tc, text=text, text_top=text_top
1844
            )
1845

1846
    def _ctrl_qubit(self, xy, glob_data, fc=None, ec=None, tc=None, text="", text_top=None):
1✔
1847
        """Draw a control circle and if top or bottom control, draw control label"""
1848
        xpos, ypos = xy
×
1849
        box = glob_data["patches_mod"].Circle(
×
1850
            xy=(xpos, ypos),
1851
            radius=WID * 0.15,
1852
            fc=fc,
1853
            ec=ec,
1854
            linewidth=self._lwidth15,
1855
            zorder=PORDER_GATE,
1856
        )
1857
        self._ax.add_patch(box)
×
1858

1859
        # adjust label height according to number of lines of text
1860
        label_padding = 0.7
×
1861
        if text is not None:
×
1862
            text_lines = text.count("\n")
×
1863
            if not text.endswith("(cal)\n"):
×
1864
                for _ in range(text_lines):
×
1865
                    label_padding += 0.3
×
1866

1867
        if text_top is None:
×
1868
            return
×
1869

1870
        # display the control label at the top or bottom if there is one
1871
        ctrl_ypos = ypos + label_padding * HIG if text_top else ypos - 0.3 * HIG
×
1872
        self._ax.text(
×
1873
            xpos,
1874
            ctrl_ypos,
1875
            text,
1876
            ha="center",
1877
            va="top",
1878
            fontsize=self._style["sfs"],
1879
            color=tc,
1880
            clip_on=True,
1881
            zorder=PORDER_TEXT,
1882
        )
1883

1884
    def _x_tgt_qubit(self, xy, glob_data, ec=None, ac=None):
1✔
1885
        """Draw the cnot target symbol"""
1886
        linewidth = self._lwidth2
×
1887
        xpos, ypos = xy
×
1888
        box = glob_data["patches_mod"].Circle(
×
1889
            xy=(xpos, ypos),
1890
            radius=HIG * 0.35,
1891
            fc=ec,
1892
            ec=ec,
1893
            linewidth=linewidth,
1894
            zorder=PORDER_GATE,
1895
        )
1896
        self._ax.add_patch(box)
×
1897

1898
        # add '+' symbol
1899
        self._ax.plot(
×
1900
            [xpos, xpos],
1901
            [ypos - 0.2 * HIG, ypos + 0.2 * HIG],
1902
            color=ac,
1903
            linewidth=linewidth,
1904
            zorder=PORDER_GATE_PLUS,
1905
        )
1906
        self._ax.plot(
×
1907
            [xpos - 0.2 * HIG, xpos + 0.2 * HIG],
1908
            [ypos, ypos],
1909
            color=ac,
1910
            linewidth=linewidth,
1911
            zorder=PORDER_GATE_PLUS,
1912
        )
1913

1914
    def _symmetric_gate(self, node, node_data, base_type, glob_data):
1✔
1915
        """Draw symmetric gates for cz, cu1, cp, and rzz"""
1916
        op = node.op
×
1917
        xy = node_data[node].q_xy
×
1918
        qubit_b = min(xy, key=lambda xy: xy[1])
×
1919
        qubit_t = max(xy, key=lambda xy: xy[1])
×
1920
        base_type = getattr(op, "base_gate", None)
×
1921
        ec = node_data[node].ec
×
1922
        tc = node_data[node].tc
×
1923
        lc = node_data[node].lc
×
1924

1925
        # cz and mcz gates
1926
        if not isinstance(op, ZGate) and isinstance(base_type, ZGate):
×
1927
            num_ctrl_qubits = op.num_ctrl_qubits
×
1928
            self._ctrl_qubit(xy[-1], glob_data, fc=ec, ec=ec, tc=tc)
×
1929
            self._line(qubit_b, qubit_t, lc=lc, zorder=PORDER_LINE_PLUS)
×
1930

1931
        # cu1, cp, rzz, and controlled rzz gates (sidetext gates)
1932
        elif isinstance(op, RZZGate) or isinstance(base_type, (U1Gate, PhaseGate, RZZGate)):
×
1933
            num_ctrl_qubits = 0 if isinstance(op, RZZGate) else op.num_ctrl_qubits
×
1934
            gate_text = "P" if isinstance(base_type, PhaseGate) else node_data[node].gate_text
×
1935

1936
            self._ctrl_qubit(xy[num_ctrl_qubits], glob_data, fc=ec, ec=ec, tc=tc)
×
1937
            if not isinstance(base_type, (U1Gate, PhaseGate)):
×
1938
                self._ctrl_qubit(xy[num_ctrl_qubits + 1], glob_data, fc=ec, ec=ec, tc=tc)
×
1939

1940
            self._sidetext(
×
1941
                node,
1942
                node_data,
1943
                qubit_b,
1944
                tc=tc,
1945
                text=f"{gate_text} ({node_data[node].param_text})",
1946
            )
1947
            self._line(qubit_b, qubit_t, lc=lc)
×
1948

1949
    def _swap(self, xy, color=None):
1✔
1950
        """Draw a Swap gate"""
1951
        self._swap_cross(xy[0], color=color)
×
1952
        self._swap_cross(xy[1], color=color)
×
1953
        self._line(xy[0], xy[1], lc=color)
×
1954

1955
    def _swap_cross(self, xy, color=None):
1✔
1956
        """Draw the Swap cross symbol"""
1957
        xpos, ypos = xy
×
1958

1959
        self._ax.plot(
×
1960
            [xpos - 0.20 * WID, xpos + 0.20 * WID],
1961
            [ypos - 0.20 * WID, ypos + 0.20 * WID],
1962
            color=color,
1963
            linewidth=self._lwidth2,
1964
            zorder=PORDER_LINE_PLUS,
1965
        )
1966
        self._ax.plot(
×
1967
            [xpos - 0.20 * WID, xpos + 0.20 * WID],
1968
            [ypos + 0.20 * WID, ypos - 0.20 * WID],
1969
            color=color,
1970
            linewidth=self._lwidth2,
1971
            zorder=PORDER_LINE_PLUS,
1972
        )
1973

1974
    def _sidetext(self, node, node_data, xy, tc=None, text=""):
1✔
1975
        """Draw the sidetext for symmetric gates"""
1976
        xpos, ypos = xy
×
1977

1978
        # 0.11 = the initial gap, add 1/2 text width to place on the right
1979
        xp = xpos + 0.11 + node_data[node].width / 2
×
1980
        self._ax.text(
×
1981
            xp,
1982
            ypos + HIG,
1983
            text,
1984
            ha="center",
1985
            va="top",
1986
            fontsize=self._style["sfs"],
1987
            color=tc,
1988
            clip_on=True,
1989
            zorder=PORDER_TEXT,
1990
        )
1991

1992
    def _line(self, xy0, xy1, lc=None, ls=None, zorder=PORDER_LINE):
1✔
1993
        """Draw a line from xy0 to xy1"""
1994
        x0, y0 = xy0
1✔
1995
        x1, y1 = xy1
1✔
1996
        linecolor = self._style["lc"] if lc is None else lc
1✔
1997
        linestyle = "solid" if ls is None else ls
1✔
1998

1999
        if linestyle == "doublet":
1✔
2000
            theta = np.arctan2(np.abs(x1 - x0), np.abs(y1 - y0))
1✔
2001
            dx = 0.05 * WID * np.cos(theta)
1✔
2002
            dy = 0.05 * WID * np.sin(theta)
1✔
2003
            self._ax.plot(
1✔
2004
                [x0 + dx, x1 + dx],
2005
                [y0 + dy, y1 + dy],
2006
                color=linecolor,
2007
                linewidth=self._lwidth2,
2008
                linestyle="solid",
2009
                zorder=zorder,
2010
            )
2011
            self._ax.plot(
1✔
2012
                [x0 - dx, x1 - dx],
2013
                [y0 - dy, y1 - dy],
2014
                color=linecolor,
2015
                linewidth=self._lwidth2,
2016
                linestyle="solid",
2017
                zorder=zorder,
2018
            )
2019
        else:
2020
            self._ax.plot(
1✔
2021
                [x0, x1],
2022
                [y0, y1],
2023
                color=linecolor,
2024
                linewidth=self._lwidth2,
2025
                linestyle=linestyle,
2026
                zorder=zorder,
2027
            )
2028

2029
    def _plot_coord(self, x_index, y_index, gate_width, glob_data, flow_op=False):
1✔
2030
        """Get the coord positions for an index"""
2031

2032
        # Check folding
2033
        fold = self._fold if self._fold > 0 else INFINITE_FOLD
1✔
2034
        h_pos = x_index % fold + 1
1✔
2035

2036
        # Don't fold flow_ops here, only gates inside the flow_op
2037
        if not flow_op and h_pos + (gate_width - 1) > fold:
1✔
2038
            x_index += fold - (h_pos - 1)
×
2039
        x_pos = x_index % fold + glob_data["x_offset"] + 0.04
1✔
2040
        if not flow_op:
1✔
2041
            x_pos += 0.5 * gate_width
1✔
2042
        else:
2043
            x_pos += 0.25
×
2044
        y_pos = y_index - (x_index // fold) * (glob_data["n_lines"] + 1)
1✔
2045

2046
        # x_index could have been updated, so need to store
2047
        glob_data["next_x_index"] = x_index
1✔
2048
        return x_pos, y_pos
1✔
2049

2050

2051
class NodeData:
1✔
2052
    """Class containing drawing data on a per node basis"""
2053

2054
    def __init__(self):
1✔
2055
        # Node data for positioning
2056
        self.width = 0.0
1✔
2057
        self.x_index = 0
1✔
2058
        self.q_xy = []
1✔
2059
        self.c_xy = []
1✔
2060

2061
        # Node data for text
2062
        self.gate_text = ""
1✔
2063
        self.raw_gate_text = ""
1✔
2064
        self.ctrl_text = ""
1✔
2065
        self.param_text = ""
1✔
2066

2067
        # Node data for color
2068
        self.fc = self.ec = self.lc = self.sc = self.gt = self.tc = 0
1✔
2069

2070
        # Special values stored for ControlFlowOps
2071
        self.nest_depth = 0
1✔
2072
        self.expr_width = 0.0
1✔
2073
        self.expr_text = ""
1✔
2074
        self.inside_flow = False
1✔
2075
        self.indexset = ()  # List of indices used for ForLoopOp
1✔
2076
        self.jump_values = []  # List of jump values used for SwitchCaseOp
1✔
2077
        self.circ_num = 0  # Which block is it in op.blocks
1✔
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