-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
matplotlib.py
1904 lines (1710 loc) · 71.6 KB
/
matplotlib.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=invalid-name,inconsistent-return-statements
"""mpl circuit visualization backend."""
import collections
import itertools
import re
from warnings import warn
import numpy as np
from qiskit.circuit import (
QuantumCircuit,
Qubit,
Clbit,
ClassicalRegister,
ControlledGate,
Measure,
ControlFlowOp,
WhileLoopOp,
IfElseOp,
ForLoopOp,
SwitchCaseOp,
)
from qiskit.circuit.controlflow import condition_resources
from qiskit.circuit.classical import expr
from qiskit.circuit.library.standard_gates import (
SwapGate,
RZZGate,
U1Gate,
PhaseGate,
XGate,
ZGate,
)
from qiskit.extensions import Initialize
from qiskit.circuit.tools.pi_check import pi_check
from qiskit.utils import optionals as _optionals
from .qcstyle import load_style
from ._utils import (
get_gate_ctrl_text,
get_param_str,
get_wire_map,
get_bit_register,
get_bit_reg_index,
get_wire_label,
get_condition_label_val,
_get_layered_instructions,
)
from ..utils import matplotlib_close_if_inline
# Default gate width and height
WID = 0.65
HIG = 0.65
# Z dimension order for different drawing types
PORDER_REGLINE = 1
PORDER_FLOW = 3
PORDER_MASK = 4
PORDER_LINE = 6
PORDER_LINE_PLUS = 7
PORDER_BARRIER = 8
PORDER_GATE = 10
PORDER_GATE_PLUS = 11
PORDER_TEXT = 13
INFINITE_FOLD = 10000000
@_optionals.HAS_MATPLOTLIB.require_in_instance
@_optionals.HAS_PYLATEX.require_in_instance
class MatplotlibDrawer:
"""Matplotlib drawer class called from circuit_drawer"""
_mathmode_regex = re.compile(r"(?<!\\)\$(.*)(?<!\\)\$")
def __init__(
self,
qubits,
clbits,
nodes,
circuit,
scale=None,
style=None,
reverse_bits=False,
plot_barriers=True,
fold=25,
ax=None,
initial_state=False,
cregbundle=None,
with_layout=False,
):
self._circuit = circuit
self._qubits = qubits
self._clbits = clbits
self._nodes = nodes
self._scale = 1.0 if scale is None else scale
self._style = style
self._plot_barriers = plot_barriers
self._reverse_bits = reverse_bits
if with_layout:
if self._circuit._layout:
self._layout = self._circuit._layout.initial_layout
else:
self._layout = None
else:
self._layout = None
self._fold = fold
if self._fold < 2:
self._fold = -1
self._ax = ax
self._initial_state = initial_state
self._global_phase = self._circuit.global_phase
self._calibrations = self._circuit.calibrations
for node in itertools.chain.from_iterable(self._nodes):
if node.cargs and node.op.name != "measure":
if cregbundle:
warn(
"Cregbundle set to False since an instruction needs to refer"
" to individual classical wire",
RuntimeWarning,
3,
)
self._cregbundle = False
break
else:
self._cregbundle = True if cregbundle is None else cregbundle
self._lwidth1 = 1.0
self._lwidth15 = 1.5
self._lwidth2 = 2.0
self._lwidth3 = 3.0
self._lwidth4 = 4.0
# Class instances of MatplotlibDrawer for each flow gate - If/Else, For, While, Switch
self._flow_drawers = {}
# Set if gate is inside a flow gate
self._flow_parent = None
self._flow_wire_map = {}
# _char_list for finding text_width of names, labels, and params
self._char_list = {
" ": (0.0958, 0.0583),
"!": (0.1208, 0.0729),
'"': (0.1396, 0.0875),
"#": (0.2521, 0.1562),
"$": (0.1917, 0.1167),
"%": (0.2854, 0.1771),
"&": (0.2333, 0.1458),
"'": (0.0833, 0.0521),
"(": (0.1167, 0.0729),
")": (0.1167, 0.0729),
"*": (0.15, 0.0938),
"+": (0.25, 0.1562),
",": (0.0958, 0.0583),
"-": (0.1083, 0.0667),
".": (0.0958, 0.0604),
"/": (0.1021, 0.0625),
"0": (0.1875, 0.1167),
"1": (0.1896, 0.1167),
"2": (0.1917, 0.1188),
"3": (0.1917, 0.1167),
"4": (0.1917, 0.1188),
"5": (0.1917, 0.1167),
"6": (0.1896, 0.1167),
"7": (0.1917, 0.1188),
"8": (0.1896, 0.1188),
"9": (0.1917, 0.1188),
":": (0.1021, 0.0604),
";": (0.1021, 0.0604),
"<": (0.25, 0.1542),
"=": (0.25, 0.1562),
">": (0.25, 0.1542),
"?": (0.1583, 0.0979),
"@": (0.2979, 0.1854),
"A": (0.2062, 0.1271),
"B": (0.2042, 0.1271),
"C": (0.2083, 0.1292),
"D": (0.2312, 0.1417),
"E": (0.1875, 0.1167),
"F": (0.1708, 0.1062),
"G": (0.2312, 0.1438),
"H": (0.225, 0.1396),
"I": (0.0875, 0.0542),
"J": (0.0875, 0.0542),
"K": (0.1958, 0.1208),
"L": (0.1667, 0.1042),
"M": (0.2583, 0.1604),
"N": (0.225, 0.1396),
"O": (0.2354, 0.1458),
"P": (0.1812, 0.1125),
"Q": (0.2354, 0.1458),
"R": (0.2083, 0.1292),
"S": (0.1896, 0.1188),
"T": (0.1854, 0.1125),
"U": (0.2208, 0.1354),
"V": (0.2062, 0.1271),
"W": (0.2958, 0.1833),
"X": (0.2062, 0.1271),
"Y": (0.1833, 0.1125),
"Z": (0.2042, 0.1271),
"[": (0.1167, 0.075),
"\\": (0.1021, 0.0625),
"]": (0.1167, 0.0729),
"^": (0.2521, 0.1562),
"_": (0.1521, 0.0938),
"`": (0.15, 0.0938),
"a": (0.1854, 0.1146),
"b": (0.1917, 0.1167),
"c": (0.1646, 0.1021),
"d": (0.1896, 0.1188),
"e": (0.1854, 0.1146),
"f": (0.1042, 0.0667),
"g": (0.1896, 0.1188),
"h": (0.1896, 0.1188),
"i": (0.0854, 0.0521),
"j": (0.0854, 0.0521),
"k": (0.1729, 0.1083),
"l": (0.0854, 0.0521),
"m": (0.2917, 0.1812),
"n": (0.1896, 0.1188),
"o": (0.1833, 0.1125),
"p": (0.1917, 0.1167),
"q": (0.1896, 0.1188),
"r": (0.125, 0.0771),
"s": (0.1562, 0.0958),
"t": (0.1167, 0.0729),
"u": (0.1896, 0.1188),
"v": (0.1771, 0.1104),
"w": (0.2458, 0.1521),
"x": (0.1771, 0.1104),
"y": (0.1771, 0.1104),
"z": (0.1562, 0.0979),
"{": (0.1917, 0.1188),
"|": (0.1, 0.0604),
"}": (0.1896, 0.1188),
}
def draw(self, filename=None, verbose=False):
"""Main entry point to 'matplotlib' ('mpl') drawer. Called from
``visualization.circuit_drawer`` and from ``QuantumCircuit.draw`` through circuit_drawer.
"""
# Import matplotlib and load all the figure, window, and style info
from matplotlib import patches
from matplotlib import pyplot as plt
# glob_data contains global values used throughout, "n_lines", "x_offset", "next_x_index",
# "patches_mod", "subfont_factor"
glob_data = {}
glob_data["patches_mod"] = patches
plt_mod = plt
self._style, def_font_ratio = load_style(self._style)
# If font/subfont ratio changes from default, have to scale width calculations for
# subfont. Font change is auto scaled in the mpl_figure.set_size_inches call in draw()
glob_data["subfont_factor"] = self._style["sfs"] * def_font_ratio / self._style["fs"]
# if no user ax, setup default figure. Else use the user figure.
if self._ax is None:
is_user_ax = False
mpl_figure = plt.figure()
mpl_figure.patch.set_facecolor(color=self._style["bg"])
self._ax = mpl_figure.add_subplot(111)
else:
is_user_ax = True
mpl_figure = self._ax.get_figure()
self._ax.axis("off")
self._ax.set_aspect("equal")
self._ax.tick_params(labelbottom=False, labeltop=False, labelleft=False, labelright=False)
# All information for the drawing is first loaded into node_data for the gates and into
# qubits_dict, clbits_dict, and wire_map for the qubits, clbits, and wires,
# followed by the coordinates for each gate.
# load the wire map
wire_map = get_wire_map(self._circuit, self._qubits + self._clbits, self._cregbundle)
# node_data per node filled with class NodeData attributes
node_data = {}
# dicts for the names and locations of register/bit labels
qubits_dict = {}
clbits_dict = {}
# load the _qubit_dict and _clbit_dict with register info
self._set_bit_reg_info(wire_map, qubits_dict, clbits_dict, glob_data)
# get layer widths - flow gates are initialized here
layer_widths = self._get_layer_widths(node_data, wire_map, glob_data)
# load the coordinates for each top level gate and compute number of folds.
# coordinates for flow gates are loaded before draw_ops
max_x_index = self._get_coords(
node_data, wire_map, layer_widths, qubits_dict, clbits_dict, glob_data
)
num_folds = max(0, max_x_index - 1) // self._fold if self._fold > 0 else 0
# The window size limits are computed, followed by one of the four possible ways
# of scaling the drawing.
# compute the window size
if max_x_index > self._fold > 0:
xmax = self._fold + glob_data["x_offset"] + 0.1
ymax = (num_folds + 1) * (glob_data["n_lines"] + 1) - 1
else:
x_incr = 0.4 if not self._nodes else 0.9
xmax = max_x_index + 1 + glob_data["x_offset"] - x_incr
ymax = glob_data["n_lines"]
xl = -self._style["margin"][0]
xr = xmax + self._style["margin"][1]
yb = -ymax - self._style["margin"][2] + 0.5
yt = self._style["margin"][3] + 0.5
self._ax.set_xlim(xl, xr)
self._ax.set_ylim(yb, yt)
# update figure size and, for backward compatibility,
# need to scale by a default value equal to (self._style["fs"] * 3.01 / 72 / 0.65)
base_fig_w = (xr - xl) * 0.8361111
base_fig_h = (yt - yb) * 0.8361111
scale = self._scale
# if user passes in an ax, this size takes priority over any other settings
if is_user_ax:
# from stackoverflow #19306510, get the bbox size for the ax and then reset scale
bbox = self._ax.get_window_extent().transformed(mpl_figure.dpi_scale_trans.inverted())
scale = bbox.width / base_fig_w / 0.8361111
# if scale not 1.0, use this scale factor
elif self._scale != 1.0:
mpl_figure.set_size_inches(base_fig_w * self._scale, base_fig_h * self._scale)
# if "figwidth" style param set, use this to scale
elif self._style["figwidth"] > 0.0:
# in order to get actual inches, need to scale by factor
adj_fig_w = self._style["figwidth"] * 1.282736
mpl_figure.set_size_inches(adj_fig_w, adj_fig_w * base_fig_h / base_fig_w)
scale = adj_fig_w / base_fig_w
# otherwise, display default size
else:
mpl_figure.set_size_inches(base_fig_w, base_fig_h)
# drawing will scale with 'set_size_inches', but fonts and linewidths do not
if scale != 1.0:
self._style["fs"] *= scale
self._style["sfs"] *= scale
self._lwidth1 = 1.0 * scale
self._lwidth15 = 1.5 * scale
self._lwidth2 = 2.0 * scale
self._lwidth3 = 3.0 * scale
self._lwidth4 = 4.0 * scale
# Once the scaling factor has been determined, the global phase, register names
# and numbers, wires, and gates are drawn
if self._global_phase:
plt_mod.text(xl, yt, "Global Phase: %s" % pi_check(self._global_phase, output="mpl"))
self._draw_regs_wires(num_folds, xmax, max_x_index, qubits_dict, clbits_dict, glob_data)
self._draw_ops(
self._nodes,
node_data,
wire_map,
layer_widths,
qubits_dict,
clbits_dict,
glob_data,
verbose,
)
if filename:
mpl_figure.savefig(
filename,
dpi=self._style["dpi"],
bbox_inches="tight",
facecolor=mpl_figure.get_facecolor(),
)
if not is_user_ax:
matplotlib_close_if_inline(mpl_figure)
return mpl_figure
def _get_layer_widths(self, node_data, wire_map, glob_data):
"""Compute the layer_widths for the layers"""
layer_widths = {}
for layer_num, layer in enumerate(self._nodes):
widest_box = WID
for i, node in enumerate(layer):
# Put the layer_num in the first node in the layer and put -1 in the rest
# so that layer widths are not counted more than once
if i != 0:
layer_num = -1
layer_widths[node] = [1, layer_num, self._flow_parent]
op = node.op
node_data[node] = NodeData()
node_data[node].width = WID
num_ctrl_qubits = 0 if not hasattr(op, "num_ctrl_qubits") else op.num_ctrl_qubits
if (
getattr(op, "_directive", False) and (not op.label or not self._plot_barriers)
) or isinstance(op, Measure):
node_data[node].raw_gate_text = op.name
continue
base_type = None if not hasattr(op, "base_gate") else op.base_gate
gate_text, ctrl_text, raw_gate_text = get_gate_ctrl_text(
op, "mpl", style=self._style, calibrations=self._calibrations
)
node_data[node].gate_text = gate_text
node_data[node].ctrl_text = ctrl_text
node_data[node].raw_gate_text = raw_gate_text
node_data[node].param_text = ""
# if single qubit, no params, and no labels, layer_width is 1
if (
(len(node.qargs) - num_ctrl_qubits) == 1
and len(gate_text) < 3
and (not hasattr(op, "params") or len(op.params) == 0)
and ctrl_text is None
):
continue
if isinstance(op, SwapGate) or isinstance(base_type, SwapGate):
continue
# small increments at end of the 3 _get_text_width calls are for small
# spacing adjustments between gates
ctrl_width = (
self._get_text_width(ctrl_text, glob_data, fontsize=self._style["sfs"]) - 0.05
)
# get param_width, but 0 for gates with array params or circuits in params
if (
hasattr(op, "params")
and len(op.params) > 0
and not any(isinstance(param, np.ndarray) for param in op.params)
and not any(isinstance(param, QuantumCircuit) for param in op.params)
):
param_text = get_param_str(op, "mpl", ndigits=3)
if isinstance(op, Initialize):
param_text = f"$[{param_text.replace('$', '')}]$"
node_data[node].param_text = param_text
raw_param_width = self._get_text_width(
param_text, glob_data, fontsize=self._style["sfs"], param=True
)
param_width = raw_param_width + 0.08
else:
param_width = raw_param_width = 0.0
# get gate_width for sidetext symmetric gates
if isinstance(op, RZZGate) or isinstance(base_type, (U1Gate, PhaseGate, RZZGate)):
if isinstance(base_type, PhaseGate):
gate_text = "P"
raw_gate_width = (
self._get_text_width(
gate_text + " ()", glob_data, fontsize=self._style["sfs"]
)
+ raw_param_width
)
gate_width = (raw_gate_width + 0.08) * 1.58
# Check if a ControlFlowOp - node_data load for these gates is done here
elif isinstance(node.op, ControlFlowOp):
self._flow_drawers[node] = []
node_data[node].width = []
node_data[node].nest_depth = 0
gate_width = 0.0
# Get the list of circuits to iterate over from the blocks
circuit_list = list(node.op.blocks)
# params is [indexset, loop_param, circuit] for for_loop,
# op.cases_specifier() returns jump tuple and circuit for switch/case
if isinstance(op, ForLoopOp):
node_data[node].indexset = op.params[0]
elif isinstance(op, SwitchCaseOp):
node_data[node].jump_values = []
cases = list(op.cases_specifier())
# Create an empty circuit at the head of the circuit_list if a Switch box
circuit_list.insert(0, cases[0][1].copy_empty_like())
for jump_values, _ in cases:
node_data[node].jump_values.append(jump_values)
# Now process the circuits inside the ControlFlowOps
for circ_num, circuit in enumerate(circuit_list):
raw_gate_width = 0.0
# Depth of nested ControlFlowOp used for color of box
if self._flow_parent is not None:
node_data[node].nest_depth = node_data[self._flow_parent].nest_depth + 1
# Update the wire_map with the qubits from the inner circuit
flow_wire_map = {
inner: wire_map[outer]
for outer, inner in zip(self._qubits, circuit.qubits)
if inner not in wire_map
}
if not flow_wire_map:
flow_wire_map = wire_map
# Get the layered node lists and instantiate a new drawer class for
# the circuit inside the ControlFlowOp.
qubits, clbits, nodes = _get_layered_instructions(
circuit, wire_map=flow_wire_map
)
flow_drawer = MatplotlibDrawer(
qubits,
clbits,
nodes,
circuit,
style=self._style,
plot_barriers=self._plot_barriers,
fold=self._fold,
cregbundle=self._cregbundle,
)
# flow_parent is the parent of the new class instance
flow_drawer._flow_parent = node
flow_drawer._flow_wire_map = flow_wire_map
self._flow_drawers[node].append(flow_drawer)
# Recursively call _get_layer_widths for the circuit inside the ControlFlowOp
flow_widths = flow_drawer._get_layer_widths(node_data, wire_map, glob_data)
layer_widths.update(flow_widths)
# Gates within a SwitchCaseOp need to know which case they are in
for flow_layer in nodes:
for flow_node in flow_layer:
if isinstance(node.op, SwitchCaseOp):
node_data[flow_node].case_num = circ_num
# Add up the width values of the same flow_parent that are not -1
# to get the raw_gate_width
for width, layer_num, flow_parent in flow_widths.values():
if layer_num != -1 and flow_parent == flow_drawer._flow_parent:
raw_gate_width += width
# Need extra incr of 1.0 for else and case boxes
gate_width += raw_gate_width + (1.0 if circ_num > 0 else 0.0)
# Minor adjustment so else and case section gates align with indexes
if circ_num > 0:
raw_gate_width += 0.045
node_data[node].width.append(raw_gate_width)
# Otherwise, standard gate or multiqubit gate
else:
raw_gate_width = self._get_text_width(
gate_text, glob_data, fontsize=self._style["fs"]
)
gate_width = raw_gate_width + 0.10
# add .21 for the qubit numbers on the left of the multibit gates
if len(node.qargs) - num_ctrl_qubits > 1:
gate_width += 0.21
box_width = max(gate_width, ctrl_width, param_width, WID)
if box_width > widest_box:
widest_box = box_width
if not isinstance(node.op, ControlFlowOp):
node_data[node].width = max(raw_gate_width, raw_param_width)
for node in layer:
layer_widths[node][0] = int(widest_box) + 1
return layer_widths
def _set_bit_reg_info(self, wire_map, qubits_dict, clbits_dict, glob_data):
"""Get all the info for drawing bit/reg names and numbers"""
longest_wire_label_width = 0
glob_data["n_lines"] = 0
initial_qbit = " |0>" if self._initial_state else ""
initial_cbit = " 0" if self._initial_state else ""
idx = 0
pos = y_off = -len(self._qubits) + 1
for ii, wire in enumerate(wire_map):
# if it's a creg, register is the key and just load the index
if isinstance(wire, ClassicalRegister):
# If wire came from ControlFlowOp and not in clbits, don't draw it
if wire[0] not in self._clbits:
continue
register = wire
index = wire_map[wire]
# otherwise, get the register from find_bit and use bit_index if
# it's a bit, or the index of the bit in the register if it's a reg
else:
# If wire came from ControlFlowOp and not in qubits or clbits, don't draw it
if wire not in self._qubits + self._clbits:
continue
register, bit_index, reg_index = get_bit_reg_index(self._circuit, wire)
index = bit_index if register is None else reg_index
wire_label = get_wire_label(
"mpl", register, index, layout=self._layout, cregbundle=self._cregbundle
)
initial_bit = initial_qbit if isinstance(wire, Qubit) else initial_cbit
# for cregs with cregbundle on, don't use math formatting, which means
# no italics
if isinstance(wire, Qubit) or register is None or not self._cregbundle:
wire_label = "$" + wire_label + "$"
wire_label += initial_bit
reg_size = (
0 if register is None or isinstance(wire, ClassicalRegister) else register.size
)
reg_remove_under = 0 if reg_size < 2 else 1
text_width = (
self._get_text_width(
wire_label, glob_data, self._style["fs"], reg_remove_under=reg_remove_under
)
* 1.15
)
if text_width > longest_wire_label_width:
longest_wire_label_width = text_width
if isinstance(wire, Qubit):
pos = -ii
qubits_dict[ii] = {
"y": pos,
"wire_label": wire_label,
}
glob_data["n_lines"] += 1
else:
if (
not self._cregbundle
or register is None
or (self._cregbundle and isinstance(wire, ClassicalRegister))
):
glob_data["n_lines"] += 1
idx += 1
pos = y_off - idx
clbits_dict[ii] = {
"y": pos,
"wire_label": wire_label,
"register": register,
}
glob_data["x_offset"] = -1.2 + longest_wire_label_width
def _get_coords(
self,
node_data,
wire_map,
layer_widths,
qubits_dict,
clbits_dict,
glob_data,
flow_parent=None,
is_not_first_block=None,
):
"""Load all the coordinate info needed to place the gates on the drawing."""
prev_x_index = -1
for layer in self._nodes:
curr_x_index = prev_x_index + 1
l_width = []
for node in layer:
# For gates inside if, else, while, or case set the x_index and if it's an
# else or case increment by if width. For additional cases increment by
# width of previous cases.
if flow_parent is not None:
node_data[node].x_index = node_data[flow_parent].x_index + curr_x_index + 1
if is_not_first_block:
# Add index space for else or first case if switch/case
node_data[node].x_index += int(node_data[flow_parent].width[0]) + 1
# Add index space for remaining cases for switch/case
if node_data[node].case_num > 1:
for width in node_data[flow_parent].width[1 : node_data[node].case_num]:
node_data[node].x_index += int(width) + 1
# get qubit indexes
q_indxs = []
for qarg in node.qargs:
if qarg in self._qubits:
q_indxs.append(wire_map[qarg])
# get clbit indexes
c_indxs = []
for carg in node.cargs:
if carg in self._clbits:
register = get_bit_register(self._circuit, carg)
if register is not None and self._cregbundle:
c_indxs.append(wire_map[register])
else:
c_indxs.append(wire_map[carg])
flow_op = isinstance(node.op, ControlFlowOp)
if flow_parent is not None:
node_data[node].inside_flow = True
x_index = node_data[node].x_index
else:
node_data[node].inside_flow = False
x_index = curr_x_index
# qubit coordinates
node_data[node].q_xy = [
self._plot_coord(
x_index,
qubits_dict[ii]["y"],
layer_widths[node][0],
glob_data,
flow_op,
)
for ii in q_indxs
]
# clbit coordinates
node_data[node].c_xy = [
self._plot_coord(
x_index,
clbits_dict[ii]["y"],
layer_widths[node][0],
glob_data,
flow_op,
)
for ii in c_indxs
]
# update index based on the value from plotting
if flow_parent is None:
curr_x_index = glob_data["next_x_index"]
l_width.append(layer_widths[node][0])
node_data[node].x_index = x_index
# adjust the column if there have been barriers encountered, but not plotted
barrier_offset = 0
if not self._plot_barriers:
# only adjust if everything in the layer wasn't plotted
barrier_offset = (
-1 if all(getattr(nd.op, "_directive", False) for nd in layer) else 0
)
prev_x_index = curr_x_index + max(l_width) + barrier_offset - 1
return prev_x_index + 1
def _get_text_width(self, text, glob_data, fontsize, param=False, reg_remove_under=None):
"""Compute the width of a string in the default font"""
from pylatexenc.latex2text import LatexNodes2Text
if not text:
return 0.0
math_mode_match = self._mathmode_regex.search(text)
num_underscores = 0
num_carets = 0
if math_mode_match:
math_mode_text = math_mode_match.group(1)
num_underscores = math_mode_text.count("_")
num_carets = math_mode_text.count("^")
text = LatexNodes2Text().latex_to_text(text.replace("$$", ""))
# If there are subscripts or superscripts in mathtext string
# we need to account for that spacing by manually removing
# from text string for text length
# if it's a register and there's a subscript at the end,
# remove 1 underscore, otherwise don't remove any
if reg_remove_under is not None:
num_underscores = reg_remove_under
if num_underscores:
text = text.replace("_", "", num_underscores)
if num_carets:
text = text.replace("^", "", num_carets)
# This changes hyphen to + to match width of math mode minus sign.
if param:
text = text.replace("-", "+")
f = 0 if fontsize == self._style["fs"] else 1
sum_text = 0.0
for c in text:
try:
sum_text += self._char_list[c][f]
except KeyError:
# if non-ASCII char, use width of 'c', an average size
sum_text += self._char_list["c"][f]
if f == 1:
sum_text *= glob_data["subfont_factor"]
return sum_text
def _draw_regs_wires(self, num_folds, xmax, max_x_index, qubits_dict, clbits_dict, glob_data):
"""Draw the register names and numbers, wires, and vertical lines at the ends"""
for fold_num in range(num_folds + 1):
# quantum registers
for qubit in qubits_dict.values():
qubit_label = qubit["wire_label"]
y = qubit["y"] - fold_num * (glob_data["n_lines"] + 1)
self._ax.text(
glob_data["x_offset"] - 0.2,
y,
qubit_label,
ha="right",
va="center",
fontsize=1.25 * self._style["fs"],
color=self._style["tc"],
clip_on=True,
zorder=PORDER_TEXT,
)
# draw the qubit wire
self._line([glob_data["x_offset"], y], [xmax, y], zorder=PORDER_REGLINE)
# classical registers
this_clbit_dict = {}
for clbit in clbits_dict.values():
y = clbit["y"] - fold_num * (glob_data["n_lines"] + 1)
if y not in this_clbit_dict.keys():
this_clbit_dict[y] = {
"val": 1,
"wire_label": clbit["wire_label"],
"register": clbit["register"],
}
else:
this_clbit_dict[y]["val"] += 1
for y, this_clbit in this_clbit_dict.items():
# cregbundle
if self._cregbundle and this_clbit["register"] is not None:
self._ax.plot(
[glob_data["x_offset"] + 0.2, glob_data["x_offset"] + 0.3],
[y - 0.1, y + 0.1],
color=self._style["cc"],
zorder=PORDER_REGLINE,
)
self._ax.text(
glob_data["x_offset"] + 0.1,
y + 0.1,
str(this_clbit["register"].size),
ha="left",
va="bottom",
fontsize=0.8 * self._style["fs"],
color=self._style["tc"],
clip_on=True,
zorder=PORDER_TEXT,
)
self._ax.text(
glob_data["x_offset"] - 0.2,
y,
this_clbit["wire_label"],
ha="right",
va="center",
fontsize=1.25 * self._style["fs"],
color=self._style["tc"],
clip_on=True,
zorder=PORDER_TEXT,
)
# draw the clbit wire
self._line(
[glob_data["x_offset"], y],
[xmax, y],
lc=self._style["cc"],
ls=self._style["cline"],
zorder=PORDER_REGLINE,
)
# lf vertical line at either end
feedline_r = num_folds > 0 and num_folds > fold_num
feedline_l = fold_num > 0
if feedline_l or feedline_r:
xpos_l = glob_data["x_offset"] - 0.01
xpos_r = self._fold + glob_data["x_offset"] + 0.1
ypos1 = -fold_num * (glob_data["n_lines"] + 1)
ypos2 = -(fold_num + 1) * (glob_data["n_lines"]) - fold_num + 1
if feedline_l:
self._ax.plot(
[xpos_l, xpos_l],
[ypos1, ypos2],
color=self._style["lc"],
linewidth=self._lwidth15,
zorder=PORDER_REGLINE,
)
if feedline_r:
self._ax.plot(
[xpos_r, xpos_r],
[ypos1, ypos2],
color=self._style["lc"],
linewidth=self._lwidth15,
zorder=PORDER_REGLINE,
)
# Mask off any lines or boxes in the bit label area to clean up
# from folding for ControlFlow and other wrapping gates
box = glob_data["patches_mod"].Rectangle(
xy=(glob_data["x_offset"] - 0.1, -fold_num * (glob_data["n_lines"] + 1) + 0.5),
width=-25.0,
height=-(fold_num + 1) * (glob_data["n_lines"] + 1),
fc=self._style["bg"],
ec=self._style["bg"],
linewidth=self._lwidth15,
zorder=PORDER_MASK,
)
self._ax.add_patch(box)
# draw index number
if self._style["index"]:
for layer_num in range(max_x_index):
if self._fold > 0:
x_coord = layer_num % self._fold + glob_data["x_offset"] + 0.53
y_coord = -(layer_num // self._fold) * (glob_data["n_lines"] + 1) + 0.65
else:
x_coord = layer_num + glob_data["x_offset"] + 0.53
y_coord = 0.65
self._ax.text(
x_coord,
y_coord,
str(layer_num + 1),
ha="center",
va="center",
fontsize=self._style["sfs"],
color=self._style["tc"],
clip_on=True,
zorder=PORDER_TEXT,
)
def _add_nodes_and_coords(
self, nodes, node_data, wire_map, layer_widths, qubits_dict, clbits_dict, glob_data
):
"""Add the nodes from ControlFlowOps and their coordinates to the main circuit"""
for flow_drawers in self._flow_drawers.values():
for i, flow_drawer in enumerate(flow_drawers):
nodes += flow_drawer._nodes
flow_drawer._get_coords(
node_data,
flow_drawer._flow_wire_map,
layer_widths,
qubits_dict,
clbits_dict,
glob_data,
flow_parent=flow_drawer._flow_parent,
is_not_first_block=(i > 0),
)
# Recurse for ControlFlowOps inside the flow_drawer
flow_drawer._add_nodes_and_coords(
nodes, node_data, wire_map, layer_widths, qubits_dict, clbits_dict, glob_data
)
def _draw_ops(
self,
nodes,
node_data,
wire_map,
layer_widths,
qubits_dict,
clbits_dict,
glob_data,
verbose=False,
):
"""Draw the gates in the circuit"""
# Add the nodes from all the ControlFlowOps and their coordinates to the main nodes
self._add_nodes_and_coords(
nodes, node_data, wire_map, layer_widths, qubits_dict, clbits_dict, glob_data
)
prev_x_index = -1
for layer in nodes:
l_width = []
curr_x_index = prev_x_index + 1
# draw the gates in this layer
for node in layer:
op = node.op
self._get_colors(node, node_data)
if verbose:
print(op)
# add conditional
if getattr(op, "condition", None) or isinstance(op, SwitchCaseOp):
cond_xy = [
self._plot_coord(
node_data[node].x_index,
clbits_dict[ii]["y"],
layer_widths[node][0],
glob_data,
isinstance(op, ControlFlowOp),
)
for ii in clbits_dict