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

Qiskit / qiskit / 26277326689

22 May 2026 08:32AM UTC coverage: 87.467% (-0.03%) from 87.494%
26277326689

Pull #14618

github

web-flow
Merge be0e5057c into 376781740
Pull Request #14618: New classical expr.Range specification

373 of 500 new or added lines in 16 files covered. (74.6%)

3 existing lines in 3 files now uncovered.

108776 of 124362 relevant lines covered (87.47%)

953953.42 hits per line

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

46.98
/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
                # Truncate directive labels to match the rendered length so the layer
435
                # width doesn't account for text that will never be displayed.
436
                if getattr(op, "_directive", False) and len(gate_text) > self._barrier_label_len:
1✔
437
                    gate_text = gate_text[: self._barrier_label_len] + "..."
×
438
                node_data[node].gate_text = gate_text
1✔
439
                node_data[node].ctrl_text = ctrl_text
1✔
440
                # Measure doesn't use raw_gate_text since it displays a dial
441
                if not isinstance(op, Measure):
1✔
442
                    node_data[node].raw_gate_text = raw_gate_text
1✔
443
                node_data[node].param_text = ""
1✔
444

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

454
                if isinstance(op, SwapGate) or isinstance(base_type, SwapGate):
1✔
455
                    continue
×
456

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

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

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

499
                    if (isinstance(op, SwitchCaseOp) and isinstance(op.target, expr.Expr)) or (
×
500
                        getattr(op, "condition", None) and isinstance(op.condition, expr.Expr)
501
                    ):
502

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

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

543
                        expr_width = self._get_text_width(
×
544
                            node_data[node].expr_text, glob_data, fontsize=self._style["sfs"]
545
                        )
546
                        node_data[node].expr_width = int(expr_width)
×
547

548
                    # Get the list of circuits to iterate over from the blocks
549
                    circuit_list = list(node.op.blocks)
×
550

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

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

564
                    # Now process the circuits inside the ControlFlowOps
565
                    for circ_num, circuit in enumerate(circuit_list):
×
566
                        # Only add expr_width for if, while, and switch
567
                        raw_gate_width = expr_width if circ_num == 0 else 0.0
×
568

569
                        # Depth of nested ControlFlowOp used for color of box
570
                        if self._flow_parent is not None:
×
571
                            node_data[node].nest_depth = node_data[self._flow_parent].nest_depth + 1
×
572

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

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

606
                        # flow_parent is the parent of the new class instance
607
                        flow_drawer._flow_parent = node
×
608
                        flow_drawer._flow_wire_map = flow_wire_map
×
609
                        self._flow_drawers[node].append(flow_drawer)
×
610

611
                        # Recursively call _get_layer_widths for the circuit inside the ControlFlowOp
612
                        flow_widths = flow_drawer._get_layer_widths(
×
613
                            node_data, flow_wire_map, outer_circuit, glob_data
614
                        )
615
                        layer_widths.update(flow_widths)
×
616

617
                        for flow_layer in flow_nodes:
×
618
                            for flow_node in flow_layer:
×
619
                                node_data[flow_node].circ_num = circ_num
×
620

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

631
                        # Need extra incr of 1.0 for else and case boxes
632
                        gate_width += raw_gate_width + (1.0 if circ_num > 0 else 0.0)
×
633

634
                        # Minor adjustment so else and case section gates align with indexes
635
                        if circ_num > 0:
×
636
                            raw_gate_width += 0.045
×
637

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

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

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

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

676
        return layer_widths
1✔
677

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

681
        longest_wire_label_width = 0
1✔
682
        glob_data["n_lines"] = 0
1✔
683
        initial_qbit = r" $|0\rangle$" if self._initial_state else ""
1✔
684
        initial_cbit = " 0" if self._initial_state else ""
1✔
685

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

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

706
            wire_label = get_wire_label(
1✔
707
                "mpl", register, index, layout=self._layout, cregbundle=self._cregbundle
708
            )
709
            initial_bit = initial_qbit if isinstance(wire, Qubit) else initial_cbit
1✔
710

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

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

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

745
                pos = y_off - idx
1✔
746
                clbits_dict[ii] = {
1✔
747
                    "y": pos,
748
                    "wire_label": wire_label,
749
                    "register": register,
750
                }
751
        glob_data["x_offset"] = -1.2 + longest_wire_label_width
1✔
752

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

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

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

794
                # get qubit indexes
795
                q_indxs = []
1✔
796
                for qarg in node.qargs:
1✔
797
                    if qarg in self._qubits:
1✔
798
                        q_indxs.append(wire_map[qarg])
1✔
799

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

813
                flow_op = isinstance(node.op, ControlFlowOp)
1✔
814

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

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

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

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

860
        return prev_x_index + 1
1✔
861

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

865
        from pylatexenc.latex2text import LatexNodes2Text
1✔
866

867
        if not text:
1✔
868
            return 0.0
1✔
869

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

879
        # If there are subscripts or superscripts in mathtext string
880
        # we need to account for that spacing by manually removing
881
        # from text string for text length
882

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

892
        # This changes hyphen to + to match width of math mode minus sign.
893
        if param:
1✔
894
            text = text.replace("-", "+")
×
895

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

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

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

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

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

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

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

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

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

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

1107
            # draw the gates in this layer
1108
            for node in layer:
1✔
1109
                op = node.op
1✔
1110

1111
                self._get_colors(node, node_data)
1✔
1112

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

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

1136
                # draw measure
1137
                if isinstance(op, Measure):
1✔
1138
                    self._measure(node, node_data, outer_circuit, glob_data)
×
1139

1140
                # draw barriers, snapshots, etc.
1141
                elif getattr(op, "_directive", False):
1✔
1142
                    if self._plot_barriers:
×
1143
                        self._barrier(node, node_data, glob_data)
×
1144

1145
                # draw the box for control flow circuits
1146
                elif isinstance(op, ControlFlowOp):
1✔
1147
                    self._flow_op_gate(node, node_data, glob_data)
×
1148

1149
                # draw single qubit gates
1150
                elif len(node_data[node].q_xy) == 1 and not node.cargs:
1✔
1151
                    self._gate(node, node_data, glob_data)
1✔
1152

1153
                # draw controlled gates
1154
                elif isinstance(op, ControlledGate) or mod_control:
1✔
1155
                    self._control_gate(node, node_data, glob_data, mod_control)
×
1156

1157
                # draw multi-qubit gate as final default
1158
                else:
1159
                    self._multiqubit_gate(node, node_data, glob_data)
1✔
1160

1161
                # Determine the max width of the circuit only at the top level
1162
                if not node_data[node].inside_flow:
1✔
1163
                    l_width.append(layer_widths[node][0])
1✔
1164

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

1174
    def _get_colors(self, node, node_data):
1✔
1175
        """Get all the colors needed for drawing the circuit"""
1176

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

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

1226
    def _condition(self, node, node_data, wire_map, outer_circuit, cond_xy, glob_data):
1✔
1227
        """Add a conditional to a gate"""
1228

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

1241
        override_fc = False
×
1242
        first_clbit = len(self._qubits)
×
1243
        cond_pos = []
×
1244

1245
        if isinstance(condition, expr.Expr):
×
1246
            # If fixing this, please update the docstrings of `QuantumCircuit.draw` and
1247
            # `visualization.circuit_drawer` to remove warnings.
1248

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

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

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

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

1305
        if not xy_plot:
×
1306
            # Expression that's only on new-style `expr.Var` nodes, and doesn't need any vertical
1307
            # line drawing.
1308
            return
×
1309

1310
        qubit_b = min(node_data[node].q_xy, key=lambda xy: xy[1])
×
1311
        clbit_b = min(xy_plot, key=lambda xy: xy[1])
×
1312

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

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

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

1341
        # draw gate box
1342
        self._gate(node, node_data, glob_data)
×
1343

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

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

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

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

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

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

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

1513
        # Swap gate
1514
        if isinstance(op, SwapGate):
1✔
1515
            self._swap(xy, node_data[node].lc)
×
1516
            return
×
1517

1518
        # RZZ Gate
1519
        elif isinstance(op, RZZGate):
1✔
1520
            self._symmetric_gate(node, node_data, RZZGate, glob_data)
×
1521
            return
×
1522

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

1532
        wid = max(node_data[node].width + 0.21, WID)
1✔
1533
        qubit_span = abs(ypos) - abs(ypos_max)
1✔
1534
        height = HIG + qubit_span
1✔
1535

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

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

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

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

1617
        qubit_span = abs(ypos) - abs(ypos_max)
×
1618
        height = HIG + qubit_span
×
1619

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

1633
        while end_x > 0.0:
×
1634
            x_shift = fold_level * self._fold
×
1635
            y_shift = fold_level * (glob_data["n_lines"] + 1)
×
1636
            end_x = xpos + box_width - x_shift if self._fold > 0 else 0.0
×
1637

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

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

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

1684
            # Indicate type of ControlFlowOp and if expression used, print below
1685
            self._ax.text(
×
1686
                xpos - x_shift - op_spacer,
1687
                ypos_max + 0.2 - y_shift,
1688
                flow_text,
1689
                ha="left",
1690
                va="center",
1691
                fontsize=self._style["fs"],
1692
                color=node_data[node].tc,
1693
                clip_on=True,
1694
                zorder=PORDER_FLOW,
1695
            )
1696
            self._ax.text(
×
1697
                xpos - x_shift + expr_spacer,
1698
                ypos_max + 0.2 - y_shift - 0.4,
1699
                node_data[node].expr_text,
1700
                ha="left",
1701
                va="center",
1702
                fontsize=self._style["sfs"],
1703
                color=node_data[node].tc,
1704
                clip_on=True,
1705
                zorder=PORDER_FLOW,
1706
            )
1707
            if isinstance(node.op, ForLoopOp):
×
NEW
1708
                indexset = node_data[node].indexset
×
1709
                # Check if it's an expr.Range object first
NEW
1710
                if isinstance(indexset, expr.Range):
×
1711
                    # Extract start, stop, step for cleaner display
NEW
1712
                    def _get_display_name(expr_obj):
×
1713
                        """Get a clean display name for an expression."""
1714
                        # Try to get the name attribute if it's a Var
NEW
1715
                        if hasattr(expr_obj, "name") and expr_obj.name is not None:
×
NEW
1716
                            return str(expr_obj.name)
×
1717
                        # Try to get the value if it's a Value
NEW
1718
                        if hasattr(expr_obj, "value"):
×
NEW
1719
                            return str(expr_obj.value)
×
1720
                        # Fall back to string representation, but truncate if too long
NEW
1721
                        s = str(expr_obj)
×
NEW
1722
                        return s[:15] + "..." if len(s) > 15 else s
×
1723

NEW
1724
                    start_str = _get_display_name(indexset.start)
×
NEW
1725
                    stop_str = _get_display_name(indexset.stop)
×
1726
                    # Only show step if it's not the default (1)
NEW
1727
                    step_val = indexset.step.value if hasattr(indexset.step, "value") else None
×
NEW
1728
                    if step_val is not None and step_val == 1:
×
NEW
1729
                        idx_set = f"r({start_str}, {stop_str})"
×
1730
                    else:
NEW
1731
                        step_str = _get_display_name(indexset.step)
×
NEW
1732
                        idx_set = f"r({start_str}, {stop_str}, {step_str})"
×
NEW
1733
                elif isinstance(indexset, range):
×
1734
                    # Python range object
NEW
1735
                    if indexset.step == 1:
×
NEW
1736
                        idx_set = f"r({indexset.start}, {indexset.stop})"
×
1737
                    else:
NEW
1738
                        idx_set = f"r({indexset.start}, {indexset.stop}, {indexset.step})"
×
1739
                else:
1740
                    # If a tuple, show first 4 elements followed by '...'
NEW
1741
                    idx_set = str(indexset)[1:-1].split(",")[:5]
×
1742
                    if len(idx_set) > 4:
×
1743
                        idx_set[4] = "..."
×
1744
                    idx_set = f"{','.join(idx_set)}"
×
1745
                y_spacer = 0.2 if len(node.qargs) == 1 else 0.5
×
1746
                self._ax.text(
×
1747
                    xpos - x_shift - 0.04,
1748
                    ypos_max - y_spacer - y_shift,
1749
                    idx_set,
1750
                    ha="left",
1751
                    va="center",
1752
                    fontsize=self._style["sfs"],
1753
                    color=node_data[node].tc,
1754
                    clip_on=True,
1755
                    zorder=PORDER_FLOW,
1756
                )
1757
            # If there's an else or a case draw the vertical line and the name
1758
            else_case_text = "Else" if isinstance(node.op, IfElseOp) else "Case"
×
1759
            ewidth_incr = if_width
×
1760
            for circ_num, ewidth in enumerate(node_data[node].width[1:]):
×
1761
                if ewidth > 0.0:
×
1762
                    self._ax.plot(
×
1763
                        [xpos + ewidth_incr + 0.3 - x_shift, xpos + ewidth_incr + 0.3 - x_shift],
1764
                        [ypos - 0.5 * HIG - 0.08 - y_shift, ypos + height - 0.22 - y_shift],
1765
                        color=colors[node_data[node].nest_depth % 4],
1766
                        linewidth=3.0,
1767
                        linestyle="solid",
1768
                        zorder=PORDER_FLOW,
1769
                    )
1770
                    self._ax.text(
×
1771
                        xpos + ewidth_incr + 0.4 - x_shift,
1772
                        ypos_max + 0.2 - y_shift,
1773
                        else_case_text,
1774
                        ha="left",
1775
                        va="center",
1776
                        fontsize=self._style["fs"],
1777
                        color=node_data[node].tc,
1778
                        clip_on=True,
1779
                        zorder=PORDER_FLOW,
1780
                    )
1781
                    if isinstance(node.op, SwitchCaseOp):
×
1782
                        jump_val = node_data[node].jump_values[circ_num]
×
1783
                        # If only one value, e.g. (0,)
1784
                        if len(str(jump_val)) == 4:
×
1785
                            jump_text = str(jump_val)[1]
×
1786
                        elif "default" in str(jump_val):
×
1787
                            jump_text = "default"
×
1788
                        else:
1789
                            # If a tuple, show first 4 elements followed by '...'
1790
                            jump_text = str(jump_val)[1:-1].replace(" ", "").split(",")[:5]
×
1791
                            if len(jump_text) > 4:
×
1792
                                jump_text[4] = "..."
×
1793
                            jump_text = f"{', '.join(jump_text)}"
×
1794
                        y_spacer = 0.2 if len(node.qargs) == 1 else 0.5
×
1795
                        self._ax.text(
×
1796
                            xpos + ewidth_incr + 0.4 - x_shift,
1797
                            ypos_max - y_spacer - y_shift,
1798
                            jump_text,
1799
                            ha="left",
1800
                            va="center",
1801
                            fontsize=self._style["sfs"],
1802
                            color=node_data[node].tc,
1803
                            clip_on=True,
1804
                            zorder=PORDER_FLOW,
1805
                        )
1806
                ewidth_incr += ewidth + 1
×
1807

1808
            fold_level += 1
×
1809

1810
    def _control_gate(self, node, node_data, glob_data, mod_control):
1✔
1811
        """Draw a controlled gate"""
1812
        op = node.op
×
1813
        xy = node_data[node].q_xy
×
1814
        base_type = getattr(op, "base_gate", None)
×
1815
        qubit_b = min(xy, key=lambda xy: xy[1])
×
1816
        qubit_t = max(xy, key=lambda xy: xy[1])
×
1817
        num_ctrl_qubits = mod_control.num_ctrl_qubits if mod_control else op.num_ctrl_qubits
×
1818
        num_qargs = len(xy) - num_ctrl_qubits
×
1819
        ctrl_state = mod_control.ctrl_state if mod_control else op.ctrl_state
×
1820
        self._set_ctrl_bits(
×
1821
            ctrl_state,
1822
            num_ctrl_qubits,
1823
            xy,
1824
            glob_data,
1825
            ec=node_data[node].ec,
1826
            tc=node_data[node].tc,
1827
            text=node_data[node].ctrl_text,
1828
            qargs=node.qargs,
1829
        )
1830
        self._line(qubit_b, qubit_t, lc=node_data[node].lc)
×
1831

1832
        if isinstance(op, RZZGate) or isinstance(base_type, (U1Gate, PhaseGate, ZGate, RZZGate)):
×
1833
            self._symmetric_gate(node, node_data, base_type, glob_data)
×
1834

1835
        elif num_qargs == 1 and isinstance(base_type, XGate):
×
1836
            tgt_color = self._style["dispcol"]["target"]
×
1837
            tgt = tgt_color if isinstance(tgt_color, str) else tgt_color[0]
×
1838
            self._x_tgt_qubit(xy[num_ctrl_qubits], glob_data, ec=node_data[node].ec, ac=tgt)
×
1839

1840
        elif num_qargs == 1:
×
1841
            self._gate(node, node_data, glob_data, xy[num_ctrl_qubits:][0])
×
1842

1843
        elif isinstance(base_type, SwapGate):
×
1844
            self._swap(xy[num_ctrl_qubits:], node_data[node].lc)
×
1845

1846
        else:
1847
            self._multiqubit_gate(node, node_data, glob_data, xy[num_ctrl_qubits:])
×
1848

1849
    def _set_ctrl_bits(
1✔
1850
        self, ctrl_state, num_ctrl_qubits, qbit, glob_data, ec=None, tc=None, text="", qargs=None
1851
    ):
1852
        """Determine which qubits are controls and whether they are open or closed"""
1853
        # place the control label at the top or bottom of controls
1854
        if text:
×
1855
            qlist = [self._circuit.find_bit(qubit).index for qubit in qargs]
×
1856
            ctbits = qlist[:num_ctrl_qubits]
×
1857
            qubits = qlist[num_ctrl_qubits:]
×
1858
            max_ctbit = max(ctbits)
×
1859
            min_ctbit = min(ctbits)
×
1860
            top = min(qubits) > min_ctbit
×
1861

1862
        # display the control qubits as open or closed based on ctrl_state
1863
        cstate = f"{ctrl_state:b}".rjust(num_ctrl_qubits, "0")[::-1]
×
1864
        for i in range(num_ctrl_qubits):
×
1865
            fc_open_close = ec if cstate[i] == "1" else self._style["bg"]
×
1866
            text_top = None
×
1867
            if text:
×
1868
                if top and qlist[i] == min_ctbit:
×
1869
                    text_top = True
×
1870
                elif not top and qlist[i] == max_ctbit:
×
1871
                    text_top = False
×
1872
            self._ctrl_qubit(
×
1873
                qbit[i], glob_data, fc=fc_open_close, ec=ec, tc=tc, text=text, text_top=text_top
1874
            )
1875

1876
    def _ctrl_qubit(self, xy, glob_data, fc=None, ec=None, tc=None, text="", text_top=None):
1✔
1877
        """Draw a control circle and if top or bottom control, draw control label"""
1878
        xpos, ypos = xy
×
1879
        box = glob_data["patches_mod"].Circle(
×
1880
            xy=(xpos, ypos),
1881
            radius=WID * 0.15,
1882
            fc=fc,
1883
            ec=ec,
1884
            linewidth=self._lwidth15,
1885
            zorder=PORDER_GATE,
1886
        )
1887
        self._ax.add_patch(box)
×
1888

1889
        # adjust label height according to number of lines of text
1890
        label_padding = 0.7
×
1891
        if text is not None:
×
1892
            text_lines = text.count("\n")
×
1893
            if not text.endswith("(cal)\n"):
×
1894
                for _ in range(text_lines):
×
1895
                    label_padding += 0.3
×
1896

1897
        if text_top is None:
×
1898
            return
×
1899

1900
        # display the control label at the top or bottom if there is one
1901
        ctrl_ypos = ypos + label_padding * HIG if text_top else ypos - 0.3 * HIG
×
1902
        self._ax.text(
×
1903
            xpos,
1904
            ctrl_ypos,
1905
            text,
1906
            ha="center",
1907
            va="top",
1908
            fontsize=self._style["sfs"],
1909
            color=tc,
1910
            clip_on=True,
1911
            zorder=PORDER_TEXT,
1912
        )
1913

1914
    def _x_tgt_qubit(self, xy, glob_data, ec=None, ac=None):
1✔
1915
        """Draw the cnot target symbol"""
1916
        linewidth = self._lwidth2
×
1917
        xpos, ypos = xy
×
1918
        box = glob_data["patches_mod"].Circle(
×
1919
            xy=(xpos, ypos),
1920
            radius=HIG * 0.35,
1921
            fc=ec,
1922
            ec=ec,
1923
            linewidth=linewidth,
1924
            zorder=PORDER_GATE,
1925
        )
1926
        self._ax.add_patch(box)
×
1927

1928
        # add '+' symbol
1929
        self._ax.plot(
×
1930
            [xpos, xpos],
1931
            [ypos - 0.2 * HIG, ypos + 0.2 * HIG],
1932
            color=ac,
1933
            linewidth=linewidth,
1934
            zorder=PORDER_GATE_PLUS,
1935
        )
1936
        self._ax.plot(
×
1937
            [xpos - 0.2 * HIG, xpos + 0.2 * HIG],
1938
            [ypos, ypos],
1939
            color=ac,
1940
            linewidth=linewidth,
1941
            zorder=PORDER_GATE_PLUS,
1942
        )
1943

1944
    def _symmetric_gate(self, node, node_data, base_type, glob_data):
1✔
1945
        """Draw symmetric gates for cz, cu1, cp, and rzz"""
1946
        op = node.op
×
1947
        xy = node_data[node].q_xy
×
1948
        qubit_b = min(xy, key=lambda xy: xy[1])
×
1949
        qubit_t = max(xy, key=lambda xy: xy[1])
×
1950
        base_type = getattr(op, "base_gate", None)
×
1951
        ec = node_data[node].ec
×
1952
        tc = node_data[node].tc
×
1953
        lc = node_data[node].lc
×
1954

1955
        # cz and mcz gates
1956
        if not isinstance(op, ZGate) and isinstance(base_type, ZGate):
×
1957
            num_ctrl_qubits = op.num_ctrl_qubits
×
1958
            self._ctrl_qubit(xy[-1], glob_data, fc=ec, ec=ec, tc=tc)
×
1959
            self._line(qubit_b, qubit_t, lc=lc, zorder=PORDER_LINE_PLUS)
×
1960

1961
        # cu1, cp, rzz, and controlled rzz gates (sidetext gates)
1962
        elif isinstance(op, RZZGate) or isinstance(base_type, (U1Gate, PhaseGate, RZZGate)):
×
1963
            num_ctrl_qubits = 0 if isinstance(op, RZZGate) else op.num_ctrl_qubits
×
1964
            gate_text = "P" if isinstance(base_type, PhaseGate) else node_data[node].gate_text
×
1965

1966
            self._ctrl_qubit(xy[num_ctrl_qubits], glob_data, fc=ec, ec=ec, tc=tc)
×
1967
            if not isinstance(base_type, (U1Gate, PhaseGate)):
×
1968
                self._ctrl_qubit(xy[num_ctrl_qubits + 1], glob_data, fc=ec, ec=ec, tc=tc)
×
1969

1970
            self._sidetext(
×
1971
                node,
1972
                node_data,
1973
                qubit_b,
1974
                tc=tc,
1975
                text=f"{gate_text} ({node_data[node].param_text})",
1976
            )
1977
            self._line(qubit_b, qubit_t, lc=lc)
×
1978

1979
    def _swap(self, xy, color=None):
1✔
1980
        """Draw a Swap gate"""
1981
        self._swap_cross(xy[0], color=color)
×
1982
        self._swap_cross(xy[1], color=color)
×
1983
        self._line(xy[0], xy[1], lc=color)
×
1984

1985
    def _swap_cross(self, xy, color=None):
1✔
1986
        """Draw the Swap cross symbol"""
1987
        xpos, ypos = xy
×
1988

1989
        self._ax.plot(
×
1990
            [xpos - 0.20 * WID, xpos + 0.20 * WID],
1991
            [ypos - 0.20 * WID, ypos + 0.20 * WID],
1992
            color=color,
1993
            linewidth=self._lwidth2,
1994
            zorder=PORDER_LINE_PLUS,
1995
        )
1996
        self._ax.plot(
×
1997
            [xpos - 0.20 * WID, xpos + 0.20 * WID],
1998
            [ypos + 0.20 * WID, ypos - 0.20 * WID],
1999
            color=color,
2000
            linewidth=self._lwidth2,
2001
            zorder=PORDER_LINE_PLUS,
2002
        )
2003

2004
    def _sidetext(self, node, node_data, xy, tc=None, text=""):
1✔
2005
        """Draw the sidetext for symmetric gates"""
2006
        xpos, ypos = xy
×
2007

2008
        # 0.11 = the initial gap, add 1/2 text width to place on the right
2009
        xp = xpos + 0.11 + node_data[node].width / 2
×
2010
        self._ax.text(
×
2011
            xp,
2012
            ypos + HIG,
2013
            text,
2014
            ha="center",
2015
            va="top",
2016
            fontsize=self._style["sfs"],
2017
            color=tc,
2018
            clip_on=True,
2019
            zorder=PORDER_TEXT,
2020
        )
2021

2022
    def _line(self, xy0, xy1, lc=None, ls=None, zorder=PORDER_LINE):
1✔
2023
        """Draw a line from xy0 to xy1"""
2024
        x0, y0 = xy0
1✔
2025
        x1, y1 = xy1
1✔
2026
        linecolor = self._style["lc"] if lc is None else lc
1✔
2027
        linestyle = "solid" if ls is None else ls
1✔
2028

2029
        if linestyle == "doublet":
1✔
2030
            theta = np.arctan2(np.abs(x1 - x0), np.abs(y1 - y0))
1✔
2031
            dx = 0.05 * WID * np.cos(theta)
1✔
2032
            dy = 0.05 * WID * np.sin(theta)
1✔
2033
            self._ax.plot(
1✔
2034
                [x0 + dx, x1 + dx],
2035
                [y0 + dy, y1 + dy],
2036
                color=linecolor,
2037
                linewidth=self._lwidth2,
2038
                linestyle="solid",
2039
                zorder=zorder,
2040
            )
2041
            self._ax.plot(
1✔
2042
                [x0 - dx, x1 - dx],
2043
                [y0 - dy, y1 - dy],
2044
                color=linecolor,
2045
                linewidth=self._lwidth2,
2046
                linestyle="solid",
2047
                zorder=zorder,
2048
            )
2049
        else:
2050
            self._ax.plot(
1✔
2051
                [x0, x1],
2052
                [y0, y1],
2053
                color=linecolor,
2054
                linewidth=self._lwidth2,
2055
                linestyle=linestyle,
2056
                zorder=zorder,
2057
            )
2058

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

2062
        # Check folding
2063
        fold = self._fold if self._fold > 0 else INFINITE_FOLD
1✔
2064
        h_pos = x_index % fold + 1
1✔
2065

2066
        # Don't fold flow_ops here, only gates inside the flow_op
2067
        if not flow_op and h_pos + (gate_width - 1) > fold:
1✔
2068
            x_index += fold - (h_pos - 1)
×
2069
        x_pos = x_index % fold + glob_data["x_offset"] + 0.04
1✔
2070
        if not flow_op:
1✔
2071
            x_pos += 0.5 * gate_width
1✔
2072
        else:
2073
            x_pos += 0.25
×
2074
        y_pos = y_index - (x_index // fold) * (glob_data["n_lines"] + 1)
1✔
2075

2076
        # x_index could have been updated, so need to store
2077
        glob_data["next_x_index"] = x_index
1✔
2078
        return x_pos, y_pos
1✔
2079

2080

2081
class NodeData:
1✔
2082
    """Class containing drawing data on a per node basis"""
2083

2084
    def __init__(self):
1✔
2085
        # Node data for positioning
2086
        self.width = 0.0
1✔
2087
        self.x_index = 0
1✔
2088
        self.q_xy = []
1✔
2089
        self.c_xy = []
1✔
2090

2091
        # Node data for text
2092
        self.gate_text = ""
1✔
2093
        self.raw_gate_text = ""
1✔
2094
        self.ctrl_text = ""
1✔
2095
        self.param_text = ""
1✔
2096

2097
        # Node data for color
2098
        self.fc = self.ec = self.lc = self.sc = self.gt = self.tc = 0
1✔
2099

2100
        # Special values stored for ControlFlowOps
2101
        self.nest_depth = 0
1✔
2102
        self.expr_width = 0.0
1✔
2103
        self.expr_text = ""
1✔
2104
        self.inside_flow = False
1✔
2105
        self.indexset = ()  # List of indices used for ForLoopOp
1✔
2106
        self.jump_values = []  # List of jump values used for SwitchCaseOp
1✔
2107
        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