-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
Copy pathtext.py
1434 lines (1198 loc) · 50.6 KB
/
text.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.
"""
A module for drawing circuits in ascii art or some other text representation
"""
from warnings import warn
from shutil import get_terminal_size
import sys
from qiskit.circuit import Clbit
from qiskit.circuit import ControlledGate
from qiskit.circuit import Reset
from qiskit.circuit import Measure
from qiskit.circuit.library.standard_gates import IGate, RZZGate, SwapGate, SXGate, SXdgGate
from qiskit.circuit.tools.pi_check import pi_check
from qiskit.visualization.utils import get_gate_ctrl_text, get_param_str, get_bit_label
from .exceptions import VisualizationError
class TextDrawerCregBundle(VisualizationError):
"""The parameter "cregbundle" was set to True in an impossible situation. For example,
a node needs to refer to individual classical wires'"""
pass
class TextDrawerEncodingError(VisualizationError):
"""A problem with encoding"""
pass
class DrawElement:
"""An element is an operation that needs to be drawn."""
def __init__(self, label=None):
self._width = None
self.label = self.mid_content = label
self.top_format = self.mid_format = self.bot_format = "%s"
self.top_connect = self.bot_connect = " "
self.top_pad = self._mid_padding = self.bot_pad = " "
self.mid_bck = self.top_bck = self.bot_bck = " "
self.bot_connector = {}
self.top_connector = {}
self.right_fill = self.left_fill = self.layer_width = 0
self.wire_label = ""
@property
def top(self):
"""Constructs the top line of the element"""
if (self.width % 2) == 0 and len(self.top_format) % 2 == 1 and len(self.top_connect) == 1:
ret = self.top_format % (self.top_pad + self.top_connect).center(
self.width, self.top_pad
)
else:
ret = self.top_format % self.top_connect.center(self.width, self.top_pad)
if self.right_fill:
ret = ret.ljust(self.right_fill, self.top_pad)
if self.left_fill:
ret = ret.rjust(self.left_fill, self.top_pad)
ret = ret.center(self.layer_width, self.top_bck)
return ret
@property
def mid(self):
"""Constructs the middle line of the element"""
ret = self.mid_format % self.mid_content.center(self.width, self._mid_padding)
if self.right_fill:
ret = ret.ljust(self.right_fill, self._mid_padding)
if self.left_fill:
ret = ret.rjust(self.left_fill, self._mid_padding)
ret = ret.center(self.layer_width, self.mid_bck)
return ret
@property
def bot(self):
"""Constructs the bottom line of the element"""
if (self.width % 2) == 0 and len(self.top_format) % 2 == 1:
ret = self.bot_format % (self.bot_pad + self.bot_connect).center(
self.width, self.bot_pad
)
else:
ret = self.bot_format % self.bot_connect.center(self.width, self.bot_pad)
if self.right_fill:
ret = ret.ljust(self.right_fill, self.bot_pad)
if self.left_fill:
ret = ret.rjust(self.left_fill, self.bot_pad)
ret = ret.center(self.layer_width, self.bot_bck)
return ret
@property
def length(self):
"""Returns the length of the element, including the box around."""
return max(len(self.top), len(self.mid), len(self.bot))
@property
def width(self):
"""Returns the width of the label, including padding"""
if self._width:
return self._width
return len(self.mid_content)
@width.setter
def width(self, value):
self._width = value
def connect(self, wire_char, where, label=None):
"""Connects boxes and elements using wire_char and setting proper connectors.
Args:
wire_char (char): For example '║' or '│'.
where (list["top", "bot"]): Where the connector should be set.
label (string): Some connectors have a label (see cu1, for example).
"""
if "top" in where and self.top_connector:
self.top_connect = self.top_connector[wire_char]
if "bot" in where and self.bot_connector:
self.bot_connect = self.bot_connector[wire_char]
if label:
self.top_format = self.top_format[:-1] + (label if label else "")
class BoxOnClWire(DrawElement):
"""Draws a box on the classical wire.
::
top: ┌───┐ ┌───┐
mid: ╡ A ╞ ══╡ A ╞══
bot: └───┘ └───┘
"""
def __init__(self, label="", top_connect="─", bot_connect="─"):
super().__init__(label)
self.top_format = "┌─%s─┐"
self.mid_format = "╡ %s ╞"
self.bot_format = "└─%s─┘"
self.top_pad = self.bot_pad = "─"
self.mid_bck = "═"
self.top_connect = top_connect
self.bot_connect = bot_connect
self.mid_content = label
class BoxOnQuWire(DrawElement):
"""Draws a box on the quantum wire.
::
top: ┌───┐ ┌───┐
mid: ┤ A ├ ──┤ A ├──
bot: └───┘ └───┘
"""
def __init__(self, label="", top_connect="─", conditional=False):
super().__init__(label)
self.top_format = "┌─%s─┐"
self.mid_format = "┤ %s ├"
self.bot_format = "└─%s─┘"
self.top_pad = self.bot_pad = self.mid_bck = "─"
self.top_connect = top_connect
self.bot_connect = "╥" if conditional else "─"
self.mid_content = label
self.top_connector = {"│": "┴"}
self.bot_connector = {"│": "┬"}
class MeasureTo(DrawElement):
"""The element on the classic wire to which the measure is performed.
::
top: ║ ║
mid: ═╩═ ═══╩═══
bot:
"""
def __init__(self, label=""):
super().__init__()
self.top_connect = " ║ "
self.mid_content = "═╩═"
self.bot_connect = label
self.mid_bck = "═"
class MeasureFrom(BoxOnQuWire):
"""The element on the quantum wire in which the measure is performed.
::
top: ┌─┐ ┌─┐
mid: ┤M├ ───┤M├───
bot: └╥┘ └╥┘
"""
def __init__(self):
super().__init__()
self.top_format = self.mid_format = self.bot_format = "%s"
self.top_connect = "┌─┐"
self.mid_content = "┤M├"
self.bot_connect = "└╥┘"
self.top_pad = self.bot_pad = " "
self._mid_padding = "─"
class MultiBox(DrawElement):
"""Elements that are drawn over multiple wires."""
def center_label(self, input_length, order):
"""In multi-bit elements, the label is centered vertically.
Args:
input_length (int): Rhe amount of wires affected.
order (int): Which middle element is this one?
"""
if input_length == order == 0:
self.top_connect = self.label
return
location_in_the_box = "*".center(input_length * 2 - 1).index("*") + 1
top_limit = order * 2 + 2
bot_limit = top_limit + 2
if top_limit <= location_in_the_box < bot_limit:
if location_in_the_box == top_limit:
self.top_connect = self.label
elif location_in_the_box == top_limit + 1:
self.mid_content = self.label
else:
self.bot_connect = self.label
@property
def width(self):
"""Returns the width of the label, including padding"""
if self._width:
return self._width
return len(self.label)
class BoxOnQuWireTop(MultiBox, BoxOnQuWire):
"""Draws the top part of a box that affects more than one quantum wire"""
def __init__(self, label="", top_connect=None, wire_label=""):
super().__init__(label)
self.wire_label = wire_label
self.bot_connect = self.bot_pad = " "
self.mid_content = "" # The label will be put by some other part of the box.
self.left_fill = len(self.wire_label)
self.top_format = "┌─" + "s".center(self.left_fill + 1, "─") + "─┐"
self.top_format = self.top_format.replace("s", "%s")
self.mid_format = f"┤{self.wire_label} %s ├"
self.bot_format = f"│{self.bot_pad * self.left_fill} %s │"
self.top_connect = top_connect if top_connect else "─"
class BoxOnWireMid(MultiBox):
"""A generic middle box"""
def __init__(self, label, input_length, order, wire_label=""):
super().__init__(label)
self.top_pad = self.bot_pad = self.top_connect = self.bot_connect = " "
self.wire_label = wire_label
self.left_fill = len(self.wire_label)
self.top_format = f"│{self.top_pad * self.left_fill} %s │"
self.bot_format = f"│{self.bot_pad * self.left_fill} %s │"
self.top_connect = self.bot_connect = self.mid_content = ""
self.center_label(input_length, order)
class BoxOnQuWireMid(BoxOnWireMid, BoxOnQuWire):
"""Draws the middle part of a box that affects more than one quantum wire"""
def __init__(self, label, input_length, order, wire_label="", control_label=None):
super().__init__(label, input_length, order, wire_label=wire_label)
if control_label:
self.mid_format = f"{control_label}{self.wire_label} %s ├"
else:
self.mid_format = f"┤{self.wire_label} %s ├"
class BoxOnQuWireBot(MultiBox, BoxOnQuWire):
"""Draws the bottom part of a box that affects more than one quantum wire"""
def __init__(self, label, input_length, bot_connect=None, wire_label="", conditional=False):
super().__init__(label)
self.wire_label = wire_label
self.top_pad = " "
self.left_fill = len(self.wire_label)
self.top_format = f"│{self.top_pad * self.left_fill} %s │"
self.mid_format = f"┤{self.wire_label} %s ├"
self.bot_format = "└─" + "s".center(self.left_fill + 1, "─") + "─┘"
self.bot_format = self.bot_format.replace("s", "%s")
bot_connect = bot_connect if bot_connect else "─"
self.bot_connect = "╥" if conditional else bot_connect
self.mid_content = self.top_connect = ""
if input_length <= 2:
self.top_connect = label
class BoxOnClWireTop(MultiBox, BoxOnClWire):
"""Draws the top part of a conditional box that affects more than one classical wire"""
def __init__(self, label="", top_connect=None, wire_label=""):
super().__init__(label)
self.wire_label = wire_label
self.mid_content = "" # The label will be put by some other part of the box.
self.bot_format = "│ %s │"
self.top_connect = top_connect if top_connect else "─"
self.bot_connect = self.bot_pad = " "
class BoxOnClWireMid(BoxOnWireMid, BoxOnClWire):
"""Draws the middle part of a conditional box that affects more than one classical wire"""
def __init__(self, label, input_length, order, wire_label="", **_):
super().__init__(label, input_length, order, wire_label=wire_label)
self.mid_format = f"╡{self.wire_label} %s ╞"
class BoxOnClWireBot(MultiBox, BoxOnClWire):
"""Draws the bottom part of a conditional box that affects more than one classical wire"""
def __init__(self, label, input_length, bot_connect="─", wire_label="", **_):
super().__init__(label)
self.wire_label = wire_label
self.left_fill = len(self.wire_label)
self.top_pad = " "
self.bot_pad = "─"
self.top_format = f"│{self.top_pad * self.left_fill} %s │"
self.mid_format = f"╡{self.wire_label} %s ╞"
self.bot_format = "└─" + "s".center(self.left_fill + 1, "─") + "─┘"
self.bot_format = self.bot_format.replace("s", "%s")
bot_connect = bot_connect if bot_connect else "─"
self.bot_connect = bot_connect
self.mid_content = self.top_connect = ""
if input_length <= 2:
self.top_connect = label
class DirectOnQuWire(DrawElement):
"""
Element to the wire (without the box).
"""
def __init__(self, label=""):
super().__init__(label)
self.top_format = " %s "
self.mid_format = "─%s─"
self.bot_format = " %s "
self._mid_padding = self.mid_bck = "─"
self.top_connector = {"│": "│"}
self.bot_connector = {"│": "│"}
class Barrier(DirectOnQuWire):
"""Draws a barrier.
::
top: ░ ░
mid: ─░─ ───░───
bot: ░ ░
"""
def __init__(self, label=""):
super().__init__("░")
self.top_connect = "░"
self.bot_connect = "░"
self.top_connector = {}
self.bot_connector = {}
class Ex(DirectOnQuWire):
"""Draws an X (usually with a connector). E.g. the top part of a swap gate.
::
top:
mid: ─X─ ───X───
bot: │ │
"""
def __init__(self, bot_connect=" ", top_connect=" ", conditional=False):
super().__init__("X")
self.bot_connect = "║" if conditional else bot_connect
self.top_connect = top_connect
class ResetDisplay(DirectOnQuWire):
"""Draws a reset gate"""
def __init__(self, conditional=False):
super().__init__("|0>")
if conditional:
self.bot_connect = "║"
class Bullet(DirectOnQuWire):
"""Draws a bullet (usually with a connector). E.g. the top part of a CX gate.
::
top:
mid: ─■─ ───■───
bot: │ │
"""
def __init__(self, top_connect="", bot_connect="", conditional=False, label=None, bottom=False):
super().__init__("■")
self.top_connect = top_connect
self.bot_connect = "║" if conditional else bot_connect
if label and bottom:
self.bot_connect = label
elif label:
self.top_connect = label
self.mid_bck = "─"
class OpenBullet(DirectOnQuWire):
"""Draws an open bullet (usually with a connector). E.g. the top part of a CX gate.
::
top:
mid: ─o─ ───o───
bot: │ │
"""
def __init__(self, top_connect="", bot_connect="", conditional=False, label=None, bottom=False):
super().__init__("o")
self.top_connect = top_connect
self.bot_connect = "║" if conditional else bot_connect
if label and bottom:
self.bot_connect = label
elif label:
self.top_connect = label
self.mid_bck = "─"
class DirectOnClWire(DrawElement):
"""
Element to the classical wire (without the box).
"""
def __init__(self, label=""):
super().__init__(label)
self.top_format = " %s "
self.mid_format = "═%s═"
self.bot_format = " %s "
self._mid_padding = self.mid_bck = "═"
self.top_connector = {"│": "│"}
self.bot_connector = {"│": "│"}
class ClBullet(DirectOnClWire):
"""Draws a bullet on classical wire (usually with a connector). E.g. the top part of a CX gate.
::
top:
mid: ═■═ ═══■═══
bot: │ │
"""
def __init__(self, top_connect="", bot_connect="", conditional=False, label=None, bottom=False):
super().__init__("■")
self.top_connect = top_connect
self.bot_connect = "║" if conditional else bot_connect
if label and bottom:
self.bot_connect = label
elif label:
self.top_connect = label
self.mid_bck = "═"
class ClOpenBullet(DirectOnClWire):
"""Draws an open bullet on classical wire (usually with a connector). E.g. the top part of a CX gate.
::
top:
mid: ═o═ ═══o═══
bot: │ │
"""
def __init__(self, top_connect="", bot_connect="", conditional=False, label=None, bottom=False):
super().__init__("o")
self.top_connect = top_connect
self.bot_connect = "║" if conditional else bot_connect
if label and bottom:
self.bot_connect = label
elif label:
self.top_connect = label
self.mid_bck = "═"
class EmptyWire(DrawElement):
"""This element is just the wire, with no operations."""
def __init__(self, wire):
super().__init__(wire)
self._mid_padding = self.mid_bck = wire
@staticmethod
def fillup_layer(layer, first_clbit):
"""Given a layer, replace the Nones in it with EmptyWire elements.
Args:
layer (list): The layer that contains Nones.
first_clbit (int): The first wire that is classic.
Returns:
list: The new layer, with no Nones.
"""
for nones in [i for i, x in enumerate(layer) if x is None]:
layer[nones] = EmptyWire("═") if nones >= first_clbit else EmptyWire("─")
return layer
class BreakWire(DrawElement):
"""This element is used to break the drawing in several pages."""
def __init__(self, arrow_char):
super().__init__()
self.top_format = self.mid_format = self.bot_format = "%s"
self.top_connect = arrow_char
self.mid_content = arrow_char
self.bot_connect = arrow_char
@staticmethod
def fillup_layer(layer_length, arrow_char):
"""Creates a layer with BreakWire elements.
Args:
layer_length (int): The length of the layer to create
arrow_char (char): The char used to create the BreakWire element.
Returns:
list: The new layer.
"""
breakwire_layer = []
for _ in range(layer_length):
breakwire_layer.append(BreakWire(arrow_char))
return breakwire_layer
class InputWire(DrawElement):
"""This element is the label and the initial value of a wire."""
def __init__(self, label):
super().__init__(label)
@staticmethod
def fillup_layer(names):
"""Creates a layer with InputWire elements.
Args:
names (list): List of names for the wires.
Returns:
list: The new layer
"""
longest = max(len(name) for name in names)
inputs_wires = []
for name in names:
inputs_wires.append(InputWire(name.rjust(longest)))
return inputs_wires
class TextDrawing:
"""The text drawing"""
def __init__(
self,
qubits,
clbits,
nodes,
reverse_bits=False,
plotbarriers=True,
line_length=None,
vertical_compression="high",
layout=None,
initial_state=True,
cregbundle=False,
global_phase=None,
encoding=None,
qregs=None,
cregs=None,
):
self.qubits = qubits
self.clbits = clbits
self.qregs = qregs
self.cregs = cregs
self.nodes = nodes
self.reverse_bits = reverse_bits
self.layout = layout
self.initial_state = initial_state
self.cregbundle = cregbundle
self.global_phase = global_phase
self.plotbarriers = plotbarriers
self.line_length = line_length
if vertical_compression not in ["high", "medium", "low"]:
raise ValueError("Vertical compression can only be 'high', 'medium', or 'low'")
self.vertical_compression = vertical_compression
if encoding:
self.encoding = encoding
else:
if sys.stdout.encoding:
self.encoding = sys.stdout.encoding
else:
self.encoding = "utf8"
self.bit_locations = {
bit: {"register": register, "index": index}
for register in cregs + qregs
for index, bit in enumerate(register)
}
for index, bit in list(enumerate(qubits)) + list(enumerate(clbits)):
if bit not in self.bit_locations:
self.bit_locations[bit] = {"register": None, "index": index}
def __str__(self):
return self.single_string()
def _repr_html_(self):
return (
'<pre style="word-wrap: normal;'
"white-space: pre;"
"background: #fff0;"
"line-height: 1.1;"
'font-family: "Courier New",Courier,monospace">'
"%s</pre>" % self.single_string()
)
def __repr__(self):
return self.single_string()
def single_string(self):
"""Creates a long string with the ascii art.
Returns:
str: The lines joined by a newline (``\\n``)
"""
try:
return "\n".join(self.lines()).encode(self.encoding).decode(self.encoding)
except (UnicodeEncodeError, UnicodeDecodeError):
warn(
"The encoding %s has a limited charset. Consider a different encoding in your "
"environment. UTF-8 is being used instead" % self.encoding,
RuntimeWarning,
)
self.encoding = "utf-8"
return "\n".join(self.lines()).encode(self.encoding).decode(self.encoding)
def dump(self, filename, encoding=None):
"""Dumps the ascii art in the file.
Args:
filename (str): File to dump the ascii art.
encoding (str): Optional. Force encoding, instead of self.encoding.
"""
with open(filename, mode="w", encoding=encoding or self.encoding) as text_file:
text_file.write(self.single_string())
def lines(self, line_length=None):
"""Generates a list with lines. These lines form the text drawing.
Args:
line_length (int): Optional. Breaks the circuit drawing to this length. This is
useful when the drawing does not fit in the console. If
None (default), it will try to guess the console width using
shutil.get_terminal_size(). If you don't want pagination
at all, set line_length=-1.
Returns:
list: A list of lines with the text drawing.
"""
if line_length is None:
line_length = self.line_length
if not line_length:
if ("ipykernel" in sys.modules) and ("spyder" not in sys.modules):
line_length = 80
else:
line_length, _ = get_terminal_size()
noqubits = len(self.qubits)
try:
layers = self.build_layers()
except TextDrawerCregBundle:
self.cregbundle = False
warn(
'The parameter "cregbundle" was disabled, since an instruction needs to refer to '
"individual classical wires",
RuntimeWarning,
2,
)
layers = self.build_layers()
layer_groups = [[]]
rest_of_the_line = line_length
for layerno, layer in enumerate(layers):
# Replace the Nones with EmptyWire
layers[layerno] = EmptyWire.fillup_layer(layer, noqubits)
TextDrawing.normalize_width(layer)
if line_length == -1:
# Do not use pagination (aka line breaking. aka ignore line_length).
layer_groups[-1].append(layer)
continue
# chop the layer to the line_length (pager)
layer_length = layers[layerno][0].length
if layer_length < rest_of_the_line:
layer_groups[-1].append(layer)
rest_of_the_line -= layer_length
else:
layer_groups[-1].append(BreakWire.fillup_layer(len(layer), "»"))
# New group
layer_groups.append([BreakWire.fillup_layer(len(layer), "«")])
rest_of_the_line = line_length - layer_groups[-1][-1][0].length
layer_groups[-1].append(
InputWire.fillup_layer(self.wire_names(with_initial_state=False))
)
rest_of_the_line -= layer_groups[-1][-1][0].length
layer_groups[-1].append(layer)
rest_of_the_line -= layer_groups[-1][-1][0].length
lines = []
if self.global_phase:
lines.append("global phase: %s" % pi_check(self.global_phase, ndigits=5))
for layer_group in layer_groups:
wires = list(zip(*layer_group))
lines += self.draw_wires(wires)
return lines
def wire_names(self, with_initial_state=False):
"""Returns a list of names for each wire.
Args:
with_initial_state (bool): Optional (Default: False). If true, adds
the initial value to the name.
Returns:
List: The list of wire names.
"""
if with_initial_state:
initial_qubit_value = "|0>"
initial_clbit_value = "0 "
else:
initial_qubit_value = ""
initial_clbit_value = ""
# quantum register
qubit_labels = []
for reg in self.qubits:
register = self.bit_locations[reg]["register"]
index = self.bit_locations[reg]["index"]
qubit_label = get_bit_label("text", register, index, qubit=True, layout=self.layout)
qubit_label += ": " if self.layout is None else " "
qubit_labels.append(qubit_label + initial_qubit_value)
# classical register
clbit_labels = []
if self.clbits:
prev_creg = None
for reg in self.clbits:
register = self.bit_locations[reg]["register"]
index = self.bit_locations[reg]["index"]
clbit_label = get_bit_label(
"text", register, index, qubit=False, cregbundle=self.cregbundle
)
if register is None or not self.cregbundle or prev_creg != register:
cregb_add = (
str(register.size) + "/" if self.cregbundle and register is not None else ""
)
clbit_labels.append(clbit_label + ": " + initial_clbit_value + cregb_add)
prev_creg = register
return qubit_labels + clbit_labels
def should_compress(self, top_line, bot_line):
"""Decides if the top_line and bot_line should be merged,
based on `self.vertical_compression`."""
if self.vertical_compression == "high":
return True
if self.vertical_compression == "low":
return False
for top, bot in zip(top_line, bot_line):
if top in ["┴", "╨"] and bot in ["┬", "╥"]:
return False
for line in (bot_line, top_line):
no_spaces = line.replace(" ", "")
if len(no_spaces) > 0 and all(c.isalpha() or c.isnumeric() for c in no_spaces):
return False
return True
def draw_wires(self, wires):
"""Given a list of wires, creates a list of lines with the text drawing.
Args:
wires (list): A list of wires with nodes.
Returns:
list: A list of lines with the text drawing.
"""
lines = []
bot_line = None
for wire in wires:
# TOP
top_line = ""
for node in wire:
top_line += node.top
if bot_line is None:
lines.append(top_line)
else:
if self.should_compress(top_line, bot_line):
lines.append(TextDrawing.merge_lines(lines.pop(), top_line))
else:
lines.append(TextDrawing.merge_lines(lines[-1], top_line, icod="bot"))
# MID
mid_line = ""
for node in wire:
mid_line += node.mid
lines.append(TextDrawing.merge_lines(lines[-1], mid_line, icod="bot"))
# BOT
bot_line = ""
for node in wire:
bot_line += node.bot
lines.append(TextDrawing.merge_lines(lines[-1], bot_line, icod="bot"))
return lines
@staticmethod
def special_label(node):
"""Some instructions have special labels"""
labels = {IGate: "I", SXGate: "√X", SXdgGate: "√Xdg"}
node_type = type(node)
return labels.get(node_type, None)
@staticmethod
def merge_lines(top, bot, icod="top"):
"""Merges two lines (top and bot) in a way that the overlapping makes sense.
Args:
top (str): the top line
bot (str): the bottom line
icod (top or bot): in case of doubt, which line should have priority? Default: "top".
Returns:
str: The merge of both lines.
"""
ret = ""
for topc, botc in zip(top, bot):
if topc == botc:
ret += topc
elif topc in "┼╪" and botc == " ":
ret += "│"
elif topc == " ":
ret += botc
elif topc in "┬╥" and botc in " ║│" and icod == "top":
ret += topc
elif topc in "┬" and botc == " " and icod == "bot":
ret += "│"
elif topc in "╥" and botc == " " and icod == "bot":
ret += "║"
elif topc in "┬│" and botc == "═":
ret += "╪"
elif topc in "┬│" and botc == "─":
ret += "┼"
elif topc in "└┘║│░" and botc == " " and icod == "top":
ret += topc
elif topc in "─═" and botc == " " and icod == "top":
ret += topc
elif topc in "─═" and botc == " " and icod == "bot":
ret += botc
elif topc in "║╥" and botc in "═":
ret += "╬"
elif topc in "║╥" and botc in "─":
ret += "╫"
elif topc in "║╫╬" and botc in " ":
ret += "║"
elif topc == "└" and botc == "┌" and icod == "top":
ret += "├"
elif topc == "┘" and botc == "┐":
ret += "┤"
elif botc in "┐┌" and icod == "top":
ret += "┬"
elif topc in "┘└" and botc in "─" and icod == "top":
ret += "┴"
elif botc == " " and icod == "top":
ret += topc
else:
ret += botc
return ret
@staticmethod
def normalize_width(layer):
"""
When the elements of the layer have different widths, sets the width to the max elements.
Args:
layer (list): A list of elements.
"""
nodes = list(filter(lambda x: x is not None, layer))
longest = max(node.length for node in nodes)
for node in nodes:
node.layer_width = longest
@staticmethod
def controlled_wires(node, layer):
"""
Analyzes the node in the layer and checks if the controlled arguments are in
the box or out of the box.
Args:
node (DAGNode): node to analyse
layer (Layer): The layer in which the node is inserted.
Returns:
Tuple(list, list, list):
- tuple: controlled arguments on top of the "node box", and its status
- tuple: controlled arguments on bottom of the "node box", and its status
- tuple: controlled arguments in the "node box", and its status
- the rest of the arguments
"""
op = node.op
num_ctrl_qubits = op.num_ctrl_qubits
ctrl_qubits = node.qargs[:num_ctrl_qubits]
args_qubits = node.qargs[num_ctrl_qubits:]
ctrl_state = f"{op.ctrl_state:b}".rjust(num_ctrl_qubits, "0")[::-1]
in_box = list()
top_box = list()
bot_box = list()
qubit_index = sorted(i for i, x in enumerate(layer.qubits) if x in args_qubits)
for ctrl_qubit in zip(ctrl_qubits, ctrl_state):
if min(qubit_index) > layer.qubits.index(ctrl_qubit[0]):
top_box.append(ctrl_qubit)
elif max(qubit_index) < layer.qubits.index(ctrl_qubit[0]):
bot_box.append(ctrl_qubit)
else:
in_box.append(ctrl_qubit)
return (top_box, bot_box, in_box, args_qubits)
def _set_ctrl_state(self, node, conditional, ctrl_text, bottom):
"""Takes the ctrl_state from node.op and appends Bullet or OpenBullet
to gates depending on whether the bit in ctrl_state is 1 or 0. Returns gates"""
op = node.op
gates = []
num_ctrl_qubits = op.num_ctrl_qubits
ctrl_qubits = node.qargs[:num_ctrl_qubits]
cstate = f"{op.ctrl_state:b}".rjust(num_ctrl_qubits, "0")[::-1]
for i in range(len(ctrl_qubits)):
if cstate[i] == "1":
gates.append(Bullet(conditional=conditional, label=ctrl_text, bottom=bottom))
else:
gates.append(OpenBullet(conditional=conditional, label=ctrl_text, bottom=bottom))
return gates
def _node_to_gate(self, node, layer):
"""Convert a dag op node into its corresponding Gate object, and establish
any connections it introduces between qubits"""
op = node.op
current_cons = []
connection_label = None
conditional = False
base_gate = getattr(op, "base_gate", None)
params = get_param_str(op, "text", ndigits=5)
if not isinstance(op, (Measure, SwapGate, Reset)) and not op._directive:
gate_text, ctrl_text, _ = get_gate_ctrl_text(op, "text")
gate_text = TextDrawing.special_label(op) or gate_text
gate_text = gate_text + params