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

Qiskit / qiskit / 13442238275

20 Feb 2025 06:33PM UTC coverage: 87.994% (-0.1%) from 88.118%
13442238275

Pull #13899

github

web-flow
Merge 634e54ac0 into 83c20e998
Pull Request #13899: Support stretchy delays in `box`

1111 of 1522 new or added lines in 36 files covered. (73.0%)

199 existing lines in 16 files now uncovered.

78717 of 89457 relevant lines covered (87.99%)

348992.06 hits per line

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

48.79
/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 .qcstyle import load_style
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
    ):
113
        self._circuit = circuit
1✔
114
        self._qubits = qubits
1✔
115
        self._clbits = clbits
1✔
116
        self._nodes = nodes
1✔
117
        self._scale = 1.0 if scale is None else scale
1✔
118

119
        self._style = style
1✔
120

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

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

135
        self._ax = ax
1✔
136

137
        self._initial_state = initial_state
1✔
138
        self._global_phase = self._circuit.global_phase
1✔
139
        self._calibrations = self._circuit._calibrations_prop
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(self._style)
1✔
271

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

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

289
        # All information for the drawing is first loaded into node_data for the gates and into
290
        # qubits_dict, clbits_dict, and wire_map for the qubits, clbits, and wires,
291
        # followed by the coordinates for each gate.
292

293
        # load the wire map
294
        wire_map = get_wire_map(self._circuit, self._qubits + self._clbits, self._cregbundle)
1✔
295

296
        # node_data per node filled with class NodeData attributes
297
        node_data = {}
1✔
298

299
        # dicts for the names and locations of register/bit labels
300
        qubits_dict = {}
1✔
301
        clbits_dict = {}
1✔
302

303
        # load the _qubit_dict and _clbit_dict with register info
304
        self._set_bit_reg_info(wire_map, qubits_dict, clbits_dict, glob_data)
1✔
305

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

309
        # load the coordinates for each top level gate and compute number of folds.
310
        # coordinates for flow gates are loaded before draw_ops
311
        max_x_index = self._get_coords(
1✔
312
            node_data, wire_map, self._circuit, layer_widths, qubits_dict, clbits_dict, glob_data
313
        )
314
        num_folds = max(0, max_x_index - 1) // self._fold if self._fold > 0 else 0
1✔
315

316
        # The window size limits are computed, followed by one of the four possible ways
317
        # of scaling the drawing.
318

319
        # compute the window size
320
        if max_x_index > self._fold > 0:
1✔
321
            xmax = self._fold + glob_data["x_offset"] + 0.1
×
322
            ymax = (num_folds + 1) * (glob_data["n_lines"] + 1) - 1
×
323
        else:
324
            x_incr = 0.4 if not self._nodes else 0.9
1✔
325
            xmax = max_x_index + 1 + glob_data["x_offset"] - x_incr
1✔
326
            ymax = glob_data["n_lines"]
1✔
327

328
        xl = -self._style["margin"][0]
1✔
329
        xr = xmax + self._style["margin"][1]
1✔
330
        yb = -ymax - self._style["margin"][2] + 0.5
1✔
331
        yt = self._style["margin"][3] + 0.5
1✔
332
        self._ax.set_xlim(xl, xr)
1✔
333
        self._ax.set_ylim(yb, yt)
1✔
334

335
        # update figure size and, for backward compatibility,
336
        # need to scale by a default value equal to (self._style["fs"] * 3.01 / 72 / 0.65)
337
        base_fig_w = (xr - xl) * 0.8361111
1✔
338
        base_fig_h = (yt - yb) * 0.8361111
1✔
339
        scale = self._scale
1✔
340

341
        # if user passes in an ax, this size takes priority over any other settings
342
        if is_user_ax:
1✔
343
            # from stackoverflow #19306510, get the bbox size for the ax and then reset scale
344
            bbox = self._ax.get_window_extent().transformed(mpl_figure.dpi_scale_trans.inverted())
×
345
            scale = bbox.width / base_fig_w / 0.8361111
×
346

347
        # if scale not 1.0, use this scale factor
348
        elif self._scale != 1.0:
1✔
349
            mpl_figure.set_size_inches(base_fig_w * self._scale, base_fig_h * self._scale)
×
350

351
        # if "figwidth" style param set, use this to scale
352
        elif self._style["figwidth"] > 0.0:
1✔
353
            # in order to get actual inches, need to scale by factor
354
            adj_fig_w = self._style["figwidth"] * 1.282736
×
355
            mpl_figure.set_size_inches(adj_fig_w, adj_fig_w * base_fig_h / base_fig_w)
×
356
            scale = adj_fig_w / base_fig_w
×
357

358
        # otherwise, display default size
359
        else:
360
            mpl_figure.set_size_inches(base_fig_w, base_fig_h)
1✔
361

362
        # drawing will scale with 'set_size_inches', but fonts and linewidths do not
363
        if scale != 1.0:
1✔
364
            self._style["fs"] *= scale
×
365
            self._style["sfs"] *= scale
×
366
            self._lwidth1 = 1.0 * scale
×
367
            self._lwidth15 = 1.5 * scale
×
368
            self._lwidth2 = 2.0 * scale
×
369
            self._lwidth3 = 3.0 * scale
×
370
            self._lwidth4 = 4.0 * scale
×
371

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

399
    def _get_layer_widths(self, node_data, wire_map, outer_circuit, glob_data):
1✔
400
        """Compute the layer_widths for the layers"""
401

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

412
                op = node.op
1✔
413
                node_data[node] = NodeData()
1✔
414
                node_data[node].width = WID
1✔
415
                num_ctrl_qubits = getattr(op, "num_ctrl_qubits", 0)
1✔
416
                if (
1✔
417
                    getattr(op, "_directive", False) and (not op.label or not self._plot_barriers)
418
                ) or isinstance(op, Measure):
419
                    node_data[node].raw_gate_text = op.name
×
420
                    continue
×
421

422
                base_type = getattr(op, "base_gate", None)
1✔
423
                gate_text, ctrl_text, raw_gate_text = get_gate_ctrl_text(
1✔
424
                    op, "mpl", style=self._style, calibrations=self._calibrations
425
                )
426
                node_data[node].gate_text = gate_text
1✔
427
                node_data[node].ctrl_text = ctrl_text
1✔
428
                node_data[node].raw_gate_text = raw_gate_text
1✔
429
                node_data[node].param_text = ""
1✔
430

431
                # if single qubit, no params, and no labels, layer_width is 1
432
                if (
1✔
433
                    (len(node.qargs) - num_ctrl_qubits) == 1
434
                    and len(gate_text) < 3
435
                    and len(getattr(op, "params", [])) == 0
436
                    and ctrl_text is None
437
                ):
438
                    continue
1✔
439

440
                if isinstance(op, SwapGate) or isinstance(base_type, SwapGate):
1✔
441
                    continue
×
442

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

465
                # get gate_width for sidetext symmetric gates
466
                if isinstance(op, RZZGate) or isinstance(base_type, (U1Gate, PhaseGate, RZZGate)):
1✔
467
                    if isinstance(base_type, PhaseGate):
×
468
                        gate_text = "P"
×
469
                    raw_gate_width = (
×
470
                        self._get_text_width(
471
                            gate_text + " ()", glob_data, fontsize=self._style["sfs"]
472
                        )
473
                        + raw_param_width
474
                    )
475
                    gate_width = (raw_gate_width + 0.08) * 1.58
×
476

477
                # Check if a ControlFlowOp - node_data load for these gates is done here
478
                elif isinstance(node.op, ControlFlowOp):
1✔
479
                    self._flow_drawers[node] = []
×
480
                    node_data[node].width = []
×
481
                    node_data[node].nest_depth = 0
×
482
                    gate_width = 0.0
×
483
                    expr_width = 0.0
×
484

485
                    if (isinstance(op, SwitchCaseOp) and isinstance(op.target, expr.Expr)) or (
×
486
                        getattr(op, "condition", None) and isinstance(op.condition, expr.Expr)
487
                    ):
488

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

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

529
                        expr_width = self._get_text_width(
×
530
                            node_data[node].expr_text, glob_data, fontsize=self._style["sfs"]
531
                        )
532
                        node_data[node].expr_width = int(expr_width)
×
533

534
                    # Get the list of circuits to iterate over from the blocks
535
                    circuit_list = list(node.op.blocks)
×
536

537
                    # params is [indexset, loop_param, circuit] for for_loop,
538
                    # op.cases_specifier() returns jump tuple and circuit for switch/case
539
                    if isinstance(op, ForLoopOp):
×
540
                        node_data[node].indexset = op.params[0]
×
541
                    elif isinstance(op, SwitchCaseOp):
×
542
                        node_data[node].jump_values = []
×
543
                        cases = list(op.cases_specifier())
×
544

545
                        # Create an empty circuit at the head of the circuit_list if a Switch box
546
                        circuit_list.insert(0, cases[0][1].copy_empty_like())
×
547
                        for jump_values, _ in cases:
×
548
                            node_data[node].jump_values.append(jump_values)
×
549

550
                    # Now process the circuits inside the ControlFlowOps
551
                    for circ_num, circuit in enumerate(circuit_list):
×
552
                        # Only add expr_width for if, while, and switch
553
                        raw_gate_width = expr_width if circ_num == 0 else 0.0
×
554

555
                        # Depth of nested ControlFlowOp used for color of box
556
                        if self._flow_parent is not None:
×
557
                            node_data[node].nest_depth = node_data[self._flow_parent].nest_depth + 1
×
558

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

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

592
                        # flow_parent is the parent of the new class instance
593
                        flow_drawer._flow_parent = node
×
594
                        flow_drawer._flow_wire_map = flow_wire_map
×
595
                        self._flow_drawers[node].append(flow_drawer)
×
596

597
                        # Recursively call _get_layer_widths for the circuit inside the ControlFlowOp
598
                        flow_widths = flow_drawer._get_layer_widths(
×
599
                            node_data, flow_wire_map, outer_circuit, glob_data
600
                        )
601
                        layer_widths.update(flow_widths)
×
602

603
                        for flow_layer in flow_nodes:
×
604
                            for flow_node in flow_layer:
×
605
                                node_data[flow_node].circ_num = circ_num
×
606

607
                        # Add up the width values of the same flow_parent that are not -1
608
                        # to get the raw_gate_width
609
                        for width, layer_num, flow_parent in flow_widths.values():
×
610
                            if layer_num != -1 and flow_parent == flow_drawer._flow_parent:
×
611
                                raw_gate_width += width
×
612

613
                        # Need extra incr of 1.0 for else and case boxes
614
                        gate_width += raw_gate_width + (1.0 if circ_num > 0 else 0.0)
×
615

616
                        # Minor adjustment so else and case section gates align with indexes
617
                        if circ_num > 0:
×
618
                            raw_gate_width += 0.045
×
619

620
                        # If expr_width has a value, remove the decimal portion from raw_gate_widthl
621
                        if not isinstance(op, ForLoopOp) and circ_num == 0:
×
622
                            node_data[node].width.append(raw_gate_width - (expr_width % 1))
×
623
                        else:
624
                            node_data[node].width.append(raw_gate_width)
×
625

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

636
                box_width = max(gate_width, ctrl_width, param_width, WID)
1✔
637
                if box_width > widest_box:
1✔
638
                    widest_box = box_width
1✔
639
                if not isinstance(node.op, ControlFlowOp):
1✔
640
                    node_data[node].width = max(raw_gate_width, raw_param_width)
1✔
641
            for node in layer:
1✔
642
                layer_widths[node][0] = int(widest_box) + 1
1✔
643

644
        return layer_widths
1✔
645

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

649
        longest_wire_label_width = 0
1✔
650
        glob_data["n_lines"] = 0
1✔
651
        initial_qbit = r" $|0\rangle$" if self._initial_state else ""
1✔
652
        initial_cbit = " 0" if self._initial_state else ""
1✔
653

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

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

674
            wire_label = get_wire_label(
1✔
675
                "mpl", register, index, layout=self._layout, cregbundle=self._cregbundle
676
            )
677
            initial_bit = initial_qbit if isinstance(wire, Qubit) else initial_cbit
1✔
678

679
            # for cregs with cregbundle on, don't use math formatting, which means
680
            # no italics
681
            if isinstance(wire, Qubit) or register is None or not self._cregbundle:
1✔
682
                wire_label = "$" + wire_label + "$"
1✔
683
            wire_label += initial_bit
1✔
684

685
            reg_size = (
1✔
686
                0 if register is None or isinstance(wire, ClassicalRegister) else register.size
687
            )
688
            reg_remove_under = 0 if reg_size < 2 else 1
1✔
689
            text_width = (
1✔
690
                self._get_text_width(
691
                    wire_label, glob_data, self._style["fs"], reg_remove_under=reg_remove_under
692
                )
693
                * 1.15
694
            )
695
            if text_width > longest_wire_label_width:
1✔
696
                longest_wire_label_width = text_width
1✔
697

698
            if isinstance(wire, Qubit):
1✔
699
                pos = -ii
1✔
700
                qubits_dict[ii] = {
1✔
701
                    "y": pos,
702
                    "wire_label": wire_label,
703
                }
704
                glob_data["n_lines"] += 1
1✔
705
            else:
706
                if (
1✔
707
                    not self._cregbundle
708
                    or register is None
709
                    or (self._cregbundle and isinstance(wire, ClassicalRegister))
710
                ):
711
                    glob_data["n_lines"] += 1
1✔
712
                    idx += 1
1✔
713

714
                pos = y_off - idx
1✔
715
                clbits_dict[ii] = {
1✔
716
                    "y": pos,
717
                    "wire_label": wire_label,
718
                    "register": register,
719
                }
720
        glob_data["x_offset"] = -1.2 + longest_wire_label_width
1✔
721

722
    def _get_coords(
1✔
723
        self,
724
        node_data,
725
        wire_map,
726
        outer_circuit,
727
        layer_widths,
728
        qubits_dict,
729
        clbits_dict,
730
        glob_data,
731
        flow_parent=None,
732
    ):
733
        """Load all the coordinate info needed to place the gates on the drawing."""
734

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

757
                # get qubit indexes
758
                q_indxs = []
1✔
759
                for qarg in node.qargs:
1✔
760
                    if qarg in self._qubits:
1✔
761
                        q_indxs.append(wire_map[qarg])
1✔
762

763
                # get clbit indexes
764
                c_indxs = []
1✔
765
                for carg in node.cargs:
1✔
766
                    if carg in self._clbits:
1✔
767
                        if self._cregbundle:
1✔
768
                            register = get_bit_register(outer_circuit, carg)
×
769
                            if register is not None:
×
770
                                c_indxs.append(wire_map[register])
×
771
                            else:
772
                                c_indxs.append(wire_map[carg])
×
773
                        else:
774
                            c_indxs.append(wire_map[carg])
1✔
775

776
                flow_op = isinstance(node.op, ControlFlowOp)
1✔
777

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

801
                # update index based on the value from plotting
802
                if flow_parent is None:
1✔
803
                    curr_x_index = glob_data["next_x_index"]
1✔
804
                l_width.append(layer_widths[node][0])
1✔
805
                node_data[node].x_index = x_index
1✔
806

807
                # Special case of default case with no ops in it, need to push end
808
                # of switch op one extra x_index
809
                if isinstance(node.op, SwitchCaseOp):
1✔
810
                    if len(node.op.blocks[-1]) == 0:
×
811
                        curr_x_index += 1
×
812

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

823
        return prev_x_index + 1
1✔
824

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

828
        from pylatexenc.latex2text import LatexNodes2Text
1✔
829

830
        if not text:
1✔
831
            return 0.0
1✔
832

833
        math_mode_match = self._mathmode_regex.search(text)
1✔
834
        num_underscores = 0
1✔
835
        num_carets = 0
1✔
836
        if math_mode_match:
1✔
837
            math_mode_text = math_mode_match.group(1)
1✔
838
            num_underscores = math_mode_text.count("_")
1✔
839
            num_carets = math_mode_text.count("^")
1✔
840
        text = LatexNodes2Text().latex_to_text(text.replace("$$", ""))
1✔
841

842
        # If there are subscripts or superscripts in mathtext string
843
        # we need to account for that spacing by manually removing
844
        # from text string for text length
845

846
        # if it's a register and there's a subscript at the end,
847
        # remove 1 underscore, otherwise don't remove any
848
        if reg_remove_under is not None:
1✔
849
            num_underscores = reg_remove_under
1✔
850
        if num_underscores:
1✔
851
            text = text.replace("_", "", num_underscores)
1✔
852
        if num_carets:
1✔
853
            text = text.replace("^", "", num_carets)
×
854

855
        # This changes hyphen to + to match width of math mode minus sign.
856
        if param:
1✔
857
            text = text.replace("-", "+")
×
858

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

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

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

893
            # classical registers
894
            this_clbit_dict = {}
1✔
895
            for clbit in clbits_dict.values():
1✔
896
                y = clbit["y"] - fold_num * (glob_data["n_lines"] + 1)
1✔
897
                if y not in this_clbit_dict:
1✔
898
                    this_clbit_dict[y] = {
1✔
899
                        "val": 1,
900
                        "wire_label": clbit["wire_label"],
901
                        "register": clbit["register"],
902
                    }
903
                else:
904
                    this_clbit_dict[y]["val"] += 1
×
905

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

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

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

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

1041
    def _draw_ops(
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
        verbose=False,
1052
    ):
1053
        """Draw the gates in the circuit"""
1054

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

1071
            # draw the gates in this layer
1072
            for node in layer:
1✔
1073
                op = node.op
1✔
1074

1075
                self._get_colors(node, node_data)
1✔
1076

1077
                if verbose:
1✔
1078
                    print(op)  # pylint: disable=bad-builtin
×
1079

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

1094
                # AnnotatedOperation with ControlModifier
1095
                mod_control = None
1✔
1096
                if getattr(op, "modifiers", None):
1✔
1097
                    canonical_modifiers = _canonicalize_modifiers(op.modifiers)
×
1098
                    for modifier in canonical_modifiers:
×
1099
                        if isinstance(modifier, ControlModifier):
×
1100
                            mod_control = modifier
×
1101
                            break
×
1102

1103
                # draw measure
1104
                if isinstance(op, Measure):
1✔
1105
                    self._measure(node, node_data, outer_circuit, glob_data)
×
1106

1107
                # draw barriers, snapshots, etc.
1108
                elif getattr(op, "_directive", False):
1✔
1109
                    if self._plot_barriers:
×
1110
                        self._barrier(node, node_data, glob_data)
×
1111

1112
                # draw the box for control flow circuits
1113
                elif isinstance(op, ControlFlowOp):
1✔
1114
                    self._flow_op_gate(node, node_data, glob_data)
×
1115

1116
                # draw single qubit gates
1117
                elif len(node_data[node].q_xy) == 1 and not node.cargs:
1✔
1118
                    self._gate(node, node_data, glob_data)
1✔
1119

1120
                # draw controlled gates
1121
                elif isinstance(op, ControlledGate) or mod_control:
1✔
1122
                    self._control_gate(node, node_data, glob_data, mod_control)
×
1123

1124
                # draw multi-qubit gate as final default
1125
                else:
1126
                    self._multiqubit_gate(node, node_data, glob_data)
1✔
1127

1128
                # Determine the max width of the circuit only at the top level
1129
                if not node_data[node].inside_flow:
1✔
1130
                    l_width.append(layer_widths[node][0])
1✔
1131

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

1141
    def _get_colors(self, node, node_data):
1✔
1142
        """Get all the colors needed for drawing the circuit"""
1143

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

1178
        if self._style["name"] == "bw":
1✔
1179
            ec = self._style["ec"]
×
1180
            lc = self._style["lc"]
×
1181
        else:
1182
            ec = fc
1✔
1183
            lc = fc
1✔
1184
        # Subtext needs to be same color as gate text
1185
        sc = gt
1✔
1186
        node_data[node].fc = fc
1✔
1187
        node_data[node].ec = ec
1✔
1188
        node_data[node].gt = gt
1✔
1189
        node_data[node].tc = self._style["tc"]
1✔
1190
        node_data[node].sc = sc
1✔
1191
        node_data[node].lc = lc
1✔
1192

1193
    def _condition(self, node, node_data, wire_map, outer_circuit, cond_xy, glob_data):
1✔
1194
        """Add a conditional to a gate"""
1195

1196
        # For SwitchCaseOp convert the target to a fully closed Clbit or register
1197
        # in condition format
1198
        if isinstance(node.op, SwitchCaseOp):
×
1199
            if isinstance(node.op.target, expr.Expr):
×
1200
                condition = node.op.target
×
1201
            elif isinstance(node.op.target, Clbit):
×
1202
                condition = (node.op.target, 1)
×
1203
            else:
1204
                condition = (node.op.target, 2 ** (node.op.target.size) - 1)
×
1205
        else:
1206
            condition = node.op.condition
×
1207

1208
        override_fc = False
×
1209
        first_clbit = len(self._qubits)
×
1210
        cond_pos = []
×
1211

1212
        if isinstance(condition, expr.Expr):
×
1213
            # If fixing this, please update the docstrings of `QuantumCircuit.draw` and
1214
            # `visualization.circuit_drawer` to remove warnings.
1215

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

1242
            # In the first case, multiple bits are indicated on the drawing. In all
1243
            # other cases, only one bit is shown.
1244
            if not self._cregbundle and isinstance(cond_bit_reg, ClassicalRegister):
×
1245
                for idx in range(cond_bit_reg.size):
×
1246
                    cond_pos.append(cond_xy[wire_map[cond_bit_reg[idx]] - first_clbit])
×
1247

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

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

1272
        if not xy_plot:
×
1273
            # Expression that's only on new-style `expr.Var` nodes, and doesn't need any vertical
1274
            # line drawing.
1275
            return
×
1276

1277
        qubit_b = min(node_data[node].q_xy, key=lambda xy: xy[1])
×
1278
        clbit_b = min(xy_plot, key=lambda xy: xy[1])
×
1279

1280
        # For IfElseOp, WhileLoopOp or SwitchCaseOp, place the condition line
1281
        # near the left edge of the box
1282
        if isinstance(node.op, (IfElseOp, WhileLoopOp, SwitchCaseOp)):
×
1283
            qubit_b = (qubit_b[0], qubit_b[1] - (0.5 * HIG + 0.14))
×
1284

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

1302
    def _measure(self, node, node_data, outer_circuit, glob_data):
1✔
1303
        """Draw the measure symbol and the line to the clbit"""
1304
        qx, qy = node_data[node].q_xy[0]
×
1305
        cx, cy = node_data[node].c_xy[0]
×
1306
        register, _, reg_index = get_bit_reg_index(outer_circuit, node.cargs[0])
×
1307

1308
        # draw gate box
1309
        self._gate(node, node_data, glob_data)
×
1310

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

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

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

1406
    def _gate(self, node, node_data, glob_data, xy=None):
1✔
1407
        """Draw a 1-qubit gate"""
1408
        if xy is None:
1✔
1409
            xy = node_data[node].q_xy[0]
1✔
1410
        xpos, ypos = xy
1✔
1411
        wid = max(node_data[node].width, WID)
1✔
1412

1413
        box = glob_data["patches_mod"].Rectangle(
1✔
1414
            xy=(xpos - 0.5 * wid, ypos - 0.5 * HIG),
1415
            width=wid,
1416
            height=HIG,
1417
            fc=node_data[node].fc,
1418
            ec=node_data[node].ec,
1419
            linewidth=self._lwidth15,
1420
            zorder=PORDER_GATE,
1421
        )
1422
        self._ax.add_patch(box)
1✔
1423

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

1451
    def _multiqubit_gate(self, node, node_data, glob_data, xy=None):
1✔
1452
        """Draw a gate covering more than one qubit"""
1453
        op = node.op
1✔
1454
        if xy is None:
1✔
1455
            xy = node_data[node].q_xy
1✔
1456

1457
        # Swap gate
1458
        if isinstance(op, SwapGate):
1✔
1459
            self._swap(xy, node, node_data, node_data[node].lc)
×
1460
            return
×
1461

1462
        # RZZ Gate
1463
        elif isinstance(op, RZZGate):
1✔
1464
            self._symmetric_gate(node, node_data, RZZGate, glob_data)
×
1465
            return
×
1466

1467
        c_xy = node_data[node].c_xy
1✔
1468
        xpos = min(x[0] for x in xy)
1✔
1469
        ypos = min(y[1] for y in xy)
1✔
1470
        ypos_max = max(y[1] for y in xy)
1✔
1471
        if c_xy:
1✔
1472
            cxpos = min(x[0] for x in c_xy)
1✔
1473
            cypos = min(y[1] for y in c_xy)
1✔
1474
            ypos = min(ypos, cypos)
1✔
1475

1476
        wid = max(node_data[node].width + 0.21, WID)
1✔
1477
        qubit_span = abs(ypos) - abs(ypos_max)
1✔
1478
        height = HIG + qubit_span
1✔
1479

1480
        box = glob_data["patches_mod"].Rectangle(
1✔
1481
            xy=(xpos - 0.5 * wid, ypos - 0.5 * HIG),
1482
            width=wid,
1483
            height=height,
1484
            fc=node_data[node].fc,
1485
            ec=node_data[node].ec,
1486
            linewidth=self._lwidth15,
1487
            zorder=PORDER_GATE,
1488
        )
1489
        self._ax.add_patch(box)
1✔
1490

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

1545
    def _flow_op_gate(self, node, node_data, glob_data):
1✔
1546
        """Draw the box for a flow op circuit"""
1547
        xy = node_data[node].q_xy
×
1548
        xpos = min(x[0] for x in xy)
×
1549
        ypos = min(y[1] for y in xy)
×
1550
        ypos_max = max(y[1] for y in xy)
×
1551

1552
        if_width = node_data[node].width[0] + WID
×
1553
        box_width = if_width
×
1554
        # Add the else and case widths to the if_width
1555
        for ewidth in node_data[node].width[1:]:
×
1556
            if ewidth > 0.0:
×
1557
                box_width += ewidth + WID + 0.3
×
1558

1559
        qubit_span = abs(ypos) - abs(ypos_max)
×
1560
        height = HIG + qubit_span
×
1561

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

1575
        while end_x > 0.0:
×
1576
            x_shift = fold_level * self._fold
×
1577
            y_shift = fold_level * (glob_data["n_lines"] + 1)
×
1578
            end_x = xpos + box_width - x_shift if self._fold > 0 else 0.0
×
1579

1580
            if isinstance(node.op, IfElseOp):
×
1581
                flow_text = "  If"
×
1582
            elif isinstance(node.op, WhileLoopOp):
×
1583
                flow_text = " While"
×
1584
            elif isinstance(node.op, ForLoopOp):
×
1585
                flow_text = " For"
×
1586
            elif isinstance(node.op, SwitchCaseOp):
×
1587
                flow_text = "Switch"
×
NEW
1588
            elif isinstance(node.op, BoxOp):
×
NEW
1589
                flow_text = ""
×
1590
            else:
1591
                raise RuntimeError(f"unhandled control-flow op: {node.name}")
1592

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

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

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

1721
            fold_level += 1
×
1722

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

1745
        if isinstance(op, RZZGate) or isinstance(base_type, (U1Gate, PhaseGate, ZGate, RZZGate)):
×
1746
            self._symmetric_gate(node, node_data, base_type, glob_data)
×
1747

1748
        elif num_qargs == 1 and isinstance(base_type, XGate):
×
1749
            tgt_color = self._style["dispcol"]["target"]
×
1750
            tgt = tgt_color if isinstance(tgt_color, str) else tgt_color[0]
×
1751
            self._x_tgt_qubit(xy[num_ctrl_qubits], glob_data, ec=node_data[node].ec, ac=tgt)
×
1752

1753
        elif num_qargs == 1:
×
1754
            self._gate(node, node_data, glob_data, xy[num_ctrl_qubits:][0])
×
1755

1756
        elif isinstance(base_type, SwapGate):
×
1757
            self._swap(xy[num_ctrl_qubits:], node, node_data, node_data[node].lc)
×
1758

1759
        else:
1760
            self._multiqubit_gate(node, node_data, glob_data, xy[num_ctrl_qubits:])
×
1761

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

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

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

1802
        # adjust label height according to number of lines of text
1803
        label_padding = 0.7
×
1804
        if text is not None:
×
1805
            text_lines = text.count("\n")
×
1806
            if not text.endswith("(cal)\n"):
×
1807
                for _ in range(text_lines):
×
1808
                    label_padding += 0.3
×
1809

1810
        if text_top is None:
×
1811
            return
×
1812

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

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

1841
        # add '+' symbol
1842
        self._ax.plot(
×
1843
            [xpos, xpos],
1844
            [ypos - 0.2 * HIG, ypos + 0.2 * HIG],
1845
            color=ac,
1846
            linewidth=linewidth,
1847
            zorder=PORDER_GATE_PLUS,
1848
        )
1849
        self._ax.plot(
×
1850
            [xpos - 0.2 * HIG, xpos + 0.2 * HIG],
1851
            [ypos, ypos],
1852
            color=ac,
1853
            linewidth=linewidth,
1854
            zorder=PORDER_GATE_PLUS,
1855
        )
1856

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

1868
        # cz and mcz gates
1869
        if not isinstance(op, ZGate) and isinstance(base_type, ZGate):
×
1870
            num_ctrl_qubits = op.num_ctrl_qubits
×
1871
            self._ctrl_qubit(xy[-1], glob_data, fc=ec, ec=ec, tc=tc)
×
1872
            self._line(qubit_b, qubit_t, lc=lc, zorder=PORDER_LINE_PLUS)
×
1873

1874
        # cu1, cp, rzz, and controlled rzz gates (sidetext gates)
1875
        elif isinstance(op, RZZGate) or isinstance(base_type, (U1Gate, PhaseGate, RZZGate)):
×
1876
            num_ctrl_qubits = 0 if isinstance(op, RZZGate) else op.num_ctrl_qubits
×
1877
            gate_text = "P" if isinstance(base_type, PhaseGate) else node_data[node].gate_text
×
1878

1879
            self._ctrl_qubit(xy[num_ctrl_qubits], glob_data, fc=ec, ec=ec, tc=tc)
×
1880
            if not isinstance(base_type, (U1Gate, PhaseGate)):
×
1881
                self._ctrl_qubit(xy[num_ctrl_qubits + 1], glob_data, fc=ec, ec=ec, tc=tc)
×
1882

1883
            self._sidetext(
×
1884
                node,
1885
                node_data,
1886
                qubit_b,
1887
                tc=tc,
1888
                text=f"{gate_text} ({node_data[node].param_text})",
1889
            )
1890
            self._line(qubit_b, qubit_t, lc=lc)
×
1891

1892
    def _swap(self, xy, node, node_data, color=None):
1✔
1893
        """Draw a Swap gate"""
1894
        self._swap_cross(xy[0], color=color)
×
1895
        self._swap_cross(xy[1], color=color)
×
1896
        self._line(xy[0], xy[1], lc=color)
×
1897

1898
        # add calibration text
1899
        gate_text = node_data[node].gate_text.split("\n")[-1]
×
1900
        if node_data[node].raw_gate_text in self._calibrations:
×
1901
            xpos, ypos = xy[0]
×
1902
            self._ax.text(
×
1903
                xpos,
1904
                ypos + 0.7 * HIG,
1905
                gate_text,
1906
                ha="center",
1907
                va="top",
1908
                fontsize=self._style["sfs"],
1909
                color=self._style["tc"],
1910
                clip_on=True,
1911
                zorder=PORDER_TEXT,
1912
            )
1913

1914
    def _swap_cross(self, xy, color=None):
1✔
1915
        """Draw the Swap cross symbol"""
1916
        xpos, ypos = xy
×
1917

1918
        self._ax.plot(
×
1919
            [xpos - 0.20 * WID, xpos + 0.20 * WID],
1920
            [ypos - 0.20 * WID, ypos + 0.20 * WID],
1921
            color=color,
1922
            linewidth=self._lwidth2,
1923
            zorder=PORDER_LINE_PLUS,
1924
        )
1925
        self._ax.plot(
×
1926
            [xpos - 0.20 * WID, xpos + 0.20 * WID],
1927
            [ypos + 0.20 * WID, ypos - 0.20 * WID],
1928
            color=color,
1929
            linewidth=self._lwidth2,
1930
            zorder=PORDER_LINE_PLUS,
1931
        )
1932

1933
    def _sidetext(self, node, node_data, xy, tc=None, text=""):
1✔
1934
        """Draw the sidetext for symmetric gates"""
1935
        xpos, ypos = xy
×
1936

1937
        # 0.11 = the initial gap, add 1/2 text width to place on the right
1938
        xp = xpos + 0.11 + node_data[node].width / 2
×
1939
        self._ax.text(
×
1940
            xp,
1941
            ypos + HIG,
1942
            text,
1943
            ha="center",
1944
            va="top",
1945
            fontsize=self._style["sfs"],
1946
            color=tc,
1947
            clip_on=True,
1948
            zorder=PORDER_TEXT,
1949
        )
1950

1951
    def _line(self, xy0, xy1, lc=None, ls=None, zorder=PORDER_LINE):
1✔
1952
        """Draw a line from xy0 to xy1"""
1953
        x0, y0 = xy0
1✔
1954
        x1, y1 = xy1
1✔
1955
        linecolor = self._style["lc"] if lc is None else lc
1✔
1956
        linestyle = "solid" if ls is None else ls
1✔
1957

1958
        if linestyle == "doublet":
1✔
1959
            theta = np.arctan2(np.abs(x1 - x0), np.abs(y1 - y0))
1✔
1960
            dx = 0.05 * WID * np.cos(theta)
1✔
1961
            dy = 0.05 * WID * np.sin(theta)
1✔
1962
            self._ax.plot(
1✔
1963
                [x0 + dx, x1 + dx],
1964
                [y0 + dy, y1 + dy],
1965
                color=linecolor,
1966
                linewidth=self._lwidth2,
1967
                linestyle="solid",
1968
                zorder=zorder,
1969
            )
1970
            self._ax.plot(
1✔
1971
                [x0 - dx, x1 - dx],
1972
                [y0 - dy, y1 - dy],
1973
                color=linecolor,
1974
                linewidth=self._lwidth2,
1975
                linestyle="solid",
1976
                zorder=zorder,
1977
            )
1978
        else:
1979
            self._ax.plot(
1✔
1980
                [x0, x1],
1981
                [y0, y1],
1982
                color=linecolor,
1983
                linewidth=self._lwidth2,
1984
                linestyle=linestyle,
1985
                zorder=zorder,
1986
            )
1987

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

1991
        # Check folding
1992
        fold = self._fold if self._fold > 0 else INFINITE_FOLD
1✔
1993
        h_pos = x_index % fold + 1
1✔
1994

1995
        # Don't fold flow_ops here, only gates inside the flow_op
1996
        if not flow_op and h_pos + (gate_width - 1) > fold:
1✔
1997
            x_index += fold - (h_pos - 1)
×
1998
        x_pos = x_index % fold + glob_data["x_offset"] + 0.04
1✔
1999
        if not flow_op:
1✔
2000
            x_pos += 0.5 * gate_width
1✔
2001
        else:
2002
            x_pos += 0.25
×
2003
        y_pos = y_index - (x_index // fold) * (glob_data["n_lines"] + 1)
1✔
2004

2005
        # x_index could have been updated, so need to store
2006
        glob_data["next_x_index"] = x_index
1✔
2007
        return x_pos, y_pos
1✔
2008

2009

2010
class NodeData:
1✔
2011
    """Class containing drawing data on a per node basis"""
2012

2013
    def __init__(self):
1✔
2014
        # Node data for positioning
2015
        self.width = 0.0
1✔
2016
        self.x_index = 0
1✔
2017
        self.q_xy = []
1✔
2018
        self.c_xy = []
1✔
2019

2020
        # Node data for text
2021
        self.gate_text = ""
1✔
2022
        self.raw_gate_text = ""
1✔
2023
        self.ctrl_text = ""
1✔
2024
        self.param_text = ""
1✔
2025

2026
        # Node data for color
2027
        self.fc = self.ec = self.lc = self.sc = self.gt = self.tc = 0
1✔
2028

2029
        # Special values stored for ControlFlowOps
2030
        self.nest_depth = 0
1✔
2031
        self.expr_width = 0.0
1✔
2032
        self.expr_text = ""
1✔
2033
        self.inside_flow = False
1✔
2034
        self.indexset = ()  # List of indices used for ForLoopOp
1✔
2035
        self.jump_values = []  # List of jump values used for SwitchCaseOp
1✔
2036
        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