-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathquantumsim.py
More file actions
4130 lines (3430 loc) · 181 KB
/
quantumsim.py
File metadata and controls
4130 lines (3430 loc) · 181 KB
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
"""
Copyright (c) 2024 Nico Kuijpers
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
Software.
THE SOFTWARE IS åPROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import math
import cmath
import matplotlib.colors as mcol
import matplotlib.animation as animation
import random
import re
from abc import ABC, abstractmethod
from collections import Counter
'''
This code requires QuTiP for rendering Bloch spheres.
See: https://qutip.org/
QuTiP can be installed by
pip install qutip
'''
from qutip import Bloch
'''
Set the default font family to Courier to ensure a monospaced font for labels of axes in
'''
matplotlib.rcParams['font.family'] = 'Arial'
'''
Symbol for pi
'''
pi_symbol = '\u03c0'
"""
Functions for the Dirac notation to describe (quantum) states and (quantum) operators.
|a> is called 'ket' and represents a column vector with 1 in entry a and 0 everywhere else.
<a| is called 'bra' and represents a row vector with 1 in entry a and 0 everywhere else.
<a||b> is the inner product of <a| and |b>, which is 1 if a = b and 0 if a != b.
|a><b| is the outer product of |a> and <b|, which is a matrix with 1 in entry (a,b) and 0 everywhere else.
Function state_as_string converts integer i, 0 <= i < N, to a quantum state in Dirac notation.
"""
class Dirac:
@staticmethod
def ket(N, a):
ket = np.zeros((N, 1))
ket[a, 0] = 1
return ket
@staticmethod
def bra(N, a):
bra = np.zeros((1, N))
bra[0, a] = 1
return bra
@staticmethod
def bra_ket(N, a, b):
bra = Dirac.bra(N, a)
ket = Dirac.ket(N, b)
return np.inner(bra, ket.T)
@staticmethod
def ket_bra(N, a, b):
ket = Dirac.ket(N, a)
bra = Dirac.bra(N, b)
return np.outer(ket, bra)
@staticmethod
def state_as_string(i,N) -> str:
if i < 0 or i >= 2**N:
raise ValueError("Input i and N must satisfy 0 <= i < 2^N")
binary_string = bin(i)
state_as_string = binary_string[2:].zfill(N)
return "|" + state_as_string + ">"
"""
Functions to obtain 2 x 2 unitary matrices for unitary qubit operations.
"""
class QubitUnitaryOperation:
@staticmethod
def get_identity():
return np.array([[1,0],[0,1]],dtype=complex)
@staticmethod
def get_pauli_x():
return np.array([[0,1],[1,0]],dtype=complex)
@staticmethod
def get_pauli_y():
return np.array([[0,complex(0,-1)],[complex(0,1),0]])
@staticmethod
def get_pauli_z():
return np.array([[1,0],[0,-1]],dtype=complex)
@staticmethod
def get_hadamard():
c = complex(1/np.sqrt(2),0)
return np.array([[c,c],[c,-c]])
@staticmethod
def get_phase(theta):
c = complex(np.cos(theta),np.sin(theta))
return np.array([[1,0],[0,c]])
@staticmethod
def get_rotate_x(theta):
sin = math.sin(theta/2)
cos = math.cos(theta/2)
return np.array([[cos, -1j * sin],[-1j * sin, cos]], dtype=complex)
@staticmethod
def get_rotate_y(theta):
sin = math.sin(theta/2)
cos = math.cos(theta/2)
return np.array([[cos, -sin], [sin, cos]], dtype=complex)
@staticmethod
def get_rotate_z(theta):
a = 0.5j * theta
return np.array([[cmath.exp(-a), 0], [0, cmath.exp(a)]], dtype=complex)
@staticmethod
def get_u_gate(theta, phi, lam):
sin = math.sin(theta/2)
cos = math.cos(theta/2)
a = cos
b = -cmath.exp(1j * lam) * sin
c = cmath.exp(1j * phi) * sin
d = cmath.exp(1j * (phi + lam)) * cos
return np.array([[a, b], [c, d]])
"""
Functions to obtain N x N unitary matrices for unitary operations on quantum circuits of N qubits.
"""
class CircuitUnitaryOperation:
@staticmethod
def get_combined_operation_for_qubit(operation, q, N):
identity = QubitUnitaryOperation.get_identity()
combined_operation = np.eye(1,1)
for i in range(0, N):
if i == q:
combined_operation = np.kron(combined_operation, operation)
else:
combined_operation = np.kron(combined_operation, identity)
return combined_operation
@staticmethod
def get_combined_operation_for_identity(N):
return np.array(np.eye(2**N),dtype=complex)
@staticmethod
def get_combined_operation_for_pauli_x(q, N):
pauli_x = QubitUnitaryOperation.get_pauli_x()
return CircuitUnitaryOperation.get_combined_operation_for_qubit(pauli_x, q, N)
@staticmethod
def get_combined_operation_for_pauli_y(q, N):
pauli_y = QubitUnitaryOperation.get_pauli_y()
return CircuitUnitaryOperation.get_combined_operation_for_qubit(pauli_y, q, N)
@staticmethod
def get_combined_operation_for_pauli_z(q, N):
pauli_z = QubitUnitaryOperation.get_pauli_z()
return CircuitUnitaryOperation.get_combined_operation_for_qubit(pauli_z, q, N)
@staticmethod
def get_combined_operation_for_hadamard(q, N):
hadamard = QubitUnitaryOperation.get_hadamard()
return CircuitUnitaryOperation.get_combined_operation_for_qubit(hadamard, q, N)
@staticmethod
def get_combined_operation_for_phase(theta, q, N):
phase = QubitUnitaryOperation.get_phase(theta)
return CircuitUnitaryOperation.get_combined_operation_for_qubit(phase, q, N)
@staticmethod
def get_combined_operation_for_rotate_x(theta, q, N):
rotate = QubitUnitaryOperation.get_rotate_x(theta)
return CircuitUnitaryOperation.get_combined_operation_for_qubit(rotate, q, N)
@staticmethod
def get_combined_operation_for_rotate_y(theta, q, N):
rotate = QubitUnitaryOperation.get_rotate_y(theta)
return CircuitUnitaryOperation.get_combined_operation_for_qubit(rotate, q, N)
@staticmethod
def get_combined_operation_for_rotate_z(theta, q, N):
rotate = QubitUnitaryOperation.get_rotate_z(theta)
return CircuitUnitaryOperation.get_combined_operation_for_qubit(rotate, q, N)
@staticmethod
def get_combined_operation_for_u_gate(theta, phi, lam, q, N):
u_gate = QubitUnitaryOperation.get_u_gate(theta, phi, lam)
return CircuitUnitaryOperation.get_combined_operation_for_qubit(u_gate, q, N)
@staticmethod
def get_combined_operation_for_controlled_qubit_operation(operation, control, target, N):
identity = QubitUnitaryOperation.get_identity()
ket_bra_00 = Dirac.ket_bra(2,0,0)
ket_bra_11 = Dirac.ket_bra(2,1,1)
combined_operation_zero = np.eye(1,1)
combined_operation_one = np.eye(1,1)
for i in range (0, N):
if control == i:
combined_operation_zero = np.kron(combined_operation_zero, ket_bra_00)
combined_operation_one = np.kron(combined_operation_one, ket_bra_11)
elif target == i:
combined_operation_zero = np.kron(combined_operation_zero, identity)
combined_operation_one = np.kron(combined_operation_one, operation)
else:
combined_operation_zero = np.kron(combined_operation_zero, identity)
combined_operation_one = np.kron(combined_operation_one, identity)
return combined_operation_zero + combined_operation_one
@staticmethod
def get_combined_operation_for_controlled_rotate_x(theta, control, target, N):
operation = QubitUnitaryOperation.get_rotate_x(theta)
return CircuitUnitaryOperation.get_combined_operation_for_controlled_qubit_operation(operation, control, target, N)
@staticmethod
def get_combined_operation_for_controlled_rotate_y(theta, control, target, N):
operation = QubitUnitaryOperation.get_rotate_y(theta)
return CircuitUnitaryOperation.get_combined_operation_for_controlled_qubit_operation(operation, control, target, N)
@staticmethod
def get_combined_operation_for_controlled_rotate_z(theta, control, target, N):
operation = QubitUnitaryOperation.get_rotate_z(theta)
return CircuitUnitaryOperation.get_combined_operation_for_controlled_qubit_operation(operation, control, target, N)
@staticmethod
def get_combined_operation_for_cnot(control, target, N):
pauli_x = QubitUnitaryOperation.get_pauli_x()
return CircuitUnitaryOperation.get_combined_operation_for_controlled_qubit_operation(pauli_x, control, target, N)
@staticmethod
def get_combined_operation_for_controlled_pauli_y(control, target, N):
pauli_y = QubitUnitaryOperation.get_pauli_y()
return CircuitUnitaryOperation.get_combined_operation_for_controlled_qubit_operation(pauli_y, control, target, N)
@staticmethod
def get_combined_operation_for_controlled_pauli_z(control, target, N):
pauli_z = QubitUnitaryOperation.get_pauli_z()
return CircuitUnitaryOperation.get_combined_operation_for_controlled_qubit_operation(pauli_z, control, target, N)
@staticmethod
def get_combined_operation_for_controlled_hadamard(control, target, N):
hadamard = QubitUnitaryOperation.get_hadamard()
return CircuitUnitaryOperation.get_combined_operation_for_controlled_qubit_operation(hadamard, control, target, N)
@staticmethod
def get_combined_operation_for_controlled_phase(theta, control, target, N):
phase_theta = QubitUnitaryOperation.get_phase(theta)
return CircuitUnitaryOperation.get_combined_operation_for_controlled_qubit_operation(phase_theta, control, target, N)
@staticmethod
def get_combined_operation_for_controlled_u_gate(theta, phi, lam, control, target, N):
u_gate = QubitUnitaryOperation.get_u_gate(theta, phi, lam)
return CircuitUnitaryOperation.get_combined_operation_for_controlled_qubit_operation(u_gate, control, target, N)
@staticmethod
def get_combined_operation_for_swap(a, b, N):
combined_operation_cnot_a_b = CircuitUnitaryOperation.get_combined_operation_for_cnot(a, b, N)
combined_operation_cnot_b_a = CircuitUnitaryOperation.get_combined_operation_for_cnot(b, a, N)
return np.dot(np.dot(combined_operation_cnot_a_b,combined_operation_cnot_b_a),combined_operation_cnot_a_b)
@staticmethod
def get_combined_operation_for_fredkin(control, a, b, N):
if control == a or control == b:
raise ValueError(f'Fredkin operation not supported for control = {control}, a = {a}, and b = {b}')
if a != 0 and b != 0:
combined_operation_swap_control_0 = CircuitUnitaryOperation.get_combined_operation_for_swap(control, 0, N)
combined_operation_swap_a_b = CircuitUnitaryOperation.get_combined_operation_for_swap(a-1, b-1, N-1)
combined_operation_fredkin = CircuitUnitaryOperation.get_combined_operation_for_controlled_unitary_operation(combined_operation_swap_a_b)
return np.dot(np.dot(combined_operation_swap_control_0, combined_operation_fredkin), combined_operation_swap_control_0)
elif a == 0:
combined_operation_swap_control_a = CircuitUnitaryOperation.get_combined_operation_for_swap(control, a, N)
combined_operation_fredkin = CircuitUnitaryOperation.get_combined_operation_for_fredkin(a, control, b, N)
return np.dot(np.dot(combined_operation_swap_control_a, combined_operation_fredkin), combined_operation_swap_control_a)
else:
combined_operation_swap_control_b = CircuitUnitaryOperation.get_combined_operation_for_swap(control, b, N)
combined_operation_fredkin = CircuitUnitaryOperation.get_combined_operation_for_fredkin(b, a, control, N)
return np.dot(np.dot(combined_operation_swap_control_b, combined_operation_fredkin), combined_operation_swap_control_b)
@staticmethod
def get_combined_operation_for_toffoli(control_a, control_b, target, N):
if control_a == control_b or control_a == target or control_b == target:
raise ValueError(f'Toffoli operation not supported for control_a = {control_a}, control_b = {control_b}, and target = {target}')
if control_b != 0 and target != 0:
combined_operation_swap_control_a_0 = CircuitUnitaryOperation.get_combined_operation_for_swap(control_a, 0, N)
combined_operation_cnot_control_b_target = CircuitUnitaryOperation.get_combined_operation_for_cnot(control_b-1, target-1, N-1)
combined_operation_toffoli = CircuitUnitaryOperation.get_combined_operation_for_controlled_unitary_operation(combined_operation_cnot_control_b_target)
return np.dot(np.dot(combined_operation_swap_control_a_0, combined_operation_toffoli), combined_operation_swap_control_a_0)
elif control_b == 0:
return CircuitUnitaryOperation.get_combined_operation_for_toffoli(control_b, control_a, target, N)
else:
combined_operation_swap_control_a_target = CircuitUnitaryOperation.get_combined_operation_for_swap(control_a, target, N)
combined_operation_toffoli = CircuitUnitaryOperation.get_combined_operation_for_toffoli(target, control_b, control_a, N)
return np.dot(np.dot(combined_operation_swap_control_a_target, combined_operation_toffoli), combined_operation_swap_control_a_target)
@staticmethod
def get_combined_operation_for_unitary_operation_general(operation, target, N):
# Qubit target is the first qubit on which the unitary operation will be applied
# N is total number of qubits (should be at least size of operation)
# 0 <= target < N
identity = QubitUnitaryOperation.get_identity()
combined_operation = np.eye(1,1)
i = 0
while i < N:
if target == i:
combined_operation = np.kron(combined_operation, operation)
i = i + math.log(operation.shape[0],2)
else:
combined_operation = np.kron(combined_operation, identity)
i = i + 1
return combined_operation
@staticmethod
def get_combined_operation_for_controlled_unitary_operation(operation):
# Qubit 0 is the control
identity = np.eye(*operation.shape)
ket_bra_00 = Dirac.ket_bra(2,0,0)
ket_bra_11 = Dirac.ket_bra(2,1,1)
combined_operation_zero = np.kron(ket_bra_00,identity)
combined_operation_one = np.kron(ket_bra_11,operation)
return combined_operation_zero + combined_operation_one
@staticmethod
def get_combined_operation_for_controlled_unitary_operation_general(operation, control, target, N):
# Qubit control is the control
# Qubit target is the first qubit on which the unitary operation will be applied
# N is total number of qubits (should be at least size of operation plus one)
# control < target and target + size(operation) <= N
identity = QubitUnitaryOperation.get_identity()
ket_bra_00 = Dirac.ket_bra(2,0,0)
ket_bra_11 = Dirac.ket_bra(2,1,1)
identity_operation = np.eye(*operation.shape)
combined_operation_zero = np.eye(1,1)
combined_operation_one = np.eye(1,1)
i = 0
while i < N:
if control == i:
combined_operation_zero = np.kron(combined_operation_zero, ket_bra_00)
combined_operation_one = np.kron(combined_operation_one, ket_bra_11)
i = i + 1
elif target == i:
combined_operation_zero = np.kron(combined_operation_zero, identity_operation)
combined_operation_one = np.kron(combined_operation_one, operation)
i = i + math.log(operation.shape[0],2)
else:
combined_operation_zero = np.kron(combined_operation_zero, identity)
combined_operation_one = np.kron(combined_operation_one, identity)
i = i + 1
return combined_operation_zero + combined_operation_one
@staticmethod
def get_combined_operation_for_multi_controlled_pauli_z_operation(N):
combined_operation = CircuitUnitaryOperation.get_combined_operation_for_identity(N)
combined_operation[2**N-1,2**N-1] = -combined_operation[2**N-1,2**N-1]
return combined_operation
@staticmethod
def get_combined_operation_for_multi_controlled_pauli_x_operation(N):
combined_operation = CircuitUnitaryOperation.get_combined_operation_for_identity(N)
combined_operation[2**N-2,2**N-2] = 1 - combined_operation[2**N-2,2**N-2]
combined_operation[2**N-2,2**N-1] = 1 - combined_operation[2**N-2,2**N-1]
combined_operation[2**N-1,2**N-2] = 1 - combined_operation[2**N-1,2**N-2]
combined_operation[2**N-1,2**N-1] = 1 - combined_operation[2**N-1,2**N-1]
return combined_operation
@staticmethod
def get_combined_operation_for_generic_toffoli(controls:list[int], target:int, N:int):
nr_controls = len(controls)
if target in controls or nr_controls >= N:
raise ValueError(f'Generic toffoli gate not supported for controls {controls} and target = {target}')
if nr_controls not in controls:
combined_operation_swap = np.eye(2**N)
controls_sorted = sorted(controls)
for i in range(nr_controls):
q = controls_sorted[i]
combined_operation_swap_q_i = CircuitUnitaryOperation.get_combined_operation_for_swap(q, i, N)
combined_operation_swap = np.dot(combined_operation_swap, combined_operation_swap_q_i)
combined_operation_swap_target_nr_controls = CircuitUnitaryOperation.get_combined_operation_for_swap(target, nr_controls, N)
combined_operation_swap = np.dot(combined_operation_swap, combined_operation_swap_target_nr_controls)
combined_operation_toffoli = CircuitUnitaryOperation.get_combined_operation_for_multi_controlled_pauli_x_operation(nr_controls + 1)
combined_operation_toffoli_circuit = CircuitUnitaryOperation.get_combined_operation_for_unitary_operation_general(combined_operation_toffoli, 0, N)
return np.dot(np.dot(combined_operation_swap, combined_operation_toffoli_circuit), np.conjugate(combined_operation_swap).T)
else:
combined_operation_swap_control_target = CircuitUnitaryOperation.get_combined_operation_for_swap(nr_controls, target, N)
controls_updated = [q for q in controls if q != nr_controls]
controls_updated.append(target)
combined_operation_generic_toffoli = CircuitUnitaryOperation.get_combined_operation_for_generic_toffoli(controls_updated, nr_controls, N)
return np.dot(np.dot(combined_operation_swap_control_target, combined_operation_generic_toffoli), np.conjugate(combined_operation_swap_control_target).T)
"""
Class representing the quantum state of a quantum circuit of N qubits.
"""
class StateVector:
def __init__(self, N):
self.N = N
self.index = 0
self.state_vector = np.zeros((2**self.N, 1), dtype=complex)
self.state_vector[self.index] = 1
def apply_unitary_operation(self, operation):
# Check if operation is a unitary matrix
if not np.allclose(np.eye(2**self.N), np.dot(np.conj(operation.T), operation)):
raise ValueError("Input matrix is not unitary")
self.state_vector = np.dot(operation, self.state_vector)
def apply_noisy_operation(self, operation):
# A noisy operation does not have to be a unitary matrix
self.state_vector = np.dot(operation, self.state_vector)
def measure_x(self, q):
# Compute the real part of <psi|X|psi>
X = CircuitUnitaryOperation.get_combined_operation_for_pauli_x(q, self.N)
return np.vdot(self.state_vector, X.dot(self.state_vector)).real
def measure_y(self, q):
# Compute the real part of <psi|Y|psi>
Y = CircuitUnitaryOperation.get_combined_operation_for_pauli_y(q, self.N)
return np.vdot(self.state_vector, Y.dot(self.state_vector)).real
def measure_z(self, q):
# Compute the real part of <psi|Z|psi>
Z = CircuitUnitaryOperation.get_combined_operation_for_pauli_z(q, self.N)
return np.vdot(self.state_vector, Z.dot(self.state_vector)).real
def measure(self) -> str:
probalities = np.square(np.abs(self.state_vector)).flatten()
self.index = np.random.choice(len(probalities), p=probalities)
return self.get_classical_state_as_string()
def measure_qubit(self, q) -> int:
identity = QubitUnitaryOperation.get_identity()
ket_bra_00 = Dirac.ket_bra(2,0,0)
ket_bra_11 = Dirac.ket_bra(2,1,1)
P0 = np.eye(1,1)
P1 = np.eye(1,1)
for i in range(self.N):
if i == q:
P0 = np.kron(P0, ket_bra_00)
P1 = np.kron(P1, ket_bra_11)
else:
P0 = np.kron(P0, identity)
P1 = np.kron(P1, identity)
prob_0 = np.vdot(self.state_vector, P0.dot(self.state_vector)).real
prob_1 = np.vdot(self.state_vector, P1.dot(self.state_vector)).real
r = np.random.random()
if r <= prob_0:
self.state_vector = np.dot(P0,self.state_vector)/np.sqrt(prob_0)
return 0
else:
self.state_vector = np.dot(P1,self.state_vector)/np.sqrt(prob_1)
return 1
def reset_qubit(self, q):
measured_value = self.measure_qubit(q)
if measured_value == 1:
combined_operation_pauli_x = CircuitUnitaryOperation.get_combined_operation_for_pauli_x(q, self.N)
self.apply_unitary_operation(combined_operation_pauli_x)
def noisy_measure(self, noisy_operations_readout=None):
# For a noisy circuit, the sum of probabilities may not be equal to one
probalities = np.square(np.abs(self.state_vector)).flatten()
probalities = probalities / np.sum(probalities)
if noisy_operations_readout != None:
for noisy_operation in noisy_operations_readout:
probalities = np.dot(noisy_operation, probalities)
probalities = np.real(probalities)
probalities = probalities / np.sum(probalities)
self.index = np.random.choice(len(probalities), p=probalities)
def get_quantum_state(self):
return self.state_vector
def get_classical_state_as_string(self):
return Dirac.state_as_string(self.index, self.N)
def print(self):
for i, val in enumerate(self.state_vector):
print(f"{Dirac.state_as_string(i,self.N)} : {val[0]}")
class RegisterPartition:
"""
This object is used splice up the classical bit register,
its purpose is pretifying ClassicalBitRegisters output when working with many classical bits
"""
def __init__(self, begin: int, end: int, name: str):
self.begin = begin
self.end = end
self.name = name
def toString(self) -> str:
return "Partition: " + self.name + ", starting from: " + str(self.begin) + " to: " + str(self.end) + ""
class ClassicalBitRegister:
def __init__(self, numberClassicBits: int):
self.numberClassicBits = numberClassicBits
self.partitions = []
self.register = []
for i in range(numberClassicBits):
self.register.insert(-1, 0)
def create_partition(self, begin: int, end: int, name: str):
if(begin > end):
raise Exception("Begin must be smaller than end")
if(end > self.numberClassicBits):
raise Exception("Can not partition beyond the register limits")
for existingPartition in self.partitions:
# Check if the new partition is within boundaries of a different one
if(existingPartition.begin >= begin and begin <= existingPartition.end):
raise Exception("Begin parameter is within boundaries of a different partition")
if(existingPartition.begin >= end and end <= existingPartition.end):
raise Exception("End parameter is within boundaries of a different partition")
# existing 0 3 new is 4 7
if(begin < existingPartition.begin and end > existingPartition.end):
raise Exception("Begin and End parameters are overlapping with a different partition")
self.partitions.append(RegisterPartition(begin, end, name))
def write(self, index: int, value: int):
if(index < 0 or index > self.numberClassicBits):
raise Exception("Index out of bounds")
if(value != 0 and value != 1):
raise Exception("Value must be either 0 or 1")
self.register.pop(index)
self.register.insert(index, value)
def read(self, index: int) -> int:
return self.register[index]
def clear(self):
for i in range(self.numberClassicBits):
self.register[i] = 0
def getAmountOfBits(self):
return self.numberClassicBits
def toString(self, beginBit: int=0, endBit: int=0):
output = ""
if beginBit == 0 and endBit == 0:
for i in range(self.numberClassicBits):
# Check first if the index is a beginning of a partition
for partition in self.partitions:
if(partition.begin == i):
output = output + " " + partition.name + ":"
break
output = output + str(self.register[i])
return output
else:
for i in range(beginBit, endBit, 1):
output = output + str(self.register[i])
return output
def print(self):
print(self.toString())
"""
Class representing a quantum circuit of N qubits.
"""
class Circuit:
def __init__(self, qubits: int, bits: int=0, save_instructions: bool=False, noise_factor: float = 1):
self.N = qubits
self.classicalBitRegister = ClassicalBitRegister(bits)
self.noise_factor = noise_factor
self.state_vector = StateVector(self.N)
self.quantum_states = [self.state_vector.get_quantum_state()]
self.descriptions = []
self.operations = []
self.gates = []
# Options / Flags
self.save_instructions = save_instructions
self.instructions = []
# Keeps track of logical errors, only usable when running surface codes with recovery gates
self.logical_error_count = 0
self.state_vector = StateVector(self.N)
self.noisy_operations_state_prep = []
self.noisy_operations_incoherent = []
self.noisy_operations_readout = []
self.x_measures = np.empty(self.N, dtype=object)
self.y_measures = np.empty(self.N, dtype=object)
self.z_measures = np.empty(self.N, dtype=object)
# Noisy gates
self.phi = [0 for _ in range(self.N)] # Keep a list of phi values for every qubit
# Load in the device parameters json
device_params = DeviceParameters()
device_params.load_from_json("./assets/noise_parameters/Virtual_Quantum_Computer.json")
qiskit_kyiv_parameter_dict = device_params.__dict__()
# Define a list of parameter values based on the stored device parameters
self.parameters = {
"T1": [float(qiskit_kyiv_parameter_dict["T1"][i % len(qiskit_kyiv_parameter_dict["T1"])]) for i in range(self.N)], # Loop over the T1 values of the device parameters to assign to each qubit
"T2": [float(qiskit_kyiv_parameter_dict["T2"][i % len(qiskit_kyiv_parameter_dict["T2"])]) for i in range(self.N)], # Loop over the T2 values of the device parameters to assign to each qubit
"p": [float(qiskit_kyiv_parameter_dict["p"][i % len(qiskit_kyiv_parameter_dict["p"])]) for i in range(self.N)], # Loop over the p values of the device parameters to assign to each qubit
}
def identity(self, q):
combined_operation = CircuitUnitaryOperation.get_combined_operation_for_identity(self.N)
self.descriptions.append(f"Identity on qubit {q}")
gate_as_string = '.'*self.N
self.gates.append(gate_as_string)
self.instructions.append(Identity(self.N, q)) if self.save_instructions else self.operations.append(combined_operation)
def pauli_x(self, q):
combined_operation = CircuitUnitaryOperation.get_combined_operation_for_pauli_x(q, self.N)
self.descriptions.append(f"Pauli X on qubit {q}")
gate_as_string = '.'*self.N
gate_as_list = list(gate_as_string)
gate_as_list[q] = 'X'
gate_as_string = ''.join(gate_as_list)
self.gates.append(gate_as_string)
self.instructions.append(Pauli_X(self.N, q)) if self.save_instructions else self.operations.append(combined_operation)
def noisy_pauli_x(self, q: int, p: float = None, T1: float = None, T2: float = None):
"""Adds a noisy Pauli X gate to the circuit
Args:
q (int): Qubit to operate on.
p (float): Single-qubit depolarizing error probability.
T1 (float): Qubit's amplitude damping time in ns.
T2 (float): Qubit's dephasing time in ns.
"""
# If any noise parameter is None use the generated value
if p is None:
p = self.parameters["p"][q] * self.noise_factor
if T1 is None:
T1 = self.parameters["T1"][q] / self.noise_factor
if T2 is None:
T2 = self.parameters["T2"][q] / self.noise_factor
self.instructions.append(NoisyPauliX(q, self.N, p, T1, T2))
self.descriptions.append(f"Noisy Pauli X on qubit {q}")
gate_as_string = '.'*self.N
gate_as_list = list(gate_as_string)
gate_as_list[q] = 'X'
gate_as_string = ''.join(gate_as_list)
self.gates.append(gate_as_string)
def pauli_y(self, q):
combined_operation = CircuitUnitaryOperation.get_combined_operation_for_pauli_y(q, self.N)
self.descriptions.append(f"Pauli Y on qubit {q}")
gate_as_string = '.'*self.N
gate_as_list = list(gate_as_string)
gate_as_list[q] = 'Y'
gate_as_string = ''.join(gate_as_list)
self.gates.append(gate_as_string)
self.instructions.append(Pauli_Y(self.N, q)) if self.save_instructions else self.operations.append(combined_operation)
def noisy_pauli_y(self, q: int, p: float= None, T1: float= None, T2: float= None):
"""Adds a noisy Pauli Y gate to the circuit
Args:
q (int): Qubit to operate on.
p (float): Single-qubit depolarizing error probability.
T1 (float): Qubit's amplitude damping time in ns.
T2 (float): Qubit's dephasing time in ns.
"""
# If any noise parameter is None use the generated value
if p is None:
p = self.parameters["p"][q] * self.noise_factor
if T1 is None:
T1 = self.parameters["T1"][q] / self.noise_factor
if T2 is None:
T2 = self.parameters["T2"][q] / self.noise_factor
self.instructions.append(NoisyPauliY(q, self.N, p, T1, T2))
self.descriptions.append(f"Noisy Pauli Y on qubit {q}")
gate_as_string = '.'*self.N
gate_as_list = list(gate_as_string)
gate_as_list[q] = 'Y'
gate_as_string = ''.join(gate_as_list)
self.gates.append(gate_as_string)
def pauli_z(self, q):
combined_operation = CircuitUnitaryOperation.get_combined_operation_for_pauli_z(q, self.N)
self.descriptions.append(f"Pauli Z on qubit {q}")
gate_as_string = '.'*self.N
gate_as_list = list(gate_as_string)
gate_as_list[q] = 'Z'
gate_as_string = ''.join(gate_as_list)
self.gates.append(gate_as_string)
self.instructions.append(Pauli_Z(self.N, q)) if self.save_instructions else self.operations.append(combined_operation)
# Define the new "virtual" Pauli Z gate
def noisy_pauli_z(self, q: int, p: float = None, T1: float = None, T2: float = None):
"""Adds a noisy Pauli Z gate to the circuit
Args:
q (int): Qubit to operate on.
p (float): Single-qubit depolarizing error probability.
T1 (float): Qubit's amplitude damping time in ns.
T2 (float): Qubit's dephasing time in ns.
"""
# If any noise parameter is None use the generated value
if p is None:
p = self.parameters["p"][q] * self.noise_factor
if T1 is None:
T1 = self.parameters["T1"][q] / self.noise_factor
if T2 is None:
T2 = self.parameters["T2"][q] / self.noise_factor
self.instructions.append(NoisyPauliZ(q, self.N, p, T1, T2))
self.descriptions.append(f"Noisy Pauli Z on qubit {q}")
gate_as_string = '.'*self.N
gate_as_list = list(gate_as_string)
gate_as_list[q] = 'Z'
gate_as_string = ''.join(gate_as_list)
self.gates.append(gate_as_string)
def hadamard(self, q):
combined_operation = CircuitUnitaryOperation.get_combined_operation_for_hadamard(q, self.N)
self.descriptions.append(f"Hadamard on qubit {q}")
gate_as_string = '.'*self.N
gate_as_list = list(gate_as_string)
gate_as_list[q] = 'H'
gate_as_string = ''.join(gate_as_list)
self.gates.append(gate_as_string)
self.instructions.append(Hadamard(self.N, q)) if self.save_instructions else self.operations.append(combined_operation)
def noisy_hadamard(self, q: int, p: float= None, T1: float= None, T2: float= None):
"""Adds a noisy hadamard gate to the circuit
Args:
q (int): Qubit to operate on.
p (float): Single-qubit depolarizing error probability.
T1 (float): Qubit's amplitude damping time in ns.
T2 (float): Qubit's dephasing time in ns.
"""
# If any noise parameter is None use the generated value
if p is None:
p = self.parameters["p"][q] * self.noise_factor
if T1 is None:
T1 = self.parameters["T1"][q] / self.noise_factor
if T2 is None:
T2 = self.parameters["T2"][q] / self.noise_factor
self.instructions.append(NoisyHadamard(q, self.N, p, T1, T2))
self.descriptions.append(f"Noisy Hadamard on qubit {q}")
gate_as_string = '.'*self.N
gate_as_list = list(gate_as_string)
gate_as_list[q] = 'H'
gate_as_string = ''.join(gate_as_list)
self.gates.append(gate_as_string)
def phase(self, theta, q):
combined_operation = CircuitUnitaryOperation.get_combined_operation_for_phase(theta, q, self.N)
self.descriptions.append(f"Phase with theta = {theta/np.pi:.3f} {pi_symbol} on qubit {q}")
gate_as_string = '.'*self.N
gate_as_list = list(gate_as_string)
gate_as_list[q] = 'S'
gate_as_string = ''.join(gate_as_list)
self.gates.append(gate_as_string)
self.instructions.append(Phase(self.N, q, theta)) if self.save_instructions else self.operations.append(combined_operation)
def noisy_phase(self, theta: float, q: int, p: float = None, T1: float = None, T2: float = None):
"""This gate is implemented making use of perfect hadamard in combination with a X gate!
Args:
theta (float): Angle of rotation on the Bloch sphere.
q (int): Qubit to operate on.
p (float): Single-qubit depolarizing error probability.
T1 (float): Qubit's amplitude damping time in ns.
T2 (float): Qubit's dephasing time in ns.
"""
# If any noise parameter is None use the generated value
if p is None:
p = self.parameters["p"][q]
if T1 is None:
T1 = self.parameters["T1"][q]
if T2 is None:
T2 = self.parameters["T2"][q]
self.instructions.append(NoisyPhase(theta, q, self.N, p, T1, T2))
self.descriptions.append(f"Noisy X rotation of {theta} on qubit {q}")
gate_as_string = '.'*self.N
gate_as_list = list(gate_as_string)
gate_as_list[q] = 'X'
gate_as_string = ''.join(gate_as_list)
self.gates.append(gate_as_string)
def rotate_x(self, theta, q):
combined_operation = CircuitUnitaryOperation.get_combined_operation_for_rotate_x(theta, q, self.N)
self.descriptions.append(f"Rotate X with theta = {theta/np.pi:.3f} {pi_symbol} on qubit {q}")
gate_as_string = '.'*self.N
gate_as_list = list(gate_as_string)
gate_as_list[q] = 'R'
gate_as_string = ''.join(gate_as_list)
self.gates.append(gate_as_string)
self.instructions.append(Rotate_X(self.N, q, theta)) if self.save_instructions else self.operations.append(combined_operation)
def rotate_y(self, theta, q):
combined_operation = CircuitUnitaryOperation.get_combined_operation_for_rotate_y(theta, q, self.N)
self.descriptions.append(f"Rotate Y with theta = {theta/np.pi:.3f} {pi_symbol} on qubit {q}")
gate_as_string = '.'*self.N
gate_as_list = list(gate_as_string)
gate_as_list[q] = 'R'
gate_as_string = ''.join(gate_as_list)
self.gates.append(gate_as_string)
self.instructions.append(Rotate_Y(self.N, q, theta)) if self.save_instructions else self.operations.append(combined_operation)
def rotate_z(self, theta, q):
combined_operation = CircuitUnitaryOperation.get_combined_operation_for_rotate_z(theta, q, self.N)
self.descriptions.append(f"Rotate Z with theta = {theta/np.pi:.3f} {pi_symbol} on qubit {q}")
gate_as_string = '.'*self.N
gate_as_list = list(gate_as_string)
gate_as_list[q] = 'R'
gate_as_string = ''.join(gate_as_list)
self.gates.append(gate_as_string)
self.instructions.append(Rotate_Z(self.N, q, theta)) if self.save_instructions else self.operations.append(combined_operation)
def u_gate(self, theta, phi, lam, q):
combined_operation = CircuitUnitaryOperation.get_combined_operation_for_u_gate(theta, phi, lam, q, self.N)
self.descriptions.append(f"U-gate with (theta,phi,lam) = ({theta/np.pi:.3f} {pi_symbol}, {phi/np.pi:.3f} {pi_symbol}, {lam/np.pi:.3f} {pi_symbol}) on qubit {q}")
gate_as_string = '.'*self.N
gate_as_list = list(gate_as_string)
gate_as_list[q] = 'U'
gate_as_string = ''.join(gate_as_list)
self.gates.append(gate_as_string)
self.instructions.append(U_Gate(self.N, q, theta, phi, lam)) if self.save_instructions else self.operations.append(combined_operation)
def cnot(self, control, target):
combined_operation = CircuitUnitaryOperation.get_combined_operation_for_cnot(control, target, self.N)
self.descriptions.append(f"CNOT with control qubit {control} and target qubit {target}")
gate_as_string = '.'*self.N
gate_as_list = list(gate_as_string)
gate_as_list[control] = '*'
gate_as_list[target] = 'X'
gate_as_string = ''.join(gate_as_list)
self.gates.append(gate_as_string)
self.instructions.append(CNOT(self.N, target, control)) if self.save_instructions else self.operations.append(combined_operation)
# Define the new cnot gate with integrated noise
def noisy_cnot(self, c_qubit: int, t_qubit: int, c_p: float= None, t_p: float= None, gate_error: float=None, c_T1: float= None, t_T1: float= None, c_T2: float= None, t_T2: float= None):
"""Adds a noisy cnot gate to the circuit with depolarizing and
relaxation errors on both qubits during the unitary evolution.
Args:
c_qubit (int): Control qubit for the gate.
t_qubit (int): Target qubit for the gate.
c_p (float): Depolarizing error probability for the control qubit.
t_p (float): Depolarizing error probability for the target qubit.
c_T1 (float): Amplitude damping time in ns for the control qubit.
t_T1 (float): Amplitude damping time in ns for the target qubit.
c_T2 (float): Dephasing time in ns for the control qubit.
t_T2 (float): Dephasing time in ns for the target qubit.
gate_error (float): CNOT depolarizing error probability.
"""
# If any noise parameter is None use the generated value
if c_p is None:
c_p = self.parameters["p"][c_qubit] * self.noise_factor
if c_T1 is None:
c_T1 = self.parameters["T1"][c_qubit] / self.noise_factor
if c_T2 is None:
c_T2 = self.parameters["T2"][c_qubit] / self.noise_factor
if t_p is None:
t_p = self.parameters["p"][t_qubit] * self.noise_factor
if t_T1 is None:
t_T1 = self.parameters["T1"][t_qubit] / self.noise_factor
if t_T2 is None:
t_T2 = self.parameters["T2"][t_qubit] / self.noise_factor
if gate_error is None:
gate_error = 0.015 # Used by Tycho's implementation
self.instructions.append(NoisyCNOT(c_qubit, t_qubit, self.N, c_p, t_p, c_T1, t_T1, c_T2, t_T2, gate_error))
self.descriptions.append(f"Noisy CNOT with target qubit {t_qubit} and control qubit {c_qubit}")
gate_as_string = '.'*self.N
gate_as_list = list(gate_as_string)
gate_as_list[c_qubit] = '*'
gate_as_list[t_qubit] = 'x'
gate_as_string = ''.join(gate_as_list)
self.gates.append(gate_as_string)
def controlled_pauli_y(self, control, target):
combined_operation = CircuitUnitaryOperation.get_combined_operation_for_controlled_pauli_y(control, target, self.N)
self.descriptions.append(f"Controlled Pauli Y with control qubit {control} and target qubit {target}")
gate_as_string = '.'*self.N
gate_as_list = list(gate_as_string)
gate_as_list[control] = '*'
gate_as_list[target] = 'Y'
gate_as_string = ''.join(gate_as_list)
self.gates.append(gate_as_string)
self.instructions.append(Controlled_Pauli_Y(self.N, target, control)) if self.save_instructions else self.operations.append(combined_operation)
def controlled_pauli_z(self, control, target):
combined_operation = CircuitUnitaryOperation.get_combined_operation_for_controlled_pauli_z(control, target, self.N)
self.descriptions.append(f"Controlled Pauli Z with control qubit {control} and target qubit {target}")
gate_as_string = '.'*self.N
gate_as_list = list(gate_as_string)
gate_as_list[control] = '*'
gate_as_list[target] = 'Z'
gate_as_string = ''.join(gate_as_list)
self.gates.append(gate_as_string)
self.instructions.append(Controlled_Pauli_Z(self.N, target, control)) if self.save_instructions else self.operations.append(combined_operation)
def controlled_hadamard(self, control, target):
combined_operation = CircuitUnitaryOperation.get_combined_operation_for_controlled_hadamard(control, target, self.N)
self.descriptions.append(f"Controlled Hadamard with control qubit {control} and target qubit {target}")
gate_as_string = '.'*self.N
gate_as_list = list(gate_as_string)
gate_as_list[control] = '*'
gate_as_list[target] = 'H'
gate_as_string = ''.join(gate_as_list)
self.gates.append(gate_as_string)
self.instructions.append(Controlled_Hadamard(self.N, target, control)) if self.save_instructions else self.operations.append(combined_operation)
def controlled_phase(self, theta, control, target):
combined_operation = CircuitUnitaryOperation.get_combined_operation_for_controlled_phase(theta, control, target, self.N)
self.descriptions.append(f"Controlled phase with theta = {theta/np.pi:.3f} {pi_symbol}, control qubit {control}, and target qubit {target}")
gate_as_string = '.'*self.N
gate_as_list = list(gate_as_string)
gate_as_list[control] = '*'
gate_as_list[target] = 'S'
gate_as_string = ''.join(gate_as_list)
self.gates.append(gate_as_string)
self.instructions.append(Controlled_Phase(theta, self.N, target, control)) if self.save_instructions else self.operations.append(combined_operation)
def controlled_rotate_x(self, theta, control, target):
combined_operation = CircuitUnitaryOperation.get_combined_operation_for_controlled_rotate_x(theta, control, target, self.N)
self.descriptions.append(f"Controlled rotate X with theta = {theta/np.pi:.3f} {pi_symbol}, control qubit {control}, and target qubit {target}")
gate_as_string = '.'*self.N
gate_as_list = list(gate_as_string)
gate_as_list[control] = '*'
gate_as_list[target] = 'R'
gate_as_string = ''.join(gate_as_list)
self.gates.append(gate_as_string)
self.instructions.append(Controlled_Rotate_X(theta, self.N, target, control)) if self.save_instructions else self.operations.append(combined_operation)
def controlled_rotate_y(self, theta, control, target):
combined_operation = CircuitUnitaryOperation.get_combined_operation_for_controlled_rotate_y(theta, control, target, self.N)
self.descriptions.append(f"Controlled rotate Y with theta = {theta/np.pi:.3f} {pi_symbol}, control qubit {control}, and target qubit {target}")
gate_as_string = '.'*self.N
gate_as_list = list(gate_as_string)
gate_as_list[control] = '*'
gate_as_list[target] = 'R'
gate_as_string = ''.join(gate_as_list)
self.gates.append(gate_as_string)
self.instructions.append(Controlled_Rotate_Y(theta, self.N, target, control)) if self.save_instructions else self.operations.append(combined_operation)
def controlled_rotate_z(self, theta, control, target):
combined_operation = CircuitUnitaryOperation.get_combined_operation_for_controlled_rotate_z(theta, control, target, self.N)
self.descriptions.append(f"Controlled rotate Z with theta = {theta/np.pi:.3f} {pi_symbol}, control qubit {control}, and target qubit {target}")
gate_as_string = '.'*self.N
gate_as_list = list(gate_as_string)
gate_as_list[control] = '*'
gate_as_list[target] = 'R'
gate_as_string = ''.join(gate_as_list)
self.gates.append(gate_as_string)
self.instructions.append(Controlled_Rotate_Z(theta, self.N, target, control)) if self.save_instructions else self.operations.append(combined_operation)
def controlled_u_gate(self, theta, phi, lam, control, target):
combined_operation = CircuitUnitaryOperation.get_combined_operation_for_controlled_u_gate(theta, phi, lam, control, target, self.N)
self.descriptions.append(f"Controlled U-gate (theta,phi,lam) = ({theta/np.pi:.3f} {pi_symbol}, {phi/np.pi:.3f} {pi_symbol}, {lam/np.pi:.3f} {pi_symbol}), control {control}, and target {target}")