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

Qiskit / qiskit / 15395797635

02 Jun 2025 03:06PM UTC coverage: 87.816% (-0.5%) from 88.333%
15395797635

Pull #14379

github

web-flow
Merge 1047435ea into 308df7ac2
Pull Request #14379: Explicitly specify that `Target` cannot be modified by indexing.

80424 of 91582 relevant lines covered (87.82%)

359886.16 hits per line

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

49.02
/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 http://www.apache.org/licenses/LICENSE-2.0.
8
#
9
# Any modifications or derivative works of this code must retain this
10
# copyright notice, and modified files need to carry a notice indicating
11
# that they have been altered from the originals.
12

13
# pylint: disable=invalid-name,inconsistent-return-statements
14

15
"""mpl circuit visualization backend."""
16

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

22
import numpy as np
1✔
23

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

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

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

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

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

87
INFINITE_FOLD = 10000000
1✔
88

89

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

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

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

120
        self._style = style
1✔
121

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

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

136
        self._ax = ax
1✔
137

138
        self._initial_state = initial_state
1✔
139
        self._global_phase = self._circuit.global_phase
1✔
140
        self._expr_len = expr_len
1✔
141
        self._cregbundle = cregbundle
1✔
142

143
        self._lwidth1 = 1.0
1✔
144
        self._lwidth15 = 1.5
1✔
145
        self._lwidth2 = 2.0
1✔
146
        self._lwidth3 = 3.0
1✔
147
        self._lwidth4 = 4.0
1✔
148

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

152
        # Set if gate is inside a flow gate
153
        self._flow_parent = None
1✔
154
        self._flow_wire_map = {}
1✔
155

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

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

259
        # Import matplotlib and load all the figure, window, and style info
260
        from matplotlib import patches
1✔
261
        from matplotlib import pyplot as plt
1✔
262

263
        # glob_data contains global values used throughout, "n_lines", "x_offset", "next_x_index",
264
        # "patches_mod", "subfont_factor"
265
        glob_data = {}
1✔
266

267
        glob_data["patches_mod"] = patches
1✔
268
        plt_mod = plt
1✔
269

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

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

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

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

299
        # load the wire map
300
        wire_map = get_wire_map(self._circuit, self._qubits + self._clbits, self._cregbundle)
1✔
301

302
        # node_data per node filled with class NodeData attributes
303
        node_data = {}
1✔
304

305
        # dicts for the names and locations of register/bit labels
306
        qubits_dict = {}
1✔
307
        clbits_dict = {}
1✔
308

309
        # load the _qubit_dict and _clbit_dict with register info
310
        self._set_bit_reg_info(wire_map, qubits_dict, clbits_dict, glob_data)
1✔
311

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

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

322
        # The window size limits are computed, followed by one of the four possible ways
323
        # of scaling the drawing.
324

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

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

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

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

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

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

364
        # otherwise, display default size
365
        else:
366
            mpl_figure.set_size_inches(base_fig_w, base_fig_h)
1✔
367

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

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

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

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

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

428
                base_type = getattr(op, "base_gate", None)
1✔
429
                gate_text, ctrl_text, raw_gate_text = get_gate_ctrl_text(
1✔
430
                    op, "mpl", style=self._style
431
                )
432
                node_data[node].gate_text = gate_text
1✔
433
                node_data[node].ctrl_text = ctrl_text
1✔
434
                node_data[node].raw_gate_text = raw_gate_text
1✔
435
                node_data[node].param_text = ""
1✔
436

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

446
                if isinstance(op, SwapGate) or isinstance(base_type, SwapGate):
1✔
447
                    continue
×
448

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

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

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

491
                    if (isinstance(op, SwitchCaseOp) and isinstance(op.target, expr.Expr)) or (
×
492
                        getattr(op, "condition", None) and isinstance(op.condition, expr.Expr)
493
                    ):
494

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

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

535
                        expr_width = self._get_text_width(
×
536
                            node_data[node].expr_text, glob_data, fontsize=self._style["sfs"]
537
                        )
538
                        node_data[node].expr_width = int(expr_width)
×
539

540
                    # Get the list of circuits to iterate over from the blocks
541
                    circuit_list = list(node.op.blocks)
×
542

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

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

556
                    # Now process the circuits inside the ControlFlowOps
557
                    for circ_num, circuit in enumerate(circuit_list):
×
558
                        # Only add expr_width for if, while, and switch
559
                        raw_gate_width = expr_width if circ_num == 0 else 0.0
×
560

561
                        # Depth of nested ControlFlowOp used for color of box
562
                        if self._flow_parent is not None:
×
563
                            node_data[node].nest_depth = node_data[self._flow_parent].nest_depth + 1
×
564

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

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

598
                        # flow_parent is the parent of the new class instance
599
                        flow_drawer._flow_parent = node
×
600
                        flow_drawer._flow_wire_map = flow_wire_map
×
601
                        self._flow_drawers[node].append(flow_drawer)
×
602

603
                        # Recursively call _get_layer_widths for the circuit inside the ControlFlowOp
604
                        flow_widths = flow_drawer._get_layer_widths(
×
605
                            node_data, flow_wire_map, outer_circuit, glob_data
606
                        )
607
                        layer_widths.update(flow_widths)
×
608

609
                        for flow_layer in flow_nodes:
×
610
                            for flow_node in flow_layer:
×
611
                                node_data[flow_node].circ_num = circ_num
×
612

613
                        # Add up the width values of the same flow_parent that are not -1
614
                        # to get the raw_gate_width
615
                        for width, layer_num, flow_parent in flow_widths.values():
×
616
                            if layer_num != -1 and flow_parent == flow_drawer._flow_parent:
×
617
                                raw_gate_width += width
×
618

619
                        # Need extra incr of 1.0 for else and case boxes
620
                        gate_width += raw_gate_width + (1.0 if circ_num > 0 else 0.0)
×
621

622
                        # Minor adjustment so else and case section gates align with indexes
623
                        if circ_num > 0:
×
624
                            raw_gate_width += 0.045
×
625

626
                        # If expr_width has a value, remove the decimal portion from raw_gate_widthl
627
                        if not isinstance(op, ForLoopOp) and circ_num == 0:
×
628
                            node_data[node].width.append(raw_gate_width - (expr_width % 1))
×
629
                        else:
630
                            node_data[node].width.append(raw_gate_width)
×
631

632
                # Otherwise, standard gate or multiqubit gate
633
                else:
634
                    raw_gate_width = self._get_text_width(
1✔
635
                        gate_text, glob_data, fontsize=self._style["fs"]
636
                    )
637
                    gate_width = raw_gate_width + 0.10
1✔
638
                    # add .21 for the qubit numbers on the left of the multibit gates
639
                    if len(node.qargs) - num_ctrl_qubits > 1:
1✔
640
                        gate_width += 0.21
×
641

642
                box_width = max(gate_width, ctrl_width, param_width, WID)
1✔
643
                if box_width > widest_box:
1✔
644
                    widest_box = box_width
1✔
645
                if not isinstance(node.op, ControlFlowOp):
1✔
646
                    node_data[node].width = max(raw_gate_width, raw_param_width)
1✔
647
            for node in layer:
1✔
648
                layer_widths[node][0] = int(widest_box) + 1
1✔
649

650
        return layer_widths
1✔
651

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

655
        longest_wire_label_width = 0
1✔
656
        glob_data["n_lines"] = 0
1✔
657
        initial_qbit = r" $|0\rangle$" if self._initial_state else ""
1✔
658
        initial_cbit = " 0" if self._initial_state else ""
1✔
659

660
        idx = 0
1✔
661
        pos = y_off = -len(self._qubits) + 1
1✔
662
        for ii, wire in enumerate(wire_map):
1✔
663
            # if it's a creg, register is the key and just load the index
664
            if isinstance(wire, ClassicalRegister):
1✔
665
                # If wire came from ControlFlowOp and not in clbits, don't draw it
666
                if wire[0] not in self._clbits:
×
667
                    continue
×
668
                register = wire
×
669
                index = wire_map[wire]
×
670

671
            # otherwise, get the register from find_bit and use bit_index if
672
            # it's a bit, or the index of the bit in the register if it's a reg
673
            else:
674
                # If wire came from ControlFlowOp and not in qubits or clbits, don't draw it
675
                if wire not in self._qubits + self._clbits:
1✔
676
                    continue
×
677
                register, bit_index, reg_index = get_bit_reg_index(self._circuit, wire)
1✔
678
                index = bit_index if register is None else reg_index
1✔
679

680
            wire_label = get_wire_label(
1✔
681
                "mpl", register, index, layout=self._layout, cregbundle=self._cregbundle
682
            )
683
            initial_bit = initial_qbit if isinstance(wire, Qubit) else initial_cbit
1✔
684

685
            # for cregs with cregbundle on, don't use math formatting, which means
686
            # no italics
687
            if isinstance(wire, Qubit) or register is None or not self._cregbundle:
1✔
688
                wire_label = "$" + wire_label + "$"
1✔
689
            wire_label += initial_bit
1✔
690

691
            reg_size = (
1✔
692
                0 if register is None or isinstance(wire, ClassicalRegister) else register.size
693
            )
694
            reg_remove_under = 0 if reg_size < 2 else 1
1✔
695
            text_width = (
1✔
696
                self._get_text_width(
697
                    wire_label, glob_data, self._style["fs"], reg_remove_under=reg_remove_under
698
                )
699
                * 1.15
700
            )
701
            if text_width > longest_wire_label_width:
1✔
702
                longest_wire_label_width = text_width
1✔
703

704
            if isinstance(wire, Qubit):
1✔
705
                pos = -ii
1✔
706
                qubits_dict[ii] = {
1✔
707
                    "y": pos,
708
                    "wire_label": wire_label,
709
                }
710
                glob_data["n_lines"] += 1
1✔
711
            else:
712
                if (
1✔
713
                    not self._cregbundle
714
                    or register is None
715
                    or (self._cregbundle and isinstance(wire, ClassicalRegister))
716
                ):
717
                    glob_data["n_lines"] += 1
1✔
718
                    idx += 1
1✔
719

720
                pos = y_off - idx
1✔
721
                clbits_dict[ii] = {
1✔
722
                    "y": pos,
723
                    "wire_label": wire_label,
724
                    "register": register,
725
                }
726
        glob_data["x_offset"] = -1.2 + longest_wire_label_width
1✔
727

728
    def _get_coords(
1✔
729
        self,
730
        node_data,
731
        wire_map,
732
        outer_circuit,
733
        layer_widths,
734
        qubits_dict,
735
        clbits_dict,
736
        glob_data,
737
        flow_parent=None,
738
    ):
739
        """Load all the coordinate info needed to place the gates on the drawing."""
740

741
        prev_x_index = -1
1✔
742
        for layer in self._nodes:
1✔
743
            curr_x_index = prev_x_index + 1
1✔
744
            l_width = []
1✔
745
            for node in layer:
1✔
746
                # For gates inside a flow op set the x_index and if it's an else or case,
747
                # increment by if/switch width. If more cases increment by width of previous cases.
748
                if flow_parent is not None:
1✔
749
                    node_data[node].inside_flow = True
×
750
                    node_data[node].x_index = node_data[flow_parent].x_index + curr_x_index + 1
×
751
                    # If an else or case
752
                    if node_data[node].circ_num > 0:
×
753
                        for width in node_data[flow_parent].width[: node_data[node].circ_num]:
×
754
                            node_data[node].x_index += int(width) + 1
×
755
                        x_index = node_data[node].x_index
×
756
                    # Add expr_width to if, while, or switch if expr used
757
                    else:
758
                        x_index = node_data[node].x_index + node_data[flow_parent].expr_width
×
759
                else:
760
                    node_data[node].inside_flow = False
1✔
761
                    x_index = curr_x_index
1✔
762

763
                # get qubit indexes
764
                q_indxs = []
1✔
765
                for qarg in node.qargs:
1✔
766
                    if qarg in self._qubits:
1✔
767
                        q_indxs.append(wire_map[qarg])
1✔
768

769
                # get clbit indexes
770
                c_indxs = []
1✔
771
                for carg in node.cargs:
1✔
772
                    if carg in self._clbits:
1✔
773
                        if self._cregbundle:
1✔
774
                            register = get_bit_register(outer_circuit, carg)
×
775
                            if register is not None:
×
776
                                c_indxs.append(wire_map[register])
×
777
                            else:
778
                                c_indxs.append(wire_map[carg])
×
779
                        else:
780
                            c_indxs.append(wire_map[carg])
1✔
781

782
                flow_op = isinstance(node.op, ControlFlowOp)
1✔
783

784
                # qubit coordinates
785
                node_data[node].q_xy = [
1✔
786
                    self._plot_coord(
787
                        x_index,
788
                        qubits_dict[ii]["y"],
789
                        layer_widths[node][0],
790
                        glob_data,
791
                        flow_op,
792
                    )
793
                    for ii in q_indxs
794
                ]
795
                # clbit coordinates
796
                node_data[node].c_xy = [
1✔
797
                    self._plot_coord(
798
                        x_index,
799
                        clbits_dict[ii]["y"],
800
                        layer_widths[node][0],
801
                        glob_data,
802
                        flow_op,
803
                    )
804
                    for ii in c_indxs
805
                ]
806

807
                # update index based on the value from plotting
808
                if flow_parent is None:
1✔
809
                    curr_x_index = glob_data["next_x_index"]
1✔
810
                l_width.append(layer_widths[node][0])
1✔
811
                node_data[node].x_index = x_index
1✔
812

813
                # Special case of default case with no ops in it, need to push end
814
                # of switch op one extra x_index
815
                if isinstance(node.op, SwitchCaseOp):
1✔
816
                    if len(node.op.blocks[-1]) == 0:
×
817
                        curr_x_index += 1
×
818

819
            # adjust the column if there have been barriers encountered, but not plotted
820
            barrier_offset = 0
1✔
821
            if not self._plot_barriers:
1✔
822
                # only adjust if everything in the layer wasn't plotted
823
                barrier_offset = (
×
824
                    -1 if all(getattr(nd.op, "_directive", False) for nd in layer) else 0
825
                )
826
            max_lwidth = max(l_width) if l_width else 0
1✔
827
            prev_x_index = curr_x_index + max_lwidth + barrier_offset - 1
1✔
828

829
        return prev_x_index + 1
1✔
830

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

834
        from pylatexenc.latex2text import LatexNodes2Text
1✔
835

836
        if not text:
1✔
837
            return 0.0
1✔
838

839
        math_mode_match = self._mathmode_regex.search(text)
1✔
840
        num_underscores = 0
1✔
841
        num_carets = 0
1✔
842
        if math_mode_match:
1✔
843
            math_mode_text = math_mode_match.group(1)
1✔
844
            num_underscores = math_mode_text.count("_")
1✔
845
            num_carets = math_mode_text.count("^")
1✔
846
        text = LatexNodes2Text().latex_to_text(text.replace("$$", ""))
1✔
847

848
        # If there are subscripts or superscripts in mathtext string
849
        # we need to account for that spacing by manually removing
850
        # from text string for text length
851

852
        # if it's a register and there's a subscript at the end,
853
        # remove 1 underscore, otherwise don't remove any
854
        if reg_remove_under is not None:
1✔
855
            num_underscores = reg_remove_under
1✔
856
        if num_underscores:
1✔
857
            text = text.replace("_", "", num_underscores)
1✔
858
        if num_carets:
1✔
859
            text = text.replace("^", "", num_carets)
×
860

861
        # This changes hyphen to + to match width of math mode minus sign.
862
        if param:
1✔
863
            text = text.replace("-", "+")
×
864

865
        f = 0 if fontsize == self._style["fs"] else 1
1✔
866
        sum_text = 0.0
1✔
867
        for c in text:
1✔
868
            try:
1✔
869
                sum_text += self._char_list[c][f]
1✔
870
            except KeyError:
×
871
                # if non-ASCII char, use width of 'c', an average size
872
                sum_text += self._char_list["c"][f]
×
873
        if f == 1:
1✔
874
            sum_text *= glob_data["subfont_factor"]
×
875
        return sum_text
1✔
876

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

880
        for fold_num in range(num_folds + 1):
1✔
881
            # quantum registers
882
            for qubit in qubits_dict.values():
1✔
883
                qubit_label = qubit["wire_label"]
1✔
884
                y = qubit["y"] - fold_num * (glob_data["n_lines"] + 1)
1✔
885
                self._ax.text(
1✔
886
                    glob_data["x_offset"] - 0.2,
887
                    y,
888
                    qubit_label,
889
                    ha="right",
890
                    va="center",
891
                    fontsize=1.25 * self._style["fs"],
892
                    color=self._style["tc"],
893
                    clip_on=True,
894
                    zorder=PORDER_TEXT,
895
                )
896
                # draw the qubit wire
897
                self._line([glob_data["x_offset"], y], [xmax, y], zorder=PORDER_REGLINE)
1✔
898

899
            # classical registers
900
            this_clbit_dict = {}
1✔
901
            for clbit in clbits_dict.values():
1✔
902
                y = clbit["y"] - fold_num * (glob_data["n_lines"] + 1)
1✔
903
                if y not in this_clbit_dict:
1✔
904
                    this_clbit_dict[y] = {
1✔
905
                        "val": 1,
906
                        "wire_label": clbit["wire_label"],
907
                        "register": clbit["register"],
908
                    }
909
                else:
910
                    this_clbit_dict[y]["val"] += 1
×
911

912
            for y, this_clbit in this_clbit_dict.items():
1✔
913
                # cregbundle
914
                if self._cregbundle and this_clbit["register"] is not None:
1✔
915
                    self._ax.plot(
×
916
                        [glob_data["x_offset"] + 0.2, glob_data["x_offset"] + 0.3],
917
                        [y - 0.1, y + 0.1],
918
                        color=self._style["cc"],
919
                        zorder=PORDER_REGLINE,
920
                    )
921
                    self._ax.text(
×
922
                        glob_data["x_offset"] + 0.1,
923
                        y + 0.1,
924
                        str(this_clbit["register"].size),
925
                        ha="left",
926
                        va="bottom",
927
                        fontsize=0.8 * self._style["fs"],
928
                        color=self._style["tc"],
929
                        clip_on=True,
930
                        zorder=PORDER_TEXT,
931
                    )
932
                self._ax.text(
1✔
933
                    glob_data["x_offset"] - 0.2,
934
                    y,
935
                    this_clbit["wire_label"],
936
                    ha="right",
937
                    va="center",
938
                    fontsize=1.25 * self._style["fs"],
939
                    color=self._style["tc"],
940
                    clip_on=True,
941
                    zorder=PORDER_TEXT,
942
                )
943
                # draw the clbit wire
944
                self._line(
1✔
945
                    [glob_data["x_offset"], y],
946
                    [xmax, y],
947
                    lc=self._style["cc"],
948
                    ls=self._style["cline"],
949
                    zorder=PORDER_REGLINE,
950
                )
951

952
            # lf vertical line at either end
953
            feedline_r = num_folds > 0 and num_folds > fold_num
1✔
954
            feedline_l = fold_num > 0
1✔
955
            if feedline_l or feedline_r:
1✔
956
                xpos_l = glob_data["x_offset"] - 0.01
×
957
                xpos_r = self._fold + glob_data["x_offset"] + 0.1
×
958
                ypos1 = -fold_num * (glob_data["n_lines"] + 1)
×
959
                ypos2 = -(fold_num + 1) * (glob_data["n_lines"]) - fold_num + 1
×
960
                if feedline_l:
×
961
                    self._ax.plot(
×
962
                        [xpos_l, xpos_l],
963
                        [ypos1, ypos2],
964
                        color=self._style["lc"],
965
                        linewidth=self._lwidth15,
966
                        zorder=PORDER_REGLINE,
967
                    )
968
                if feedline_r:
×
969
                    self._ax.plot(
×
970
                        [xpos_r, xpos_r],
971
                        [ypos1, ypos2],
972
                        color=self._style["lc"],
973
                        linewidth=self._lwidth15,
974
                        zorder=PORDER_REGLINE,
975
                    )
976
            # Mask off any lines or boxes in the bit label area to clean up
977
            # from folding for ControlFlow and other wrapping gates
978
            box = glob_data["patches_mod"].Rectangle(
1✔
979
                xy=(glob_data["x_offset"] - 0.1, -fold_num * (glob_data["n_lines"] + 1) + 0.5),
980
                width=-25.0,
981
                height=-(fold_num + 1) * (glob_data["n_lines"] + 1),
982
                fc=self._style["bg"],
983
                ec=self._style["bg"],
984
                linewidth=self._lwidth15,
985
                zorder=PORDER_MASK,
986
            )
987
            self._ax.add_patch(box)
1✔
988

989
        # draw index number
990
        if self._style["index"]:
1✔
991
            for layer_num in range(max_x_index):
×
992
                if self._fold > 0:
×
993
                    x_coord = layer_num % self._fold + glob_data["x_offset"] + 0.53
×
994
                    y_coord = -(layer_num // self._fold) * (glob_data["n_lines"] + 1) + 0.65
×
995
                else:
996
                    x_coord = layer_num + glob_data["x_offset"] + 0.53
×
997
                    y_coord = 0.65
×
998
                self._ax.text(
×
999
                    x_coord,
1000
                    y_coord,
1001
                    str(layer_num + 1),
1002
                    ha="center",
1003
                    va="center",
1004
                    fontsize=self._style["sfs"],
1005
                    color=self._style["tc"],
1006
                    clip_on=True,
1007
                    zorder=PORDER_TEXT,
1008
                )
1009

1010
    def _add_nodes_and_coords(
1✔
1011
        self,
1012
        nodes,
1013
        node_data,
1014
        wire_map,
1015
        outer_circuit,
1016
        layer_widths,
1017
        qubits_dict,
1018
        clbits_dict,
1019
        glob_data,
1020
    ):
1021
        """Add the nodes from ControlFlowOps and their coordinates to the main circuit"""
1022
        for flow_drawers in self._flow_drawers.values():
1✔
1023
            for flow_drawer in flow_drawers:
×
1024
                nodes += flow_drawer._nodes
×
1025
                flow_drawer._get_coords(
×
1026
                    node_data,
1027
                    flow_drawer._flow_wire_map,
1028
                    outer_circuit,
1029
                    layer_widths,
1030
                    qubits_dict,
1031
                    clbits_dict,
1032
                    glob_data,
1033
                    flow_parent=flow_drawer._flow_parent,
1034
                )
1035
                # Recurse for ControlFlowOps inside the flow_drawer
1036
                flow_drawer._add_nodes_and_coords(
×
1037
                    nodes,
1038
                    node_data,
1039
                    wire_map,
1040
                    outer_circuit,
1041
                    layer_widths,
1042
                    qubits_dict,
1043
                    clbits_dict,
1044
                    glob_data,
1045
                )
1046

1047
    def _draw_ops(
1✔
1048
        self,
1049
        nodes,
1050
        node_data,
1051
        wire_map,
1052
        outer_circuit,
1053
        layer_widths,
1054
        qubits_dict,
1055
        clbits_dict,
1056
        glob_data,
1057
        verbose=False,
1058
    ):
1059
        """Draw the gates in the circuit"""
1060

1061
        # Add the nodes from all the ControlFlowOps and their coordinates to the main nodes
1062
        self._add_nodes_and_coords(
1✔
1063
            nodes,
1064
            node_data,
1065
            wire_map,
1066
            outer_circuit,
1067
            layer_widths,
1068
            qubits_dict,
1069
            clbits_dict,
1070
            glob_data,
1071
        )
1072
        prev_x_index = -1
1✔
1073
        for layer in nodes:
1✔
1074
            l_width = []
1✔
1075
            curr_x_index = prev_x_index + 1
1✔
1076

1077
            # draw the gates in this layer
1078
            for node in layer:
1✔
1079
                op = node.op
1✔
1080

1081
                self._get_colors(node, node_data)
1✔
1082

1083
                if verbose:
1✔
1084
                    print(op)  # pylint: disable=bad-builtin
×
1085

1086
                # add conditional
1087
                if getattr(op, "condition", None) or isinstance(op, SwitchCaseOp):
1✔
1088
                    cond_xy = [
×
1089
                        self._plot_coord(
1090
                            node_data[node].x_index,
1091
                            clbits_dict[ii]["y"],
1092
                            layer_widths[node][0],
1093
                            glob_data,
1094
                            isinstance(op, ControlFlowOp),
1095
                        )
1096
                        for ii in clbits_dict
1097
                    ]
1098
                    self._condition(node, node_data, wire_map, outer_circuit, cond_xy, glob_data)
×
1099

1100
                # AnnotatedOperation with ControlModifier
1101
                mod_control = None
1✔
1102
                if getattr(op, "modifiers", None):
1✔
1103
                    canonical_modifiers = _canonicalize_modifiers(op.modifiers)
×
1104
                    for modifier in canonical_modifiers:
×
1105
                        if isinstance(modifier, ControlModifier):
×
1106
                            mod_control = modifier
×
1107
                            break
×
1108

1109
                # draw measure
1110
                if isinstance(op, Measure):
1✔
1111
                    self._measure(node, node_data, outer_circuit, glob_data)
×
1112

1113
                # draw barriers, snapshots, etc.
1114
                elif getattr(op, "_directive", False):
1✔
1115
                    if self._plot_barriers:
×
1116
                        self._barrier(node, node_data, glob_data)
×
1117

1118
                # draw the box for control flow circuits
1119
                elif isinstance(op, ControlFlowOp):
1✔
1120
                    self._flow_op_gate(node, node_data, glob_data)
×
1121

1122
                # draw single qubit gates
1123
                elif len(node_data[node].q_xy) == 1 and not node.cargs:
1✔
1124
                    self._gate(node, node_data, glob_data)
1✔
1125

1126
                # draw controlled gates
1127
                elif isinstance(op, ControlledGate) or mod_control:
1✔
1128
                    self._control_gate(node, node_data, glob_data, mod_control)
×
1129

1130
                # draw multi-qubit gate as final default
1131
                else:
1132
                    self._multiqubit_gate(node, node_data, glob_data)
1✔
1133

1134
                # Determine the max width of the circuit only at the top level
1135
                if not node_data[node].inside_flow:
1✔
1136
                    l_width.append(layer_widths[node][0])
1✔
1137

1138
            # adjust the column if there have been barriers encountered, but not plotted
1139
            barrier_offset = 0
1✔
1140
            if not self._plot_barriers:
1✔
1141
                # only adjust if everything in the layer wasn't plotted
1142
                barrier_offset = (
×
1143
                    -1 if all(getattr(nd.op, "_directive", False) for nd in layer) else 0
1144
                )
1145
            prev_x_index = curr_x_index + (max(l_width) if l_width else 0) + barrier_offset - 1
1✔
1146

1147
    def _get_colors(self, node, node_data):
1✔
1148
        """Get all the colors needed for drawing the circuit"""
1149

1150
        op = node.op
1✔
1151
        base_name = getattr(getattr(op, "base_gate", None), "name", None)
1✔
1152
        color = None
1✔
1153
        if node_data[node].raw_gate_text in self._style["dispcol"]:
1✔
1154
            color = self._style["dispcol"][node_data[node].raw_gate_text]
1✔
1155
        elif op.name in self._style["dispcol"]:
1✔
1156
            color = self._style["dispcol"][op.name]
×
1157
        if color is not None:
1✔
1158
            # Backward compatibility for style dict using 'displaycolor' with
1159
            # gate color and no text color, so test for str first
1160
            if isinstance(color, str):
1✔
1161
                fc = color
×
1162
                gt = self._style["gt"]
×
1163
            else:
1164
                fc = color[0]
1✔
1165
                gt = color[1]
1✔
1166
        # Treat special case of classical gates in iqx style by making all
1167
        # controlled gates of x, dcx, and swap the classical gate color
1168
        elif self._style["name"] in ["iqp", "iqx", "iqp-dark", "iqx-dark"] and base_name in [
1✔
1169
            "x",
1170
            "dcx",
1171
            "swap",
1172
        ]:
1173
            color = self._style["dispcol"][base_name]
×
1174
            if isinstance(color, str):
×
1175
                fc = color
×
1176
                gt = self._style["gt"]
×
1177
            else:
1178
                fc = color[0]
×
1179
                gt = color[1]
×
1180
        else:
1181
            fc = self._style["gc"]
1✔
1182
            gt = self._style["gt"]
1✔
1183

1184
        if self._style["name"] == "bw":
1✔
1185
            ec = self._style["ec"]
×
1186
            lc = self._style["lc"]
×
1187
        else:
1188
            ec = fc
1✔
1189
            lc = fc
1✔
1190
        # Subtext needs to be same color as gate text
1191
        sc = gt
1✔
1192
        node_data[node].fc = fc
1✔
1193
        node_data[node].ec = ec
1✔
1194
        node_data[node].gt = gt
1✔
1195
        node_data[node].tc = self._style["tc"]
1✔
1196
        node_data[node].sc = sc
1✔
1197
        node_data[node].lc = lc
1✔
1198

1199
    def _condition(self, node, node_data, wire_map, outer_circuit, cond_xy, glob_data):
1✔
1200
        """Add a conditional to a gate"""
1201

1202
        # For SwitchCaseOp convert the target to a fully closed Clbit or register
1203
        # in condition format
1204
        if isinstance(node.op, SwitchCaseOp):
×
1205
            if isinstance(node.op.target, expr.Expr):
×
1206
                condition = node.op.target
×
1207
            elif isinstance(node.op.target, Clbit):
×
1208
                condition = (node.op.target, 1)
×
1209
            else:
1210
                condition = (node.op.target, 2 ** (node.op.target.size) - 1)
×
1211
        else:
1212
            condition = node.op.condition
×
1213

1214
        override_fc = False
×
1215
        first_clbit = len(self._qubits)
×
1216
        cond_pos = []
×
1217

1218
        if isinstance(condition, expr.Expr):
×
1219
            # If fixing this, please update the docstrings of `QuantumCircuit.draw` and
1220
            # `visualization.circuit_drawer` to remove warnings.
1221

1222
            condition_bits = condition_resources(condition).clbits
×
1223
            label = "[expr]"
×
1224
            override_fc = True
×
1225
            registers = collections.defaultdict(list)
×
1226
            for bit in condition_bits:
×
1227
                registers[get_bit_register(outer_circuit, bit)].append(bit)
×
1228
            # Registerless bits don't care whether cregbundle is set.
1229
            cond_pos.extend(cond_xy[wire_map[bit] - first_clbit] for bit in registers.pop(None, ()))
×
1230
            if self._cregbundle:
×
1231
                cond_pos.extend(cond_xy[wire_map[register] - first_clbit] for register in registers)
×
1232
            else:
1233
                cond_pos.extend(
×
1234
                    cond_xy[wire_map[bit] - first_clbit]
1235
                    for bit in itertools.chain.from_iterable(registers.values())
1236
                )
1237
            val_bits = ["1"] * len(cond_pos)
×
1238
        else:
1239
            label, val_bits = get_condition_label_val(condition, self._circuit, self._cregbundle)
×
1240
            cond_bit_reg = condition[0]
×
1241
            cond_bit_val = int(condition[1])
×
1242
            override_fc = (
×
1243
                cond_bit_val != 0
1244
                and self._cregbundle
1245
                and isinstance(cond_bit_reg, ClassicalRegister)
1246
            )
1247

1248
            # In the first case, multiple bits are indicated on the drawing. In all
1249
            # other cases, only one bit is shown.
1250
            if not self._cregbundle and isinstance(cond_bit_reg, ClassicalRegister):
×
1251
                for idx in range(cond_bit_reg.size):
×
1252
                    cond_pos.append(cond_xy[wire_map[cond_bit_reg[idx]] - first_clbit])
×
1253

1254
            # If it's a register bit and cregbundle, need to use the register to find the location
1255
            elif self._cregbundle and isinstance(cond_bit_reg, Clbit):
×
1256
                register = get_bit_register(outer_circuit, cond_bit_reg)
×
1257
                if register is not None:
×
1258
                    cond_pos.append(cond_xy[wire_map[register] - first_clbit])
×
1259
                else:
1260
                    cond_pos.append(cond_xy[wire_map[cond_bit_reg] - first_clbit])
×
1261
            else:
1262
                cond_pos.append(cond_xy[wire_map[cond_bit_reg] - first_clbit])
×
1263

1264
        xy_plot = []
×
1265
        for val_bit, xy in zip(val_bits, cond_pos):
×
1266
            fc = self._style["lc"] if override_fc or val_bit == "1" else self._style["bg"]
×
1267
            box = glob_data["patches_mod"].Circle(
×
1268
                xy=xy,
1269
                radius=WID * 0.15,
1270
                fc=fc,
1271
                ec=self._style["lc"],
1272
                linewidth=self._lwidth15,
1273
                zorder=PORDER_GATE,
1274
            )
1275
            self._ax.add_patch(box)
×
1276
            xy_plot.append(xy)
×
1277

1278
        if not xy_plot:
×
1279
            # Expression that's only on new-style `expr.Var` nodes, and doesn't need any vertical
1280
            # line drawing.
1281
            return
×
1282

1283
        qubit_b = min(node_data[node].q_xy, key=lambda xy: xy[1])
×
1284
        clbit_b = min(xy_plot, key=lambda xy: xy[1])
×
1285

1286
        # For IfElseOp, WhileLoopOp or SwitchCaseOp, place the condition line
1287
        # near the left edge of the box
1288
        if isinstance(node.op, (IfElseOp, WhileLoopOp, SwitchCaseOp)):
×
1289
            qubit_b = (qubit_b[0], qubit_b[1] - (0.5 * HIG + 0.14))
×
1290

1291
        # display the label at the bottom of the lowest conditional and draw the double line
1292
        xpos, ypos = clbit_b
×
1293
        if isinstance(node.op, Measure):
×
1294
            xpos += 0.3
×
1295
        self._ax.text(
×
1296
            xpos,
1297
            ypos - 0.3 * HIG,
1298
            label,
1299
            ha="center",
1300
            va="top",
1301
            fontsize=self._style["sfs"],
1302
            color=self._style["tc"],
1303
            clip_on=True,
1304
            zorder=PORDER_TEXT,
1305
        )
1306
        self._line(qubit_b, clbit_b, lc=self._style["cc"], ls=self._style["cline"])
×
1307

1308
    def _measure(self, node, node_data, outer_circuit, glob_data):
1✔
1309
        """Draw the measure symbol and the line to the clbit"""
1310
        qx, qy = node_data[node].q_xy[0]
×
1311
        cx, cy = node_data[node].c_xy[0]
×
1312
        register, _, reg_index = get_bit_reg_index(outer_circuit, node.cargs[0])
×
1313

1314
        # draw gate box
1315
        self._gate(node, node_data, glob_data)
×
1316

1317
        # add measure symbol
1318
        arc = glob_data["patches_mod"].Arc(
×
1319
            xy=(qx, qy - 0.15 * HIG),
1320
            width=WID * 0.7,
1321
            height=HIG * 0.7,
1322
            theta1=0,
1323
            theta2=180,
1324
            fill=False,
1325
            ec=node_data[node].gt,
1326
            linewidth=self._lwidth2,
1327
            zorder=PORDER_GATE,
1328
        )
1329
        self._ax.add_patch(arc)
×
1330
        self._ax.plot(
×
1331
            [qx, qx + 0.35 * WID],
1332
            [qy - 0.15 * HIG, qy + 0.20 * HIG],
1333
            color=node_data[node].gt,
1334
            linewidth=self._lwidth2,
1335
            zorder=PORDER_GATE,
1336
        )
1337
        # arrow
1338
        self._line(
×
1339
            node_data[node].q_xy[0],
1340
            [cx, cy + 0.35 * WID],
1341
            lc=self._style["cc"],
1342
            ls=self._style["cline"],
1343
        )
1344
        arrowhead = glob_data["patches_mod"].Polygon(
×
1345
            (
1346
                (cx - 0.20 * WID, cy + 0.35 * WID),
1347
                (cx + 0.20 * WID, cy + 0.35 * WID),
1348
                (cx, cy + 0.04),
1349
            ),
1350
            fc=self._style["cc"],
1351
            ec=None,
1352
        )
1353
        self._ax.add_artist(arrowhead)
×
1354
        # target
1355
        if self._cregbundle and register is not None:
×
1356
            self._ax.text(
×
1357
                cx + 0.25,
1358
                cy + 0.1,
1359
                str(reg_index),
1360
                ha="left",
1361
                va="bottom",
1362
                fontsize=0.8 * self._style["fs"],
1363
                color=self._style["tc"],
1364
                clip_on=True,
1365
                zorder=PORDER_TEXT,
1366
            )
1367

1368
    def _barrier(self, node, node_data, glob_data):
1✔
1369
        """Draw a barrier"""
1370
        for i, xy in enumerate(node_data[node].q_xy):
×
1371
            xpos, ypos = xy
×
1372
            # For the topmost barrier, reduce the rectangle if there's a label to allow for the text.
1373
            if i == 0 and node.op.label is not None:
×
1374
                ypos_adj = -0.35
×
1375
            else:
1376
                ypos_adj = 0.0
×
1377
            self._ax.plot(
×
1378
                [xpos, xpos],
1379
                [ypos + 0.5 + ypos_adj, ypos - 0.5],
1380
                linewidth=self._lwidth1,
1381
                linestyle="dashed",
1382
                color=self._style["lc"],
1383
                zorder=PORDER_TEXT,
1384
            )
1385
            box = glob_data["patches_mod"].Rectangle(
×
1386
                xy=(xpos - (0.3 * WID), ypos - 0.5),
1387
                width=0.6 * WID,
1388
                height=1.0 + ypos_adj,
1389
                fc=self._style["bc"],
1390
                ec=None,
1391
                alpha=0.6,
1392
                linewidth=self._lwidth15,
1393
                zorder=PORDER_BARRIER,
1394
            )
1395
            self._ax.add_patch(box)
×
1396

1397
            # display the barrier label at the top if there is one
1398
            if i == 0 and node.op.label is not None:
×
1399
                dir_ypos = ypos + 0.65 * HIG
×
1400
                self._ax.text(
×
1401
                    xpos,
1402
                    dir_ypos,
1403
                    node.op.label,
1404
                    ha="center",
1405
                    va="top",
1406
                    fontsize=self._style["fs"],
1407
                    color=node_data[node].tc,
1408
                    clip_on=True,
1409
                    zorder=PORDER_TEXT,
1410
                )
1411

1412
    def _gate(self, node, node_data, glob_data, xy=None):
1✔
1413
        """Draw a 1-qubit gate"""
1414
        if xy is None:
1✔
1415
            xy = node_data[node].q_xy[0]
1✔
1416
        xpos, ypos = xy
1✔
1417
        wid = max(node_data[node].width, WID)
1✔
1418

1419
        box = glob_data["patches_mod"].Rectangle(
1✔
1420
            xy=(xpos - 0.5 * wid, ypos - 0.5 * HIG),
1421
            width=wid,
1422
            height=HIG,
1423
            fc=node_data[node].fc,
1424
            ec=node_data[node].ec,
1425
            linewidth=self._lwidth15,
1426
            zorder=PORDER_GATE,
1427
        )
1428
        self._ax.add_patch(box)
1✔
1429

1430
        if node_data[node].gate_text:
1✔
1431
            gate_ypos = ypos
1✔
1432
            if node_data[node].param_text:
1✔
1433
                gate_ypos = ypos + 0.15 * HIG
×
1434
                self._ax.text(
×
1435
                    xpos,
1436
                    ypos - 0.3 * HIG,
1437
                    node_data[node].param_text,
1438
                    ha="center",
1439
                    va="center",
1440
                    fontsize=self._style["sfs"],
1441
                    color=node_data[node].sc,
1442
                    clip_on=True,
1443
                    zorder=PORDER_TEXT,
1444
                )
1445
            self._ax.text(
1✔
1446
                xpos,
1447
                gate_ypos,
1448
                node_data[node].gate_text,
1449
                ha="center",
1450
                va="center",
1451
                fontsize=self._style["fs"],
1452
                color=node_data[node].gt,
1453
                clip_on=True,
1454
                zorder=PORDER_TEXT,
1455
            )
1456

1457
    def _multiqubit_gate(self, node, node_data, glob_data, xy=None):
1✔
1458
        """Draw a gate covering more than one qubit"""
1459
        op = node.op
1✔
1460
        if xy is None:
1✔
1461
            xy = node_data[node].q_xy
1✔
1462

1463
        # Swap gate
1464
        if isinstance(op, SwapGate):
1✔
1465
            self._swap(xy, node_data[node].lc)
×
1466
            return
×
1467

1468
        # RZZ Gate
1469
        elif isinstance(op, RZZGate):
1✔
1470
            self._symmetric_gate(node, node_data, RZZGate, glob_data)
×
1471
            return
×
1472

1473
        c_xy = node_data[node].c_xy
1✔
1474
        xpos = min(x[0] for x in xy)
1✔
1475
        ypos = min(y[1] for y in xy)
1✔
1476
        ypos_max = max(y[1] for y in xy)
1✔
1477
        if c_xy:
1✔
1478
            cxpos = min(x[0] for x in c_xy)
1✔
1479
            cypos = min(y[1] for y in c_xy)
1✔
1480
            ypos = min(ypos, cypos)
1✔
1481

1482
        wid = max(node_data[node].width + 0.21, WID)
1✔
1483
        qubit_span = abs(ypos) - abs(ypos_max)
1✔
1484
        height = HIG + qubit_span
1✔
1485

1486
        box = glob_data["patches_mod"].Rectangle(
1✔
1487
            xy=(xpos - 0.5 * wid, ypos - 0.5 * HIG),
1488
            width=wid,
1489
            height=height,
1490
            fc=node_data[node].fc,
1491
            ec=node_data[node].ec,
1492
            linewidth=self._lwidth15,
1493
            zorder=PORDER_GATE,
1494
        )
1495
        self._ax.add_patch(box)
1✔
1496

1497
        # annotate inputs
1498
        for bit, y in enumerate([x[1] for x in xy]):
1✔
1499
            self._ax.text(
1✔
1500
                xpos + 0.07 - 0.5 * wid,
1501
                y,
1502
                str(bit),
1503
                ha="left",
1504
                va="center",
1505
                fontsize=self._style["fs"],
1506
                color=node_data[node].gt,
1507
                clip_on=True,
1508
                zorder=PORDER_TEXT,
1509
            )
1510
        if c_xy:
1✔
1511
            # annotate classical inputs
1512
            for bit, y in enumerate([x[1] for x in c_xy]):
1✔
1513
                self._ax.text(
1✔
1514
                    cxpos + 0.07 - 0.5 * wid,
1515
                    y,
1516
                    str(bit),
1517
                    ha="left",
1518
                    va="center",
1519
                    fontsize=self._style["fs"],
1520
                    color=node_data[node].gt,
1521
                    clip_on=True,
1522
                    zorder=PORDER_TEXT,
1523
                )
1524
        if node_data[node].gate_text:
1✔
1525
            gate_ypos = ypos + 0.5 * qubit_span
1✔
1526
            if node_data[node].param_text:
1✔
1527
                gate_ypos = ypos + 0.4 * height
×
1528
                self._ax.text(
×
1529
                    xpos + 0.11,
1530
                    ypos + 0.2 * height,
1531
                    node_data[node].param_text,
1532
                    ha="center",
1533
                    va="center",
1534
                    fontsize=self._style["sfs"],
1535
                    color=node_data[node].sc,
1536
                    clip_on=True,
1537
                    zorder=PORDER_TEXT,
1538
                )
1539
            self._ax.text(
1✔
1540
                xpos + 0.11,
1541
                gate_ypos,
1542
                node_data[node].gate_text,
1543
                ha="center",
1544
                va="center",
1545
                fontsize=self._style["fs"],
1546
                color=node_data[node].gt,
1547
                clip_on=True,
1548
                zorder=PORDER_TEXT,
1549
            )
1550

1551
    def _flow_op_gate(self, node, node_data, glob_data):
1✔
1552
        """Draw the box for a flow op circuit"""
1553
        xy = node_data[node].q_xy
×
1554
        xpos = min(x[0] for x in xy)
×
1555
        ypos = min(y[1] for y in xy)
×
1556
        ypos_max = max(y[1] for y in xy)
×
1557

1558
        if_width = node_data[node].width[0] + WID
×
1559
        box_width = if_width
×
1560
        # Add the else and case widths to the if_width
1561
        for ewidth in node_data[node].width[1:]:
×
1562
            if ewidth > 0.0:
×
1563
                box_width += ewidth + WID + 0.3
×
1564

1565
        qubit_span = abs(ypos) - abs(ypos_max)
×
1566
        height = HIG + qubit_span
×
1567

1568
        # Cycle through box colors based on depth.
1569
        # Default - blue, purple, green, black
1570
        colors = [
×
1571
            self._style["dispcol"]["h"][0],
1572
            self._style["dispcol"]["u"][0],
1573
            self._style["dispcol"]["x"][0],
1574
            self._style["cc"],
1575
        ]
1576
        # To fold box onto next lines, draw it repeatedly, shifting
1577
        # it left by x_shift and down by y_shift
1578
        fold_level = 0
×
1579
        end_x = xpos + box_width
×
1580

1581
        while end_x > 0.0:
×
1582
            x_shift = fold_level * self._fold
×
1583
            y_shift = fold_level * (glob_data["n_lines"] + 1)
×
1584
            end_x = xpos + box_width - x_shift if self._fold > 0 else 0.0
×
1585

1586
            if isinstance(node.op, IfElseOp):
×
1587
                flow_text = "  If"
×
1588
            elif isinstance(node.op, WhileLoopOp):
×
1589
                flow_text = " While"
×
1590
            elif isinstance(node.op, ForLoopOp):
×
1591
                flow_text = " For"
×
1592
            elif isinstance(node.op, SwitchCaseOp):
×
1593
                flow_text = "Switch"
×
1594
            elif isinstance(node.op, BoxOp):
×
1595
                flow_text = ""
×
1596
            else:
1597
                raise RuntimeError(f"unhandled control-flow op: {node.name}")
1598

1599
            # Some spacers. op_spacer moves 'Switch' back a bit for alignment,
1600
            # expr_spacer moves the expr over to line up with 'Switch' and
1601
            # empty_default_spacer makes the switch box longer if the default
1602
            # case is empty so text doesn't run past end of box.
1603
            if isinstance(node.op, SwitchCaseOp):
×
1604
                op_spacer = 0.04
×
1605
                expr_spacer = 0.0
×
1606
                empty_default_spacer = 0.3 if len(node.op.blocks[-1]) == 0 else 0.0
×
1607
            elif isinstance(node.op, BoxOp):
×
1608
                op_spacer = 0.0
×
1609
                expr_spacer = 0.0
×
1610
                empty_default_spacer = 0.0
×
1611
            else:
1612
                op_spacer = 0.08
×
1613
                expr_spacer = 0.02
×
1614
                empty_default_spacer = 0.0
×
1615

1616
            # FancyBbox allows rounded corners
1617
            box = glob_data["patches_mod"].FancyBboxPatch(
×
1618
                xy=(xpos - x_shift, ypos - 0.5 * HIG - y_shift),
1619
                width=box_width + empty_default_spacer,
1620
                height=height,
1621
                boxstyle="round, pad=0.1",
1622
                fc="none",
1623
                ec=colors[node_data[node].nest_depth % 4],
1624
                linewidth=self._lwidth3,
1625
                zorder=PORDER_FLOW,
1626
            )
1627
            self._ax.add_patch(box)
×
1628

1629
            # Indicate type of ControlFlowOp and if expression used, print below
1630
            self._ax.text(
×
1631
                xpos - x_shift - op_spacer,
1632
                ypos_max + 0.2 - y_shift,
1633
                flow_text,
1634
                ha="left",
1635
                va="center",
1636
                fontsize=self._style["fs"],
1637
                color=node_data[node].tc,
1638
                clip_on=True,
1639
                zorder=PORDER_FLOW,
1640
            )
1641
            self._ax.text(
×
1642
                xpos - x_shift + expr_spacer,
1643
                ypos_max + 0.2 - y_shift - 0.4,
1644
                node_data[node].expr_text,
1645
                ha="left",
1646
                va="center",
1647
                fontsize=self._style["sfs"],
1648
                color=node_data[node].tc,
1649
                clip_on=True,
1650
                zorder=PORDER_FLOW,
1651
            )
1652
            if isinstance(node.op, ForLoopOp):
×
1653
                idx_set = str(node_data[node].indexset)
×
1654
                # If a range was used display 'range' and grab the range value
1655
                # to be displayed below
1656
                if "range" in idx_set:
×
1657
                    idx_set = "r(" + idx_set[6:-1] + ")"
×
1658
                else:
1659
                    # If a tuple, show first 4 elements followed by '...'
1660
                    idx_set = str(node_data[node].indexset)[1:-1].split(",")[:5]
×
1661
                    if len(idx_set) > 4:
×
1662
                        idx_set[4] = "..."
×
1663
                    idx_set = f"{','.join(idx_set)}"
×
1664
                y_spacer = 0.2 if len(node.qargs) == 1 else 0.5
×
1665
                self._ax.text(
×
1666
                    xpos - x_shift - 0.04,
1667
                    ypos_max - y_spacer - y_shift,
1668
                    idx_set,
1669
                    ha="left",
1670
                    va="center",
1671
                    fontsize=self._style["sfs"],
1672
                    color=node_data[node].tc,
1673
                    clip_on=True,
1674
                    zorder=PORDER_FLOW,
1675
                )
1676
            # If there's an else or a case draw the vertical line and the name
1677
            else_case_text = "Else" if isinstance(node.op, IfElseOp) else "Case"
×
1678
            ewidth_incr = if_width
×
1679
            for circ_num, ewidth in enumerate(node_data[node].width[1:]):
×
1680
                if ewidth > 0.0:
×
1681
                    self._ax.plot(
×
1682
                        [xpos + ewidth_incr + 0.3 - x_shift, xpos + ewidth_incr + 0.3 - x_shift],
1683
                        [ypos - 0.5 * HIG - 0.08 - y_shift, ypos + height - 0.22 - y_shift],
1684
                        color=colors[node_data[node].nest_depth % 4],
1685
                        linewidth=3.0,
1686
                        linestyle="solid",
1687
                        zorder=PORDER_FLOW,
1688
                    )
1689
                    self._ax.text(
×
1690
                        xpos + ewidth_incr + 0.4 - x_shift,
1691
                        ypos_max + 0.2 - y_shift,
1692
                        else_case_text,
1693
                        ha="left",
1694
                        va="center",
1695
                        fontsize=self._style["fs"],
1696
                        color=node_data[node].tc,
1697
                        clip_on=True,
1698
                        zorder=PORDER_FLOW,
1699
                    )
1700
                    if isinstance(node.op, SwitchCaseOp):
×
1701
                        jump_val = node_data[node].jump_values[circ_num]
×
1702
                        # If only one value, e.g. (0,)
1703
                        if len(str(jump_val)) == 4:
×
1704
                            jump_text = str(jump_val)[1]
×
1705
                        elif "default" in str(jump_val):
×
1706
                            jump_text = "default"
×
1707
                        else:
1708
                            # If a tuple, show first 4 elements followed by '...'
1709
                            jump_text = str(jump_val)[1:-1].replace(" ", "").split(",")[:5]
×
1710
                            if len(jump_text) > 4:
×
1711
                                jump_text[4] = "..."
×
1712
                            jump_text = f"{', '.join(jump_text)}"
×
1713
                        y_spacer = 0.2 if len(node.qargs) == 1 else 0.5
×
1714
                        self._ax.text(
×
1715
                            xpos + ewidth_incr + 0.4 - x_shift,
1716
                            ypos_max - y_spacer - y_shift,
1717
                            jump_text,
1718
                            ha="left",
1719
                            va="center",
1720
                            fontsize=self._style["sfs"],
1721
                            color=node_data[node].tc,
1722
                            clip_on=True,
1723
                            zorder=PORDER_FLOW,
1724
                        )
1725
                ewidth_incr += ewidth + 1
×
1726

1727
            fold_level += 1
×
1728

1729
    def _control_gate(self, node, node_data, glob_data, mod_control):
1✔
1730
        """Draw a controlled gate"""
1731
        op = node.op
×
1732
        xy = node_data[node].q_xy
×
1733
        base_type = getattr(op, "base_gate", None)
×
1734
        qubit_b = min(xy, key=lambda xy: xy[1])
×
1735
        qubit_t = max(xy, key=lambda xy: xy[1])
×
1736
        num_ctrl_qubits = mod_control.num_ctrl_qubits if mod_control else op.num_ctrl_qubits
×
1737
        num_qargs = len(xy) - num_ctrl_qubits
×
1738
        ctrl_state = mod_control.ctrl_state if mod_control else op.ctrl_state
×
1739
        self._set_ctrl_bits(
×
1740
            ctrl_state,
1741
            num_ctrl_qubits,
1742
            xy,
1743
            glob_data,
1744
            ec=node_data[node].ec,
1745
            tc=node_data[node].tc,
1746
            text=node_data[node].ctrl_text,
1747
            qargs=node.qargs,
1748
        )
1749
        self._line(qubit_b, qubit_t, lc=node_data[node].lc)
×
1750

1751
        if isinstance(op, RZZGate) or isinstance(base_type, (U1Gate, PhaseGate, ZGate, RZZGate)):
×
1752
            self._symmetric_gate(node, node_data, base_type, glob_data)
×
1753

1754
        elif num_qargs == 1 and isinstance(base_type, XGate):
×
1755
            tgt_color = self._style["dispcol"]["target"]
×
1756
            tgt = tgt_color if isinstance(tgt_color, str) else tgt_color[0]
×
1757
            self._x_tgt_qubit(xy[num_ctrl_qubits], glob_data, ec=node_data[node].ec, ac=tgt)
×
1758

1759
        elif num_qargs == 1:
×
1760
            self._gate(node, node_data, glob_data, xy[num_ctrl_qubits:][0])
×
1761

1762
        elif isinstance(base_type, SwapGate):
×
1763
            self._swap(xy[num_ctrl_qubits:], node_data[node].lc)
×
1764

1765
        else:
1766
            self._multiqubit_gate(node, node_data, glob_data, xy[num_ctrl_qubits:])
×
1767

1768
    def _set_ctrl_bits(
1✔
1769
        self, ctrl_state, num_ctrl_qubits, qbit, glob_data, ec=None, tc=None, text="", qargs=None
1770
    ):
1771
        """Determine which qubits are controls and whether they are open or closed"""
1772
        # place the control label at the top or bottom of controls
1773
        if text:
×
1774
            qlist = [self._circuit.find_bit(qubit).index for qubit in qargs]
×
1775
            ctbits = qlist[:num_ctrl_qubits]
×
1776
            qubits = qlist[num_ctrl_qubits:]
×
1777
            max_ctbit = max(ctbits)
×
1778
            min_ctbit = min(ctbits)
×
1779
            top = min(qubits) > min_ctbit
×
1780

1781
        # display the control qubits as open or closed based on ctrl_state
1782
        cstate = f"{ctrl_state:b}".rjust(num_ctrl_qubits, "0")[::-1]
×
1783
        for i in range(num_ctrl_qubits):
×
1784
            fc_open_close = ec if cstate[i] == "1" else self._style["bg"]
×
1785
            text_top = None
×
1786
            if text:
×
1787
                if top and qlist[i] == min_ctbit:
×
1788
                    text_top = True
×
1789
                elif not top and qlist[i] == max_ctbit:
×
1790
                    text_top = False
×
1791
            self._ctrl_qubit(
×
1792
                qbit[i], glob_data, fc=fc_open_close, ec=ec, tc=tc, text=text, text_top=text_top
1793
            )
1794

1795
    def _ctrl_qubit(self, xy, glob_data, fc=None, ec=None, tc=None, text="", text_top=None):
1✔
1796
        """Draw a control circle and if top or bottom control, draw control label"""
1797
        xpos, ypos = xy
×
1798
        box = glob_data["patches_mod"].Circle(
×
1799
            xy=(xpos, ypos),
1800
            radius=WID * 0.15,
1801
            fc=fc,
1802
            ec=ec,
1803
            linewidth=self._lwidth15,
1804
            zorder=PORDER_GATE,
1805
        )
1806
        self._ax.add_patch(box)
×
1807

1808
        # adjust label height according to number of lines of text
1809
        label_padding = 0.7
×
1810
        if text is not None:
×
1811
            text_lines = text.count("\n")
×
1812
            if not text.endswith("(cal)\n"):
×
1813
                for _ in range(text_lines):
×
1814
                    label_padding += 0.3
×
1815

1816
        if text_top is None:
×
1817
            return
×
1818

1819
        # display the control label at the top or bottom if there is one
1820
        ctrl_ypos = ypos + label_padding * HIG if text_top else ypos - 0.3 * HIG
×
1821
        self._ax.text(
×
1822
            xpos,
1823
            ctrl_ypos,
1824
            text,
1825
            ha="center",
1826
            va="top",
1827
            fontsize=self._style["sfs"],
1828
            color=tc,
1829
            clip_on=True,
1830
            zorder=PORDER_TEXT,
1831
        )
1832

1833
    def _x_tgt_qubit(self, xy, glob_data, ec=None, ac=None):
1✔
1834
        """Draw the cnot target symbol"""
1835
        linewidth = self._lwidth2
×
1836
        xpos, ypos = xy
×
1837
        box = glob_data["patches_mod"].Circle(
×
1838
            xy=(xpos, ypos),
1839
            radius=HIG * 0.35,
1840
            fc=ec,
1841
            ec=ec,
1842
            linewidth=linewidth,
1843
            zorder=PORDER_GATE,
1844
        )
1845
        self._ax.add_patch(box)
×
1846

1847
        # add '+' symbol
1848
        self._ax.plot(
×
1849
            [xpos, xpos],
1850
            [ypos - 0.2 * HIG, ypos + 0.2 * HIG],
1851
            color=ac,
1852
            linewidth=linewidth,
1853
            zorder=PORDER_GATE_PLUS,
1854
        )
1855
        self._ax.plot(
×
1856
            [xpos - 0.2 * HIG, xpos + 0.2 * HIG],
1857
            [ypos, ypos],
1858
            color=ac,
1859
            linewidth=linewidth,
1860
            zorder=PORDER_GATE_PLUS,
1861
        )
1862

1863
    def _symmetric_gate(self, node, node_data, base_type, glob_data):
1✔
1864
        """Draw symmetric gates for cz, cu1, cp, and rzz"""
1865
        op = node.op
×
1866
        xy = node_data[node].q_xy
×
1867
        qubit_b = min(xy, key=lambda xy: xy[1])
×
1868
        qubit_t = max(xy, key=lambda xy: xy[1])
×
1869
        base_type = getattr(op, "base_gate", None)
×
1870
        ec = node_data[node].ec
×
1871
        tc = node_data[node].tc
×
1872
        lc = node_data[node].lc
×
1873

1874
        # cz and mcz gates
1875
        if not isinstance(op, ZGate) and isinstance(base_type, ZGate):
×
1876
            num_ctrl_qubits = op.num_ctrl_qubits
×
1877
            self._ctrl_qubit(xy[-1], glob_data, fc=ec, ec=ec, tc=tc)
×
1878
            self._line(qubit_b, qubit_t, lc=lc, zorder=PORDER_LINE_PLUS)
×
1879

1880
        # cu1, cp, rzz, and controlled rzz gates (sidetext gates)
1881
        elif isinstance(op, RZZGate) or isinstance(base_type, (U1Gate, PhaseGate, RZZGate)):
×
1882
            num_ctrl_qubits = 0 if isinstance(op, RZZGate) else op.num_ctrl_qubits
×
1883
            gate_text = "P" if isinstance(base_type, PhaseGate) else node_data[node].gate_text
×
1884

1885
            self._ctrl_qubit(xy[num_ctrl_qubits], glob_data, fc=ec, ec=ec, tc=tc)
×
1886
            if not isinstance(base_type, (U1Gate, PhaseGate)):
×
1887
                self._ctrl_qubit(xy[num_ctrl_qubits + 1], glob_data, fc=ec, ec=ec, tc=tc)
×
1888

1889
            self._sidetext(
×
1890
                node,
1891
                node_data,
1892
                qubit_b,
1893
                tc=tc,
1894
                text=f"{gate_text} ({node_data[node].param_text})",
1895
            )
1896
            self._line(qubit_b, qubit_t, lc=lc)
×
1897

1898
    def _swap(self, xy, color=None):
1✔
1899
        """Draw a Swap gate"""
1900
        self._swap_cross(xy[0], color=color)
×
1901
        self._swap_cross(xy[1], color=color)
×
1902
        self._line(xy[0], xy[1], lc=color)
×
1903

1904
    def _swap_cross(self, xy, color=None):
1✔
1905
        """Draw the Swap cross symbol"""
1906
        xpos, ypos = xy
×
1907

1908
        self._ax.plot(
×
1909
            [xpos - 0.20 * WID, xpos + 0.20 * WID],
1910
            [ypos - 0.20 * WID, ypos + 0.20 * WID],
1911
            color=color,
1912
            linewidth=self._lwidth2,
1913
            zorder=PORDER_LINE_PLUS,
1914
        )
1915
        self._ax.plot(
×
1916
            [xpos - 0.20 * WID, xpos + 0.20 * WID],
1917
            [ypos + 0.20 * WID, ypos - 0.20 * WID],
1918
            color=color,
1919
            linewidth=self._lwidth2,
1920
            zorder=PORDER_LINE_PLUS,
1921
        )
1922

1923
    def _sidetext(self, node, node_data, xy, tc=None, text=""):
1✔
1924
        """Draw the sidetext for symmetric gates"""
1925
        xpos, ypos = xy
×
1926

1927
        # 0.11 = the initial gap, add 1/2 text width to place on the right
1928
        xp = xpos + 0.11 + node_data[node].width / 2
×
1929
        self._ax.text(
×
1930
            xp,
1931
            ypos + HIG,
1932
            text,
1933
            ha="center",
1934
            va="top",
1935
            fontsize=self._style["sfs"],
1936
            color=tc,
1937
            clip_on=True,
1938
            zorder=PORDER_TEXT,
1939
        )
1940

1941
    def _line(self, xy0, xy1, lc=None, ls=None, zorder=PORDER_LINE):
1✔
1942
        """Draw a line from xy0 to xy1"""
1943
        x0, y0 = xy0
1✔
1944
        x1, y1 = xy1
1✔
1945
        linecolor = self._style["lc"] if lc is None else lc
1✔
1946
        linestyle = "solid" if ls is None else ls
1✔
1947

1948
        if linestyle == "doublet":
1✔
1949
            theta = np.arctan2(np.abs(x1 - x0), np.abs(y1 - y0))
1✔
1950
            dx = 0.05 * WID * np.cos(theta)
1✔
1951
            dy = 0.05 * WID * np.sin(theta)
1✔
1952
            self._ax.plot(
1✔
1953
                [x0 + dx, x1 + dx],
1954
                [y0 + dy, y1 + dy],
1955
                color=linecolor,
1956
                linewidth=self._lwidth2,
1957
                linestyle="solid",
1958
                zorder=zorder,
1959
            )
1960
            self._ax.plot(
1✔
1961
                [x0 - dx, x1 - dx],
1962
                [y0 - dy, y1 - dy],
1963
                color=linecolor,
1964
                linewidth=self._lwidth2,
1965
                linestyle="solid",
1966
                zorder=zorder,
1967
            )
1968
        else:
1969
            self._ax.plot(
1✔
1970
                [x0, x1],
1971
                [y0, y1],
1972
                color=linecolor,
1973
                linewidth=self._lwidth2,
1974
                linestyle=linestyle,
1975
                zorder=zorder,
1976
            )
1977

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

1981
        # Check folding
1982
        fold = self._fold if self._fold > 0 else INFINITE_FOLD
1✔
1983
        h_pos = x_index % fold + 1
1✔
1984

1985
        # Don't fold flow_ops here, only gates inside the flow_op
1986
        if not flow_op and h_pos + (gate_width - 1) > fold:
1✔
1987
            x_index += fold - (h_pos - 1)
×
1988
        x_pos = x_index % fold + glob_data["x_offset"] + 0.04
1✔
1989
        if not flow_op:
1✔
1990
            x_pos += 0.5 * gate_width
1✔
1991
        else:
1992
            x_pos += 0.25
×
1993
        y_pos = y_index - (x_index // fold) * (glob_data["n_lines"] + 1)
1✔
1994

1995
        # x_index could have been updated, so need to store
1996
        glob_data["next_x_index"] = x_index
1✔
1997
        return x_pos, y_pos
1✔
1998

1999

2000
class NodeData:
1✔
2001
    """Class containing drawing data on a per node basis"""
2002

2003
    def __init__(self):
1✔
2004
        # Node data for positioning
2005
        self.width = 0.0
1✔
2006
        self.x_index = 0
1✔
2007
        self.q_xy = []
1✔
2008
        self.c_xy = []
1✔
2009

2010
        # Node data for text
2011
        self.gate_text = ""
1✔
2012
        self.raw_gate_text = ""
1✔
2013
        self.ctrl_text = ""
1✔
2014
        self.param_text = ""
1✔
2015

2016
        # Node data for color
2017
        self.fc = self.ec = self.lc = self.sc = self.gt = self.tc = 0
1✔
2018

2019
        # Special values stored for ControlFlowOps
2020
        self.nest_depth = 0
1✔
2021
        self.expr_width = 0.0
1✔
2022
        self.expr_text = ""
1✔
2023
        self.inside_flow = False
1✔
2024
        self.indexset = ()  # List of indices used for ForLoopOp
1✔
2025
        self.jump_values = []  # List of jump values used for SwitchCaseOp
1✔
2026
        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