/
SEO_writer.py
1568 lines (1263 loc) · 47 KB
/
SEO_writer.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
from qubiter.CktEmbedder import *
from qubiter.Controls import *
from qubiter.OneQubitGate import *
import re
import qubiter.utilities_gen as utg
from qubiter.PlaceholderManager import *
import sys
import os
from IPython.display import HTML, display
if 'autograd.numpy' not in sys.modules:
import numpy as np
class SEO_writer:
"""
The constructor of this class opens an English and a Picture file. Every
other method of the class writes, each time it is called, a single line
in each of those 2 files.
Note SEO stands for Sequence of Elementary Operations.
So what are English and Picture files?
We use 3 types of files to characterize a single quantum circuit (in the
gate model): (1) an English file (2) a Picture file (3) a Log file.
Log files are written by class SEO_reader, whereas English and Picture
files are written by this class, SEO_writer.
A log file just contains useful information like the number of lines of
the English file (same as that of Picture file) and their number of
operations.
The lines of an English and Picture file are in 1-1 correspondence,
each line representing a single operation (e.g., a multi-controlled one
qubit gate or a multi-controlled 2 qubit swap).
The English file (resp., Picture file) contains complete (resp.,
partial, in the form of an ASCII picture) info about the operation
specified by each line.
In English and Picture files, time flows downward.
The class SEO_writer gives the bool option ZL. When this argument is set
to True (resp., False), the Picture file shows the zero qubit last (
resp., first), and the remaining qubits in consecutive order. Picture
files written with zero bit last (resp., first) are labelled prefix +
'_ZLpict.text' (resp., prefix + '_ZFpict.txt'). The ZL choice does not
affect the English file.
See the following and earlier arXiv papers by R.R.Tucci for more info on
English and Picture files.
http://arxiv.org/abs/1004.2205
"Quibbs, a Code Generator for Quantum Gibbs Sampling"
The following pdf is stored in the same folder as this python file.
qubiter_rosetta_stone.pdf
This pdf gives examples of lines in analytic/Picture/English formats.
The Picture file examples follow the ZL convention.
3 kinds (called 0, 1, 2) of measurements MEAS are allowed. A type 0
measurement inserts a projector ``|0><0| = n = P_0`` at the target bit.
A type 1 measurement inserts a projector ``|1><1| = nbar = P_1`` at the
target bit. A type 2 measurement stores a copy of the state vector after
``|0><0|`` has been applied, and another copy after ``|1><1|`` has been
applied.
If a vertical wire hasn't been measured as type 2 measurement,
it is drawn in pic file as "|"; otherwise, it is drawn as ":".
Attributes
----------
emb : CktEmbedder
english_out : _io.TextIOWrapper
file object for output text file that stores English description of
circuit
file_prefix : str
beginning of the name of both English and Picture files
gate_line_counter : int
indentation : int
Starts at 0, Grows by 4 at end of each write_LOOP and decrease by 4
at beginning of each write_NEXT
measured_bits : list(int)
list of bits that have been measured with type 2 measurement and
haven't been reset to ``|0>`` or ``|1>``
picture_out : _io.TextIOWrapper
file object for output text file that stores ASCII Picture
description of circuit
ZL : bool
"""
def __init__(self, file_prefix, emb, ZL=True,
english_out=None, picture_out=None):
"""
Constructor
Parameters
----------
file_prefix : str
emb : CktEmbedder
ZL : bool
english_out : _io.TextIOWrapper
picture_out : _io.TextIOWrapper
Returns
-------
"""
self.gate_line_counter = 0
self.file_prefix = file_prefix
self.emb = emb
self.ZL = ZL
self.measured_bits = []
if english_out is None and file_prefix:
self.english_out = open(utg.preface(self.get_eng_file_path(
rel=True)), 'wt')
else:
self.english_out = english_out
if picture_out is None and file_prefix:
self.picture_out = open(utg.preface(self.get_pic_file_path(
rel=True)), 'wt')
else:
self.picture_out = picture_out
self.indentation = 0
def get_eng_file_path(self, rel=False):
"""
Returns path (relative if rel is True, absolute if rel is False) of
English file.
Attributes
----------
rel : bool
Returns
-------
str
"""
rel_path = utg.get_eng_file_rel_path(self.file_prefix,
self.emb.num_qbits_aft)
# print("..,,mmmm", rel_path)
return rel_path if rel else utg.preface(rel_path)
def get_pic_file_path(self, rel=False):
"""
Returns path (relative if rel is True, absolute if rel is False) of
Picture file.
Attributes
----------
rel : bool
Returns
-------
str
"""
rel_path = utg.get_pic_file_rel_path(self.file_prefix,
self.emb.num_qbits_aft,
ZL=self.ZL)
return rel_path if rel else utg.preface(rel_path)
def close_files(self):
"""
Closes English and Picture files that were opened by the constructor.
Returns
-------
None
"""
# print("bbnnnvvv", 'closing files')
self.english_out.close()
self.picture_out.close()
def delete_files(self):
"""
This method will delete the English and Picture files. The files are
closed before being deleted in case that hasn't been done yet.
Closing a file a second time does nothing.
Returns
-------
None
"""
self.close_files()
import os
os.remove(self.get_eng_file_path())
os.remove(self.get_pic_file_path())
@staticmethod
def gen_html_from_eng_or_pic_file(f):
"""
This function returns a string for an html table generated from an
English or Picture file. The table has two columns.
The first column gives the line numbers starting from 1.
Parameters
----------
f : file
f is file object returned by open()
Returns
-------
str
"""
k = 1
line = f.readline()
all_lines = ''
td0 = "<td style='border-right:1px solid red;'>"
td1 = "<td style='text-align:left;'>"
while line:
all_lines += td0 + str(k) + "</td>" + td1 +\
"<pre>" + line.strip() + "</pre>" +\
'</td></tr>'
k += 1
line = f.readline()
table = "<table style='font-family:monospace'><tr>" +\
all_lines + '</table>'
# print(table)
return table
def print_eng_file(self, jup=False):
"""
Prints English file.
Parameters
----------
jup : bool
If jup=False, it prints text. Otherwise, it draws in a jupyter
notebook a table with line numbers starting at 1
Returns
-------
None
"""
with open(utg.preface(self.get_eng_file_path(rel=True)), 'r') as f:
if not jup:
print(f.read())
else:
dis_obj = HTML(SEO_writer.gen_html_from_eng_or_pic_file(f))
display(dis_obj)
def print_pic_file(self, jup=False):
"""
Prints Picture file.
Parameters
----------
jup : bool
If jup=False, it prints text. Otherwise, it draws in a jupyter
notebook a table with line numbers starting at 1
Returns
-------
None
"""
with open(utg.preface(self.get_pic_file_path(rel=True)), 'r') as f:
if not jup:
print(f.read())
else:
dis_obj = HTML(SEO_writer.gen_html_from_eng_or_pic_file(f))
display(dis_obj)
def colonize(self, pic_line):
"""
This function returns new version of pic_line. Every "|" wire is
replaced by ":" colon wire and vice versa iff the wire is at a bit
position that has been measured (type 2 measurement) in the past and
not reset. This function assumes pic_line in ZL convention so must
call this function before calling write_ZF_or_ZL_pic_line()
Parameters
----------
pic_line : str
Returns
-------
str
"""
num_qbits = self.emb.num_qbits_aft
li = list(pic_line)
for bit in range(0, num_qbits):
m = 4*(num_qbits - 1 - bit)
if bit in self.measured_bits:
if li[m] == "|":
li[m] = ":"
else:
if li[m] == ":":
li[m] = "|"
return "".join(li)
def write_ZF_or_ZL_pic_line(self, pic_line):
"""
Writes a line in the Picture file using either the ZF or ZL
conventions. pic_line is originally written in ZL format, so this
method does nothing to pic_line if ZL option is chosen but reverses
order of gates if ZF option chosen.
Parameters
----------
pic_line : str
Returns
-------
None
"""
# example:
# Ry--R---<--->---Rz
if not self.ZL:
pic_line = pic_line.strip()
# delimiter is -- or --- or 2 spaces or 3 spaces
nodes = re.split('-{2,3}| {2,3}', pic_line)
dash_or_space = [pic_line[k*4 + 3] for k in range(len(nodes)-1)]
nodes = list(reversed(nodes))
dash_or_space = list(reversed(dash_or_space))
for kk in range(len(nodes)):
if nodes[kk] == '<':
nodes[kk] = '>'
elif nodes[kk] == '<<':
nodes[kk] = '>>'
elif nodes[kk] == '>':
nodes[kk] = '<'
elif nodes[kk] == '>>':
nodes[kk] = '<<'
new_line = ''
k = 0
for nd in nodes:
if k < len(nodes) - 1:
if len(nd) == 1:
new_line += (nd + dash_or_space[k]*3)
elif len(nd) == 2:
new_line += (nd + dash_or_space[k]*2)
else: # k = len(nodes) - 1
new_line += nd
k += 1
else:
new_line = pic_line
self.picture_out.write(new_line)
def write_IF_M_beg(self, trols):
"""
Writes a 'IF_M( <controls> ){' line in eng & pic files.
Parameters
----------
trols : Controls
Returns
-------
None
"""
aft_trols = trols.new_embedded_self(self.emb)
s = "IF_M(\t"
num_controls = len(aft_trols.bit_pos)
for c in range(num_controls):
s += str(aft_trols.bit_pos[c]) + \
("T" if aft_trols.kinds[c] == True else "F") + \
("\t){\n" if (c == num_controls - 1) else "\t")
self.english_out.write(' '*self.indentation + s)
self.picture_out.write(' '*self.indentation + s)
def write_IF_M_end(self):
"""
Writes an '}IF_M' line in eng and pic files.
Parameters
----------
Returns
-------
None
"""
s = "}IF_M\n"
self.english_out.write(' '*self.indentation + s)
self.picture_out.write(' '*self.indentation + s)
def write_LOOP(self, loop_num, nreps):
"""
Writes a 'LOOP' line in eng & pic files. The gates between a LOOP
line and its partner NEXT line are to be repeated a number of times
called nreps.
Parameters
----------
loop_num : int
nreps : int
Returns
-------
None
"""
s = "LOOP\t" + str(loop_num) + "\tNREPS=\t" + str(nreps) + '\n'
self.english_out.write(' '*self.indentation + s)
self.picture_out.write(' '*self.indentation + s)
self.indentation += 4
def write_MEAS(self, tar_bit_pos, kind):
"""
Writes a 'MEAS' line in eng & pic files. This denotes a measurement
step. We allow 3 kinds of measurements (0, 1, 2) at a target bit.
Parameters
----------
tar_bit_pos : int
kind : int
either 0, 1 or 2
Returns
-------
None
"""
# num_qbits_bef = self.emb.num_qbits_bef
num_qbits_aft = self.emb.num_qbits_aft
aft_tar_bit_pos = self.emb.aft(tar_bit_pos)
assert kind in [0, 1, 2], "unsupported measurement kind"
if kind == 2:
self.measured_bits.append(aft_tar_bit_pos)
# english file
s = 'MEAS\t' + str(kind) + '\tAT\t' + str(aft_tar_bit_pos) + '\n'
self.english_out.write(' '*self.indentation + s)
# picture file
pic_line = ""
biggest = aft_tar_bit_pos
smallest = aft_tar_bit_pos
# k a bit position
for k in range(num_qbits_aft-1, biggest, -1):
pic_line += "| "
if kind == 0:
pic_line += "M0 "
elif kind == 1:
pic_line += 'M1 '
else:
pic_line += 'M '
for k in range(smallest-1, -1, -1):
pic_line += "| "
pic_line = self.colonize(pic_line)
self.write_ZF_or_ZL_pic_line(pic_line)
self.picture_out.write("\n")
def write_NEXT(self, loop_num):
"""
Writes a 'NEXT' line in eng & pic files.
Parameters
----------
loop_num : int
Returns
-------
None
"""
self.indentation -= 4
s = "NEXT\t" + str(loop_num) + '\n'
self.english_out.write(' '*self.indentation + s)
self.picture_out.write(' '*self.indentation + s)
def write_NOTA(self, bla_str, permission=True):
"""
Writes a 'NOTA' line in eng & pic files. As the name implies,
a NOTA is just a note or comment such as "I love you Mary". It is
not a gate.
Parameters
----------
bla_str : str
permission : bool
General permission, useful for turning off whole batches of NOTAs
Returns
-------
None
"""
if permission:
s = "NOTA\t" + bla_str.rstrip() + '\n'
self.english_out.write(' '*self.indentation + s)
self.picture_out.write(' '*self.indentation + s)
def write_PRINT(self, style):
"""
Writes a 'PRINT' line in eng & pic files.
Parameters
----------
style : str
Returns
-------
None
"""
s = "PRINT\t" + style + '\n'
self.english_out.write(' '*self.indentation + s)
self.picture_out.write(' '*self.indentation + s)
def rads_to_degs_str(self, rads):
"""
This method returns
str(rads*180/pi) if isinstance(rads, float)
rads if is_legal_var_name(rads) (this implies rads is str)
aborts otherwise.
The method is only used inside this class so I am making it
non-static even though it doesn't use self.
Parameters
----------
rads : float | str
Returns
-------
str
"""
# print("--nnn", type(rads))
# np.float types are different from float!!!
if isinstance(rads, (int, float, np.floating)):
# print("--nnn", str(rads*180/np.pi))
return '{0:0.6f}'.format(rads*180/np.pi)
else:
assert PlaceholderManager.is_legal_var_name(rads), \
"attempting to write an illegal variable name: '" +\
str(rads) + "'"
return rads
def write_controlled_preamble(self, trols):
"""
This is an internal function, used as preamble to all methods that
are named write_controlled_...()
Parameters
----------
trols : Controls
Returns
-------
Controls
"""
self.gate_line_counter += 1
assert not self.english_out.closed
assert not self.picture_out.closed
aft_trols = trols.new_embedded_self(self.emb)
# add extra controls if there are any
extra_dict = self.emb.extra_controls.bit_pos_to_kind
if extra_dict:
aft_trols.bit_pos_to_kind.update(extra_dict)
aft_trols.refresh_lists()
return aft_trols
def write_controlled_one_qbit_gate(
self, tar_bit_pos, trols, one_qbit_gate_fun, fun_arg_list=None):
"""
Writes a line in eng & pic files for a one bit gate (from class
OneQubitGate) with >= 0 controls.
Parameters
----------
tar_bit_pos : int
trols : Controls
one_qbit_gate_fun : function
maps Any->np.ndarray
fun_arg_list : list
Returns
-------
None
"""
aft_trols = self.write_controlled_preamble(trols)
# num_qbits_bef = self.emb.num_qbits_bef
num_qbits_aft = self.emb.num_qbits_aft
aft_tar_bit_pos = self.emb.aft(tar_bit_pos)
# number of controls may be zero
num_controls = len(aft_trols.bit_pos)
assert aft_tar_bit_pos not in aft_trols.bit_pos,\
"target bit cannot be a control bit"
if fun_arg_list is None:
fun_arg_list = []
# english file
self.english_out.write(' '*self.indentation)
if one_qbit_gate_fun == OneQubitGate.had2:
self.english_out.write("HAD2")
elif one_qbit_gate_fun == OneQubitGate.phase_fac:
self.english_out.write("PHAS\t" +
self.rads_to_degs_str(fun_arg_list[0]))
elif one_qbit_gate_fun == OneQubitGate.P_0_phase_fac:
self.english_out.write("P0PH\t" +
self.rads_to_degs_str(fun_arg_list[0]))
elif one_qbit_gate_fun == OneQubitGate.P_1_phase_fac:
self.english_out.write("P1PH\t" +
self.rads_to_degs_str(fun_arg_list[0]))
elif one_qbit_gate_fun == OneQubitGate.rot_ax:
ang_rads = fun_arg_list[0]
axis = fun_arg_list[1]
degs_str = self.rads_to_degs_str(ang_rads)
if axis == 1:
self.english_out.write("ROTX\t" + degs_str)
elif axis == 2:
self.english_out.write("ROTY\t" + degs_str)
elif axis == 3:
self.english_out.write("ROTZ\t" + degs_str)
else:
assert False
elif one_qbit_gate_fun == OneQubitGate.rot:
x_degs = self.rads_to_degs_str(fun_arg_list[0])
y_degs = self.rads_to_degs_str(fun_arg_list[1])
z_degs = self.rads_to_degs_str(fun_arg_list[2])
self.english_out.write("ROTN\t" +
x_degs + "\t" + y_degs + "\t" + z_degs)
elif one_qbit_gate_fun == OneQubitGate.sigx:
self.english_out.write("SIGX")
elif one_qbit_gate_fun == OneQubitGate.sigy:
self.english_out.write("SIGY")
elif one_qbit_gate_fun == OneQubitGate.sigz:
self.english_out.write("SIGZ")
elif one_qbit_gate_fun == OneQubitGate.u2:
ph_degs = self.rads_to_degs_str(fun_arg_list[0])
x_degs = self.rads_to_degs_str(fun_arg_list[1])
y_degs = self.rads_to_degs_str(fun_arg_list[2])
z_degs = self.rads_to_degs_str(fun_arg_list[3])
self.english_out.write("U_2_\t" + ph_degs + "\t" +
x_degs + "\t" + y_degs + "\t" + z_degs)
else:
assert False, "writing an unsupported controlled gate\n" +\
one_qbit_gate_fun.__name__
self.english_out.write("\tAT\t" + str(aft_tar_bit_pos) +
("\tIF\t" if num_controls != 0 else "\n"))
# list bit-positions in decreasing order
for c in range(num_controls):
self.english_out.write(
str(aft_trols.bit_pos[c]) +
("T" if aft_trols.kinds[c] == True else "F") +
("\n" if c == num_controls - 1 else "\t"))
# picture file
pic_line = ""
biggest = aft_tar_bit_pos
smallest = aft_tar_bit_pos
if num_controls != 0:
biggest = max(aft_trols.bit_pos[0], aft_tar_bit_pos)
smallest = min(aft_trols.bit_pos[num_controls-1], aft_tar_bit_pos)
# k a bit position
for k in range(num_qbits_aft-1, biggest, -1):
pic_line += "| "
c_int = 0
for k in range(biggest, smallest-1, -1):
is_target = (k == aft_tar_bit_pos)
is_control = False
control_kind = False
tres = ' '*3 if (k == smallest) else "---"
dos = ' '*2 if (k == smallest) else "--"
# c_int starts at last value
for c in range(c_int, num_controls, +1):
if k == aft_trols.bit_pos[c]:
is_control = True
control_kind = aft_trols.kinds[c]
c_int += 1
break
if is_control:
pic_line += ("@" if control_kind else "O") + tres
else: # is not control
if not is_target: # is not control or target
pic_line += "+" + tres
else: # is target
if one_qbit_gate_fun == OneQubitGate.had2:
pic_line += "H" + tres
elif one_qbit_gate_fun == OneQubitGate.phase_fac:
pic_line += "Ph" + dos
elif one_qbit_gate_fun == OneQubitGate.P_0_phase_fac:
pic_line += "OP" + dos
elif one_qbit_gate_fun == OneQubitGate.P_1_phase_fac:
pic_line += "@P" + dos
elif one_qbit_gate_fun == OneQubitGate.rot_ax:
axis = fun_arg_list[1]
if axis == 1:
pic_line += "Rx" + dos
elif axis == 2:
pic_line += "Ry" + dos
elif axis == 3:
pic_line += "Rz" + dos
else:
assert False
elif one_qbit_gate_fun == OneQubitGate.rot:
pic_line += "R" + tres
elif one_qbit_gate_fun == OneQubitGate.sigx:
pic_line += "X" + tres
elif one_qbit_gate_fun == OneQubitGate.sigy:
pic_line += "Y" + tres
elif one_qbit_gate_fun == OneQubitGate.sigz:
pic_line += "Z" + tres
elif one_qbit_gate_fun == OneQubitGate.u2:
rads1 = fun_arg_list[1]
rads2 = fun_arg_list[2]
rads3 = fun_arg_list[3]
def both_are_small(r1, r2):
if isinstance(r1, str) or isinstance(r2, str):
return False
if abs(r1) > 1e-6 or abs(r2) > 1e-6:
return False
return True
small_12 = both_are_small(rads1, rads2)
small_23 = both_are_small(rads2, rads3)
small_13 = both_are_small(rads1, rads3)
if small_12 and small_23:
pic_line += "Ph" + dos
elif small_23:
pic_line += "Ux" + dos
elif small_13:
pic_line += "Uy" + dos
elif small_12:
pic_line += "Uz" + dos
else:
pic_line += "U" + tres
else:
assert False, \
"writing an unsupported controlled gate\n" +\
one_qbit_gate_fun.__name__
for k in range(smallest-1, -1, -1):
pic_line += "| "
pic_line = self.colonize(pic_line)
self.write_ZF_or_ZL_pic_line(pic_line)
self.picture_out.write("\n")
def write_controlled_qbit_swap(self, bit1, bit2, trols, rads_list=None):
"""
If rads_list=None, this method writes a line in eng & pic files for
a 'SWAP' with >= 0 controls
NOTE: SWAP is qbit symmetric: SWAP(0,1) = SWAP(1,0)
If rads_list is not None and equals a list of 2 angles, rads_list=[
rads0, rads1], this method writes a generalization of SWAP that I
call SWAY (just to have a verb that is close to swap)
SWAY =
[1 0 0]
[0 U2 0]
[0 0 1]
where U2 is the most general 2-dim unitary matrix satisfying
sigx U2 sigx = U2.
If U2 is parametrized as
U2 = exp(j*(rads0 + rads1*sigx + rads2*sigy + rads3*sigz))
then SWAY is qbit symmetric (SWAY(0,1)=SWAY(1,0)) iff sigx U2 sigx
= U2 iff rads2=rads3=0.
SWAY includes SWAP, sqrt(SWAP), iSWAP, sqrt(iSWAP), PWAP,
sqrt(PSWAP) etc.
Parameters
----------
bit1 : int
bit2 : int
bit1 and bit2 are the positions of the swapped bits.
trols : Controls
rads_list : list[float | str ] | None
Returns
-------
None
"""
aft_trols = self.write_controlled_preamble(trols)
num_qbits_bef = self.emb.num_qbits_bef
num_qbits_aft = self.emb.num_qbits_aft
# aft_tar_bit_pos = self.emb.aft(tar_bit_pos)
# number of controls may be zero
num_controls = len(aft_trols.bit_pos)
assert bit1 != bit2, "swapped bits must be different"
assert -1 < bit1 < num_qbits_bef
assert -1 < bit2 < num_qbits_bef
x = [self.emb.aft(bit1), self.emb.aft(bit2)]
big = max(x)
small = min(x)
use_sway = False
if rads_list is not None:
assert len(rads_list) == 2
use_sway = True
# english file
gate_name = 'SWAP'
if use_sway:
gate_name = 'SWAY'
self.english_out.write(' '*self.indentation + gate_name +
'\t' + str(big) + "\t" + str(small))
if use_sway:
self.english_out.write('\tBY')
for k in range(2):
deg_str = self.rads_to_degs_str(rads_list[k])
self.english_out.write('\t' + deg_str)
self.english_out.write("\tIF\t" if num_controls != 0 else "\n")
# list bit-positions in decreasing order
for c in range(num_controls):
self.english_out.write(
str(aft_trols.bit_pos[c]) +
("T" if aft_trols.kinds[c] == True else "F") +
("\n" if (c == num_controls - 1) else "\t"))
# picture file
pic_line = ""
biggest = big
smallest = small
if num_controls != 0:
biggest = max(aft_trols.bit_pos[0], big)
smallest = min(aft_trols.bit_pos[num_controls-1], small)
# k a bit position
for k in range(num_qbits_aft-1, biggest, -1):
pic_line += "| "
c_int = 0
for k in range(biggest, smallest-1, -1):
is_big = (k == big)
is_small = (k == small)
is_control = False
control_kind = False
tres = ' '*3 if (k == smallest) else "---"
dos = ' '*2 if (k == smallest) else "--"
for c in range(c_int, num_controls, +1):
if k == aft_trols.bit_pos[c]:
is_control = True
control_kind = aft_trols.kinds[c]
c_int += 1
break
if is_control:
pic_line += ('@' if control_kind else 'O') + tres
else: # control not found
if is_big:
if use_sway:
pic_line += "<<" + dos
else:
pic_line += "<" + tres
elif is_small:
if use_sway:
pic_line += ">>" + dos
else:
pic_line += ">" + tres
else:
pic_line += "+" + tres
for k in range(smallest-1, -1, -1):
pic_line += "| "
pic_line = self.colonize(pic_line)
self.write_ZF_or_ZL_pic_line(pic_line)
self.picture_out.write("\n")
def write_controlled_multiplexor_gate(self,
tar_bit_pos, trols, rad_angles):
"""
Writes a line in eng & pic files for a multiplexor 'MP_Y' with >= 0
controls of either int (integer, intrinsic) or True/False kind.
Parameters
----------
tar_bit_pos : int
trols : Controls
rad_angles : list[float]
Returns
-------
None
"""
aft_trols = self.write_controlled_preamble(trols)
# num_qbits_bef = self.emb.num_qbits_bef
num_qbits_aft = self.emb.num_qbits_aft
aft_tar_bit_pos = self.emb.aft(tar_bit_pos)
# number of controls may be zero
num_controls = len(aft_trols.bit_pos)
assert aft_tar_bit_pos not in aft_trols.bit_pos,\
"target bit cannot be a control bit"
num_int_controls = aft_trols.get_num_int_controls()
assert num_int_controls != 0, \
"multiplexor with no half-moon controls"
num_angles = len(rad_angles)
assert num_angles == (1 << num_int_controls),\
"wrong number of multiplexor angles"
# english file
self.english_out.write(' '*self.indentation +
"MP_Y\tAT\t" + str(aft_tar_bit_pos) + "\tIF\t")
# list bit-positions in decreasing order
for c in range(num_controls):
x = aft_trols.kinds[c]
kind_str = ""
# bool is subclass of int
# so isinstance(x, int) will be true if x is bool!
if not isinstance(x, bool):
kind_str = ":" + str(x)
elif not x:
kind_str = "F"
elif x:
kind_str = "T"
self.english_out.write(
str(aft_trols.bit_pos[c]) + kind_str + "\t")
# use BY to indicate end of controls
self.english_out.write("\tBY\t")
for k in range(num_angles):
self.english_out.write(
self.rads_to_degs_str(rad_angles[k]) +
("\n" if k == (num_angles-1) else "\t"))
# picture file
pic_line = ""
biggest = aft_tar_bit_pos
smallest = aft_tar_bit_pos
if num_controls != 0:
biggest = max(aft_trols.bit_pos[0], aft_tar_bit_pos)
smallest = min(aft_trols.bit_pos[num_controls-1], aft_tar_bit_pos)
# k a bit position
for k in range(num_qbits_aft-1, biggest, -1):
pic_line += "| "
c_int = 0
for k in range(biggest, smallest-1, -1):
is_target = (k == tar_bit_pos)
is_control = False
control_kind = False
tres = ' '*3 if (k == smallest) else "---"
dos = ' '*2 if (k == smallest) else "--"
# c_int starts at last value
for c in range(c_int, num_controls, +1):
if k == aft_trols.bit_pos[c]:
is_control = True
control_kind = aft_trols.kinds[c]
c_int += 1