/
compilers.py
2818 lines (2347 loc) · 151 KB
/
compilers.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
""" Clifford circuit, CNOT circuit, and stabilizer state/measurement generation compilation routines """
from __future__ import division, print_function, absolute_import, unicode_literals
#***************************************************************************************************
# Copyright 2015, 2019 National Technology & Engineering Solutions of Sandia, LLC (NTESS).
# Under the terms of Contract DE-NA0003525 with NTESS, the U.S. Government retains certain rights
# in this software.
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
# in compliance with the License. You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0 or in the LICENSE file in the root pyGSTi directory.
#***************************************************************************************************
import numpy as _np
import copy as _copy
from ..objects.circuit import Circuit as _Circuit
from ..baseobjs import Label as _Label
from ..tools import symplectic as _symp
from ..tools import matrixmod2 as _mtx
from ..tools import compattools as _compat
def create_standard_cost_function(name):
"""
Creates the standard 'costfunctions' from an input string, used for calculating the
"cost" of a circuit created by some compilation algorithms
Parameters
----------
name : str
Allowed values are:
- '2QGC' : the cost of the circuit is the number of 2-qubit gates it contains.
- 'depth' : the cost of the circuit is the depth of the circuit.
- '2QGC:x:depth:y' : the cost of the circuit is x * the number of 2-qubit gates in the circuit +
y * the depth of the circuit, where x and y are integers.
Returns
-------
function
A function that takes a circuit as the first argument, a ProcessorSpec as the second
argument (or a "junk" input when a ProcessorSpec is not needed), and returns the cost
of the circuit.
"""
if name == '2QGC':
def costfunction(circuit, junk): # Junk input as no processorspec is needed here.
return circuit.twoQgate_count()
elif name == 'depth':
def costfunction(circuit, junk): # Junk input as no processorspec is needed here.
return circuit.depth()
# This allows for '2QGC:x:depth:y' strings
elif name[:4] == '2QGC':
s = name.split(":")
try: twoQGCfactor = int(s[1])
except: raise ValueError("This `costfunction` string is not a valid option!")
assert(s[2] == 'depth'), "This `costfunction` string is not a valid option!"
try: depthfactor = int(s[3])
except: raise ValueError("This `costfunction` string is not a valid option!")
def costfunction(circuit, junk): # Junk input as no processorspec is needed here.
return twoQGCfactor * circuit.twoQgate_count() + depthfactor * circuit.depth()
else: raise ValueError("This `costfunction` string is not a valid option!")
return costfunction
def compile_clifford(s, p, pspec=None, subsetQs=None, iterations=20, algorithm='ROGGE', aargs=[],
costfunction='2QGC:10:depth:1', prefixpaulis=False, paulirandomize=False):
"""
Compiles an n-qubit Clifford gate, described by the symplectic matrix s and vector p, into
a circuit over the specified model, or, a standard model. Clifford gates/circuits can be converted
to, or sampled in, the symplectic representation using the functions in pygsti.tools.symplectic.
The circuit created by this function will be over a user-specified model and respects any desired
connectivity, if a ProcessorSpec object is provided. Otherwise, it is over a canonical model containing
all-to-all CNOTs, Hadamard, Phase, 3 products of Hadamard and Phase, and the Pauli gates.
Parameters
----------
s : array over [0,1]
An (2n X 2n) symplectic matrix of 0s and 1s integers.
p : array over [0,1]
A length-2n vector over [0,1,2,3] that, together with s, defines a valid n-qubit Clifford
gate.
pspec : ProcessorSpec, optional
An nbar-qubit ProcessorSpec object that encodes the device that the Clifford is being compiled
for, where nbar >= n. If this is specified, the output circuit is over the gates available
in this device. If this is None, the output circuit is over the "canonical" model of CNOT gates
between all qubits, consisting of "H", "HP", "PH", "HPH", "I", "X", "Y" and "Z", which is the set
used internally for the compilation. In most circumstances, the output will be more useful if a
ProcessorSpec is provided.
If nbar > n it is necessary to provide `subsetQs`, that specifies which of the qubits in `pspec`
the Clifford acts on. (All other qubits will not be part of the returned circuit, regardless of
whether that means an over-head is required to avoid using gates that act on those qubits. If these
additional qubits should be used, then the input Clifford needs to be ``padded'' to be the identity
on those qubits).
The ordering of the indices in (`s`,`p`) is w.r.t to ordering of the qubit labels in pspec.qubit_labels,
unless `subsetQs` is specified. Then, the ordering is taken w.r.t the ordering of the list `subsetQs`.
subsetQs : List, optional
Required if the Clifford to compile is over less qubits than `pspec`. In this case this is a
list of the qubits to compile the Clifford for; it should be a subset of the elements of
pspec.qubit_labels. The ordering of the qubits in (`s`,`p`) is taken w.r.t the ordering of this list.
iterations : int, optional
Some of the allowed algorithms are randomized. This is the number of iterations used in
algorithm if it is a randomized algorithm specified. If any randomized algorithms are specified,
the time taken by this function increases linearly with `iterations`. Increasing `iterations`
will often improve the obtained compilation (the "cost" of the obtained circuit, as specified
by `costfunction` may decrease towards some asymptotic value).
algorithm : str, optional
Specifies the algorithm used for the core part of the compilation: finding a circuit that is a Clifford
with `s` the symplectic matrix in its symplectic representation (a circuit that implements that desired
Clifford up to Pauli operators). The allowed values of this are:
- 'BGGE': A basic, deterministic global Gaussian elimination algorithm. Circuits obtained from this algorithm
contain, in expectation, O(n^2) 2-qubit gates. Although the returned circuit will respect device
connectivity, this algorithm does *not* take connectivity into account in an intelligient way. More details
on this algorithm are given in `compile_symplectic_with_ordered_global_gaussian_elimination()`; it is the
algorithm described in that docstring but with the qubit ordering fixed to the order in the input `s`.
- 'ROGGE': A randomized elimination order global Gaussian elimination algorithm. This is the same algorithm as
'BGGE' except that the order that the qubits are eliminated in is randomized. This results in significantly
lower-cost circuits than the 'BGGE' method (given sufficiently many iterations). More details are given in
the `compile_symplectic_with_random_ordered_global_gaussian_elimination()` docstring.
- 'iAGvGE': Our improved version of the Aaraonson-Gottesman method for compiling a Clifford circuit, which
uses 3 CNOT circuits and 3 1Q-gate layers (rather than the 5 CNOT circuit used in the algorithm of AG in
Phys. Rev. A 70 052328 (2004)), with the CNOT circuits compiled using Gaussian elimination. Note that this
algorithm appears to perform substantially worse than 'ROGGE', even though with an upgraded CNOT compiler
it is asymptotically optimal (unlike any of the GGE methods). Also, note that this algorithm is randomized:
there are many possible CNOT circuits (with non-equivalent action, individually) for the 2 of the 3 CNOT
stages, and we randomize over those possible circuits. This randomization is equivalent to the randomization
used in the stabilizer state/measurement compilers.
aargs : list, optional
If the algorithm can take optional arguments, not already specified as separate arguments above, then
this list is passed to the compile_symplectic algorithm as its final arguments.
costfunction : function or string, optional
If a function, it is a function that takes a circuit and `pspec` as the first and second inputs and
returns a 'cost' (a float) for the circuit. The circuit input to this function will be over the gates in
`pspec`, if a `pspec` has been provided, and as described above if not. This costfunction is used to decide
between different compilations when randomized algorithms are used: the lowest cost circuit is chosen. If
a string it must be one of:
- '2QGC' : the cost of the circuit is the number of 2-qubit gates it contains.
- 'depth' : the cost of the circuit is the depth of the circuit.
- '2QGC:x:depth:y' : the cost of the circuit is x * the number of 2-qubit gates in the circuit +
y * the depth of the circuit, where x and y are integers.
prefixpauli : bool, optional
The circuits are constructed by finding a circuit that implements the correct Clifford up to Pauli
operators, and then attaching a (compiled) Pauli layer to the start or end of this circuit. If this
bool is True (False) the Pauli layer is (pre-) post-fixed.
paulirandomize : bool, optional
If True then independent, uniformly random Pauli layers (a Pauli on each qubit) are inserted in between
every layer in the circuit. These Paulis are then compiled into the gates in `pspec`, if `pspec` is provided.
That is, this Pauli-frame-randomizes / Pauli-twirls the internal layers of this Clifford circuit. This can
be useful for preventing coherent addition of errors in the circuit.
Returns
-------
Circuit
A circuit implementing the input Clifford gate/circuit.
"""
assert(_symp.check_valid_clifford(s, p)), "Input is not a valid Clifford!"
n = _np.shape(s)[0] // 2
if pspec is not None:
if subsetQs is None:
assert(pspec.number_of_qubits == n), \
("If all the qubits in `pspec` are to be used, "
"the Clifford must be over all {} qubits!".format(pspec.number_of_qubits))
qubit_labels = pspec.qubit_labels
else:
assert(len(subsetQs) == n), "The subset of qubits to compile for is the wrong size for this CLifford!!"
qubit_labels = subsetQs
else:
assert(subsetQs is None), "subsetQs can only be specified if `pspec` is not None!"
qubit_labels = list(range(n))
# Create a circuit that implements a Clifford with symplectic matrix s. This is the core
# of this compiler, and is the part that can be implemented with different algorithms.
circuit = compile_symplectic(s, pspec=pspec, subsetQs=subsetQs, iterations=iterations, algorithms=[algorithm, ],
costfunction=costfunction, paulirandomize=paulirandomize, aargs={'algorithm': aargs},
check=False)
circuit = circuit.copy(editable=True)
temp_s, temp_p = _symp.symplectic_rep_of_clifford_circuit(circuit, pspec=pspec)
# Find the necessary Pauli layer to compile the correct Clifford, not just the correct
# Clifford up to Paulis. The required Pauli layer depends on whether we pre-fix or post-fix it.
if prefixpaulis: pauli_layer = _symp.find_premultipled_pauli(s, temp_p, p, qubit_labels=qubit_labels)
else: pauli_layer = _symp.find_postmultipled_pauli(s, temp_p, p, qubit_labels=qubit_labels)
# Turn the Pauli layer into a circuit.
pauli_circuit = _Circuit(layer_labels=pauli_layer, line_labels=qubit_labels, editable=True)
# Only change gate library of the Pauli circuit if we have a ProcessorSpec with compilations.
if pspec is not None:
pauli_circuit.change_gate_library(
pspec.compilations['absolute'], oneQgate_relations=pspec.oneQgate_relations) # identity=pspec.identity,
# Prefix or post-fix the Pauli circuit to the main symplectic-generating circuit.
if prefixpaulis: circuit.prefix_circuit(pauli_circuit)
else: circuit.append_circuit(pauli_circuit)
# If we aren't Pauli-randomizing, do a final bit of depth compression
if pspec is not None: circuit.compress_depth(oneQgate_relations=pspec.oneQgate_relations, verbosity=0)
else: circuit.compress_depth(verbosity=0)
# Check that the correct Clifford has been compiled. This should never fail, but could if
# the compilation provided for the internal gates is incorrect (the alternative is a mistake in this algorithm).
s_out, p_out = _symp.symplectic_rep_of_clifford_circuit(circuit, pspec=pspec)
assert(_np.array_equal(s, s_out))
assert(_np.array_equal(p, p_out))
return circuit
def compile_symplectic(s, pspec=None, subsetQs=None, iterations=20, algorithms=['ROGGE'],
costfunction='2QGC:10:depth:1', paulirandomize=False, aargs={}, check=True):
"""
Returns an n-qubit circuit that implements an n-qubit Clifford gate that is described by the symplectic
matrix `s` and *some* vector `p`. The circuit created by this function will be over a user-specified model
and respecting any desired connectivity, if a ProcessorSpec object is provided. Otherwise, it is over a
canonical model containing all-to-all CNOTs, Hadamard, Phase, 3 products of Hadamard and Phase, and the
Pauli gates.
Parameters
----------
s : array over [0,1]
An (2n X 2n) symplectic matrix of 0s and 1s integers.
pspec : ProcessorSpec, optional
An nbar-qubit ProcessorSpec object that encodes the device that `s` is being compiled
for, where nbar >= n. If this is specified, the output circuit is over the gates available
in this device. If this is None, the output circuit is over the "canonical" model of CNOT gates
between all qubits, consisting of "H", "HP", "PH", "HPH", "I", "X", "Y" and "Z", which is the set
used internally for the compilation.
If nbar > n it is necessary to provide `subsetQs`, that specifies which of the qubits in `pspec`
the Clifford acts on. (All other qubits will not be part of the returned circuit, regardless of
whether that means an over-head is required to avoid using gates that act on those qubits. If these
additional qubits should be used, then the input `s` needs to be ``padded'' to be the identity
on those qubits).
The indexing `s` is assumed to be the same as that in the list pspec.qubit_labels, unless `subsetQs`
is specified. Then, the ordering is taken w.r.t the ordering of the list `subsetQs`.
subsetQs : List, optional
Required if the Clifford to compile is over less qubits than `pspec`. In this case this is a
list of the qubits to compile the Clifford for; it should be a subset of the elements of pspec.qubit_labels.
The ordering of the qubits in (`s`,`p`) is taken w.r.t the ordering of this list.
iterations : int, optional
Some of the allowed algorithms are randomized. This is the number of iterations used in
each algorithm specified that is a randomized algorithm.
algorithms : list of strings, optional
Specifies the algorithms used. If more than one algorithm is specified, then all the algorithms
are implemented and the lowest "cost" circuit obtained from all the algorithms (and iterations of
those algorithms, if randomized) is returned.
The allowed elements of this list are:
- 'BGGE': A basic, deterministic global Gaussian elimination algorithm. Circuits obtained from this algorithm
contain, in expectation, O(n^2) 2-qubit gates. Although the returned circuit will respect device
connectivity, this algorithm does *not* take connectivity into account in an intelligient way. More details
on this algorithm are given in `compile_symplectic_with_ordered_global_gaussian_elimination()`; it is the
algorithm described in that docstring but with the qubit ordering fixed to the order in the input `s`.
- 'ROGGE': A randomized elimination order global Gaussian elimination algorithm. This is the same algorithm as
'BGGE' except that the order that the qubits are eliminated in is randomized. This results in significantly
lower-cost circuits than the 'BGGE' method (given sufficiently many iterations). More details are given in
the `compile_symplectic_with_random_ordered_global_gaussian_elimination()` docstring.
- 'iAGvGE': Our improved version of the Aaraonson-Gottesman method for compiling a symplectic matrix, which
uses 3 CNOT circuits and 3 1Q-gate layers (rather than the 5 CNOT circuit used in the algorithm of AG in
Phys. Rev. A 70 052328 (2004)), with the CNOT circuits compiled using Gaussian elimination. Note that this
algorithm appears to perform substantially worse than 'ROGGE', even though with an upgraded CNOT compiler
it is asymptotically optimal (unlike any of the GGE methods). Also, note that this algorithm is randomized:
there are many possible CNOT circuits (with non-equivalent action, individually) for the 2 of the 3 CNOT
stages, and we randomize over those possible circuits. This randomization is equivalent to the randomization
used in the stabilizer state/measurement compilers.
costfunction : function or string, optional
If a function, it is a function that takes a circuit and `pspec` as the first and second inputs and
returns a cost (a float) for the circuit. The circuit input to this function will be over the gates in
`pspec`, if a `pspec` has been provided, and as described above if not. This costfunction is used to decide
between different compilations when randomized algorithms are used: the lowest cost circuit is chosen. If
a string it must be one of:
- '2QGC' : the cost of the circuit is the number of 2-qubit gates it contains.
- 'depth' : the cost of the circuit is the depth of the circuit.
- '2QGC:x:depth:y' : the cost of the circuit is x * the number of 2-qubit gates in the circuit +
y * the depth of the circuit, where x and y are integers.
paulirandomize : bool, optional
If True then independent, uniformly random Pauli layers (a Pauli on each qubit) are inserted in between
every layer in the circuit. These Paulis are then compiled into the gates in `pspec`, if `pspec` is provided.
That is, this Pauli-frame-randomizes / Pauli-twirls the internal layers of this Clifford circuit. This can
be useful for preventing coherent addition of errors in the circuit.
aargs : dict, optional
If the algorithm can take optional arguments, not already specified as separate arguments above, then
the list arrgs[algorithmname] is passed to the compile_symplectic algorithm as its final arguments, where
`algorithmname` is the name of algorithm specified in the list `algorithms`.
check : bool, optional
Whether to check that the output circuit implements the correct symplectic matrix (i.e., tests for algorithm
success).
Returns
-------
Circuit
A circuit implementing the input Clifford gate/circuit.
"""
# The number of qubits the symplectic matrix is on.
n = _np.shape(s)[0] // 2
if pspec is not None:
if subsetQs is None:
assert(pspec.number_of_qubits == n), \
("If all the qubits in `pspec` are to be used, "
"`s` must be a symplectic matrix over {} qubits!".format(pspec.number_of_qubits))
else:
assert(len(subsetQs) == n), \
"The subset of qubits to compile `s` for is the wrong size for this symplectic matrix!"
else:
assert(subsetQs is None), "subsetQs can only be specified if `pspec` is not None!"
all_algorithms = ['BGGE', 'ROGGE', 'iAGvGE'] # Future: ['AGvGE','AGvPMH','iAGvPMH']
assert(set(algorithms).issubset(set(all_algorithms))), "One or more algorithms names are invalid!"
# A list to hold the compiled circuits, from which we'll choose the best one. Each algorithm
# only returns 1 circuit, so this will have the same length as the `algorithms` list.
circuits = []
# If the costfunction is a string, create the relevant "standard" costfunction function.
if _compat.isstr(costfunction):
costfunction = create_standard_cost_function(costfunction)
# Deterministic basic global Gaussian elimination
if 'BGGE' in algorithms:
if subsetQs is not None:
eliminationorder = list(range(len(subsetQs)))
elif pspec is not None:
eliminationorder = list(range(len(pspec.qubit_labels)))
else:
eliminationorder = list(range(n))
circuit = compile_symplectic_using_OGGE_algorithm(s, eliminationorder=eliminationorder, pspec=pspec,
subsetQs=subsetQs, ctype='basic', check=False)
circuits.append(circuit)
# Randomized basic global Gaussian elimination, whereby the order that the qubits are eliminated in
# is randomized.
if 'ROGGE' in algorithms:
circuit = compile_symplectic_using_ROGGE_algorithm(s, pspec=pspec, subsetQs=subsetQs, ctype='basic',
costfunction=costfunction, iterations=iterations,
check=False)
circuits.append(circuit)
# Future:
# The Aaraonson-Gottesman method for compiling a symplectic matrix using 5 CNOT circuits + local layers,
# with the CNOT circuits compiled using Gaussian elimination.
# if 'AGvGE' in algorithms:
# circuit = compile_symplectic_using_AG_algorithm(s, pspec=pspec, subsetQs=subsetQs, cnotmethod='GE',
# check=False)
# circuits.append(circuit)
# Future
# The Aaraonson-Gottesman method for compiling a symplectic matrix using 5 CNOT circuits + local layers,
# with the CNOT circuits compiled using the asymptotically optimal O(n^2/logn) CNOT circuit algorithm of
# PMH.
# if 'AGvPMH' in algorithms:
# circuit = compile_symplectic_using_AG_algorithm(s, pspec=pspec, subsetQs=subsetQs, cnotmethod = 'PMH',
# check=False)
# circuits.append(circuit)
# Our improved version of the Aaraonson-Gottesman method for compiling a symplectic matrix, which uses 3
# CNOT circuits and 3 1Q-gate layers, with the CNOT circuits compiled using Gaussian elimination.
if 'iAGvGE' in algorithms:
# This defaults to what we think is the best Gauss. elimin. based CNOT compiler in pyGSTi (this one may actual
# not be the best one though). Note that this is a randomized version of the algorithm (using the albert-factor
# randomization).
circuit = compile_symplectic_using_RiAG_algoritm(s, pspec, subsetQs=subsetQs, iterations=iterations,
cnotalg='COiCAGE', cargs=[], costfunction=costfunction,
check=False)
circuits.append(circuit)
# Future
# The Aaraonson-Gottesman method for compiling a symplectic matrix using 5 CNOT circuits + local layers,
# with the CNOT circuits compiled using the asymptotically optimal O(n^2/logn) CNOT circuit algorithm of
# PMH.
# if 'iAGvPMH' in algorithms:
# circuit = compile_symplectic_with_iAG_algorithm(s, pspec=pspec, subsetQs=subsetQs, cnotmethod = 'PMH',
# check=False)
# circuits.append(circuit)
# If multiple algorithms have be called, find the lowest cost circuit.
if len(circuits) > 1:
bestcost = _np.inf
for c in circuits:
c_cost = costfunction(c, pspec)
if c_cost < bestcost:
circuit = c.copy()
bestcost = c_cost
else: circuit = circuits[0]
# If we want to Pauli randomize the circuits, we insert a random compiled Pauli layer between every layer.
if paulirandomize:
paulilist = ['I', 'X', 'Y', 'Z']
d = circuit.depth()
for i in range(0, d + 1):
# Different labelling depending on subsetQs and pspec.
if pspec is None:
pcircuit = _Circuit(layer_labels=[_Label(paulilist[_np.random.randint(4)], k)
for k in range(n)], num_lines=n, identity='I')
else:
# Map the circuit to the correct qubit labels
if subsetQs is not None:
pcircuit = _Circuit(layer_labels=[_Label(paulilist[_np.random.randint(4)], subsetQs[k])
for k in range(n)],
line_labels=subsetQs, editable=True) # , identity=pspec.identity)
else:
pcircuit = _Circuit(layer_labels=[_Label(paulilist[_np.random.randint(4)], pspec.qubit_labels[k])
for k in range(n)],
line_labels=pspec.qubit_labels, editable=True) # , identity=pspec.identity)
# Compile the circuit into the native model, using an "absolute" compilation -- Pauli-equivalent is
# not sufficient here.
# identity=pspec.identity,
pcircuit.change_gate_library(pspec.compilations['absolute'],
oneQgate_relations=pspec.oneQgate_relations)
circuit.insert_circuit(pcircuit, d - i)
if check:
implemented_s, implemented_p = _symp.symplectic_rep_of_clifford_circuit(circuit, pspec=pspec)
assert(_np.array_equal(s, implemented_s))
return circuit
def compile_symplectic_using_ROGGE_algorithm(s, pspec=None, subsetQs=None, ctype='basic',
costfunction='2QGC:10:depth:1', iterations=10, check=True):
"""
The order global Gaussian elimiation algorithm of compile_symplectic_using_OGGE_algorithm() with the
qubit elimination order randomized. See that function for further details on the algorithm, This algorithm
is more conveniently and flexibly accessed via the `compile_symplectic()` or `compile_clifford()` wrap-around
functions.
Parameters
----------
s : array over [0,1]
An (2n X 2n) symplectic matrix of 0s and 1s integers.
pspec : ProcessorSpec, optional
An nbar-qubit ProcessorSpec object that encodes the device that `s` is being compiled
for, where nbar >= n. If this is specified, the output circuit is over the gates available
in this device. If this is None, the output circuit is over the "canonical" model of CNOT gates
between all qubits, consisting of "H", "HP", "PH", "HPH", "I", "X", "Y" and "Z", which is the set
used internally for the compilation.
If nbar > n it is necessary to provide `subsetQs`, that specifies which of the qubits in `pspec`
the Clifford acts on. (All other qubits will not be part of the returned circuit, regardless of
whether that means an over-head is required to avoid using gates that act on those qubits. If these
additional qubits should be used, then the input `s` needs to be ``padded'' to be the identity
on those qubits).
The indexing `s` is assumed to be the same as that in the list pspec.qubit_labels, unless `subsetQs`
is specified. Then, the ordering is taken w.r.t the ordering of the list `subsetQs`.
subsetQs : List, optional
Required if the Clifford to compile is over less qubits than `pspec`. In this case this is a
list of the qubits to compile the Clifford for; it should be a subset of the elements of pspec.qubit_labels.
The ordering of the qubits in (`s`,`p`) is taken w.r.t the ordering of this list.
ctype : str, optional
The particular variant on the global Gaussian elimiation core algorithm. Currently there is only one
such variant, corresponding to the string "basic".
iterations : int, optional
The number of different random orderings tried. The lowest "cost" circuit obtained from the
different orderings is what is returned.
costfunction : function or string, optional
If a function, it is a function that takes a circuit and `pspec` as the first and second inputs and
returns a cost (a float) for the circuit. The circuit input to this function will be over the gates in
`pspec`, if a `pspec` has been provided, and as described above if not. This costfunction is used to decide
between different compilations when randomized algorithms are used: the lowest cost circuit is chosen. If
a string it must be one of:
- '2QGC' : the cost of the circuit is the number of 2-qubit gates it contains.
- 'depth' : the cost of the circuit is the depth of the circuit.
- '2QGC:x:depth:y' : the cost of the circuit is x * the number of 2-qubit gates in the circuit +
y * the depth of the circuit, where x and y are integers.
check : bool, optional
Whether to check that the output circuit implements the correct symplectic matrix (i.e., tests for algorithm
success).
Returns
-------
Circuit
A circuit implementing the input symplectic matrix.
"""
# The number of qubits the symplectic matrix is on.
n = _np.shape(s)[0] // 2
# If the costfunction is a string, create the relevant "standard" costfunction function.
if _compat.isstr(costfunction):
costfunction = create_standard_cost_function(costfunction)
# The elimination order in terms of qubit *index*, which is randomized below.
if subsetQs is not None:
eliminationorder = list(range(len(subsetQs)))
elif pspec is not None:
eliminationorder = list(range(len(pspec.qubit_labels)))
else:
eliminationorder = list(range(n))
lowestcost = _np.inf
for i in range(0, iterations):
# Pick a random order to attempt the elimination in
_np.random.shuffle(eliminationorder)
# Call the re-ordered global Gaussian elimination, which is wrap-around for the GE algorithms to deal
# with qubit relabeling. Check is False avoids multiple checks of success, when only the last check matters.
circuit = compile_symplectic_using_OGGE_algorithm(
s, eliminationorder, pspec=pspec, subsetQs=subsetQs, ctype=ctype, check=False)
# Find the cost of the circuit, and keep it if this circuit is the lowest-cost circuit so far.
circuit_cost = costfunction(circuit, pspec)
if circuit_cost < lowestcost:
bestcircuit = circuit.copy()
lowestcost = circuit_cost
if check:
implemented_s, implemented_p = _symp.symplectic_rep_of_clifford_circuit(bestcircuit, pspec=pspec)
assert(_np.array_equal(s, implemented_s))
return bestcircuit
def compile_symplectic_using_OGGE_algorithm(s, eliminationorder, pspec=None, subsetQs=None, ctype='basic', check=True):
"""
An ordered global Gaussian elimiation algorithm for creating a circuit that implements a Clifford that is
represented by the symplectic matrix `s` (and *some* phase vector). This algorithm is more conveniently and flexibly
accessed via the `compile_symplectic()` or `compile_clifford()` wrap-around functions.
The algorithm works as follows:
1. The `s` matrix is permuted so that the index for the jth qubit to eliminate becomes index j.
2. The "global Gaussian elimination" algorithm of E. Hostens, J. Dehaene, and B. De Moor, PRA 71 042315 (2015) is
implemented, which can be used to decompose `s` into a circuit over CNOT, SWAP, H, and P. That algorithm is for
d-dimensional qudits, and simplifies significantly for d=2 (qubits), which is the case implemented here. However,
we are unware of anywhere else that this algorithm is clearly stated for the qubit case (although this basic
algorithm is widely known).
Parameters
----------
s : array over [0,1]
An (2n X 2n) symplectic matrix of 0s and 1s integers.
eliminationorder : list
The elimination order for the qubits. If `pspec` is specified, this should be a list consisting of the
qubit labels that `s` is over (this can be a subset of all qubits in `pspec` is `subsetQs` is None). If
`pspec` is not specified this list should consist of the integers between 0 and n-1 in any order, corresponding
to the indices of `s`.
pspec : ProcessorSpec, optional
An nbar-qubit ProcessorSpec object that encodes the device that `s` is being compiled
for, where nbar >= n. If this is specified, the output circuit is over the gates available
in this device. If this is None, the output circuit is over the "canonical" model of CNOT gates
between all qubits, consisting of "H", "HP", "PH", "HPH", "I", "X", "Y" and "Z", which is the set
used internally for the compilation.
If nbar > n it is necessary to provide `subsetQs`, that specifies which of the qubits in `pspec`
the Clifford acts on. (All other qubits will not be part of the returned circuit, regardless of
whether that means an over-head is required to avoid using gates that act on those qubits. If these
additional qubits should be used, then the input `s` needs to be ``padded'' to be the identity
on those qubits).
The indexing `s` is assumed to be the same as that in the list pspec.qubit_labels, unless `subsetQs`
is specified. Then, the ordering is taken w.r.t the ordering of the list `subsetQs`.
subsetQs : List, optional
Required if the Clifford to compile is over less qubits than `pspec`. In this case this is a
list of the qubits to compile the Clifford for; it should be a subset of the elements of pspec.qubit_labels.
The ordering of the qubits in (`s`,`p`) is taken w.r.t the ordering of this list.
ctype : str, optional
The particular variant on the global Gaussian elimiation core algorithm. Currently there is only one
such variant, corresponding to the string "basic".
check : bool, optional
Whether to check that the output circuit implements the correct symplectic matrix (i.e., tests for algorithm
success).
Returns
-------
Circuit
A circuit implementing the input symplectic matrix.
"""
# Re-order the s matrix to reflect the order we want to eliminate the qubits in,
# because we hand the symp. matrix to a function that eliminates them in a fixed order.
n = _np.shape(s)[0] // 2
P = _np.zeros((n, n), int)
for j in range(0, n):
P[j, eliminationorder[j]] = 1
P2n = _np.zeros((2 * n, 2 * n), int)
P2n[0:n, 0:n] = P
P2n[n:2 * n, n:2 * n] = P
permuted_s = _mtx.dotmod2(_mtx.dotmod2(P2n, s), _np.transpose(P2n))
if ctype == 'basic':
# Check is False avoids multiple checks of success, when only the last check matters.
circuit = compile_symplectic_using_GGE_core(permuted_s, check=False)
circuit = circuit.copy(editable=True) # make editable - maybe make `editable` a param of above fn call?
else: raise ValueError("The compilation sub-method is not valid!")
# Futures: write a connectivity-adjusted algorithm, similar to the COGE/iCAGE CNOT compilers.
# If the subsetQs is not None, we relabel the circuit in terms of the labels of these qubits.
if subsetQs is not None:
assert(len(eliminationorder) == len(subsetQs)
), "`subsetQs` must be the same length as `elimintionorder`! The mapping to qubit labels is ambigiuous!"
circuit.map_state_space_labels_inplace({i: subsetQs[eliminationorder[i]] for i in range(n)})
circuit.reorder_lines(subsetQs)
# If the subsetQs is None, but there is a pspec, we relabel the circuit in terms of the full set
# of pspec labels.
elif pspec is not None:
assert(len(eliminationorder) == len(pspec.qubit_labels)
), "If `subsetQs` is not specified `s` should be over all the qubits in `pspec`!"
circuit.map_state_space_labels_inplace({i: pspec.qubit_labels[eliminationorder[i]] for i in range(n)})
circuit.reorder_lines(pspec.qubit_labels)
else:
circuit.map_state_space_labels_inplace({i: eliminationorder[i] for i in range(n)})
circuit.reorder_lines(list(range(n)))
# If we have a pspec, we change the gate library. We use a pauli-equivalent compilation, as it is
# only necessary to implement each gate in this circuit up to Pauli matrices.
if pspec is not None:
if subsetQs is None:
# ,identity=pspec.identity,
circuit.change_gate_library(pspec.compilations['paulieq'], oneQgate_relations=pspec.oneQgate_relations)
else:
# identity=pspec.identity,
circuit.change_gate_library(pspec.compilations['paulieq'], allowed_filter=set(subsetQs),
oneQgate_relations=pspec.oneQgate_relations)
if check:
implemented_s, implemented_p = _symp.symplectic_rep_of_clifford_circuit(circuit, pspec=pspec)
assert(_np.array_equal(s, implemented_s))
return circuit
def compile_symplectic_using_GGE_core(s, check=True):
"""
Creates a circuit over 'I','H','HP','PH','HPH', and 'CNOT' that implements a Clifford
gate with `s` as its symplectic matrix in the symplectic representation (and with any
phase vector). This circuit is generated using a basic Gaussian elimination algorithm,
which is described in more detail in compile_symplectic_using_OGGE_algorithm(), which
is a wrap-around for this algorithm that implements a more flexible compilation method.
This algorithm is more conveniently accessed via the `compile_symplectic()` or
`compile_clifford()` functions.
Parameters
----------
s: array
A 2n X 2n symplectic matrix over [0,1] for any positive integer n. The returned
circuit is over n qubits.
check : bool, optional
Whether to check that the generated circuit does implement `s`.
Returns
-------
Circuit
A circuit that implements a Clifford that is represented by the symplectic matrix `s`.
"""
sout = _np.copy(s) # Copy so that we don't change the input s.
n = _np.shape(s)[0] // 2
assert(_symp.check_symplectic(s, convention='standard')), "The input matrix must be symplectic!"
instruction_list = []
# Map the portion of the symplectic matrix acting on qubit j to the identity, for j = 0,...,d-1 in
# turn, using the basic row operations corresponding to the CNOT, Hadamard, phase, and SWAP gates.
for j in range(n):
# *** Step 1: Set the upper half of column j to the relevant identity column ***
upperl_c = sout[:n, j]
lowerl_c = sout[n:, j]
upperl_ones = list(_np.nonzero(upperl_c == 1)[0])
lowerl_ones = list(_np.nonzero(lowerl_c == 1)[0])
# If the jth element in the column is not 1, it needs to be set to 1.
if j not in upperl_ones:
# First try using a Hadamard gate.
if j in lowerl_ones:
instruction_list.append(_Label('H', j))
_symp.apply_internal_gate_to_symplectic(sout, 'H', [j, ])
# Then try using a swap gate, we don't try and find the best qubit to swap with.
elif len(upperl_ones) >= 1:
instruction_list.append(_Label('CNOT', [j, upperl_ones[0]]))
instruction_list.append(_Label('CNOT', [upperl_ones[0], j]))
instruction_list.append(_Label('CNOT', [j, upperl_ones[0]]))
_symp.apply_internal_gate_to_symplectic(sout, 'SWAP', [j, upperl_ones[0]])
# Finally, try using swap and Hadamard gates, we don't try and find the best qubit to swap with.
else:
instruction_list.append(_Label('H', lowerl_ones[0]))
_symp.apply_internal_gate_to_symplectic(sout, 'H', [lowerl_ones[0], ])
instruction_list.append(_Label('CNOT', [j, lowerl_ones[0]]))
instruction_list.append(_Label('CNOT', [lowerl_ones[0], j]))
instruction_list.append(_Label('CNOT', [j, lowerl_ones[0]]))
_symp.apply_internal_gate_to_symplectic(sout, 'SWAP', [j, lowerl_ones[0]])
# Update the lists that keep track of where the 1s are in the column.
upperl_c = sout[:n, j]
lowerl_c = sout[n:, j]
upperl_ones = list(_np.nonzero(upperl_c == 1)[0])
lowerl_ones = list(_np.nonzero(lowerl_c == 1)[0])
# Pair up qubits with 1s in the jth upper jth column, and set all but the
# jth qubit to 0 in logarithmic depth. When there is an odd number of qubits
# one of them is left out in the layer.
while len(upperl_ones) >= 2:
num_pairs = len(upperl_ones) // 2
for i in range(0, num_pairs):
if upperl_ones[i + 1] != j:
controlq = upperl_ones[i]
targetq = upperl_ones[i + 1]
del upperl_ones[1 + i]
else:
controlq = upperl_ones[i + 1]
targetq = upperl_ones[i]
del upperl_ones[i]
instruction_list.append(_Label('CNOT', (controlq, targetq)))
_symp.apply_internal_gate_to_symplectic(sout, 'CNOT', [controlq, targetq])
# *** Step 2: Set the lower half of column j to all zeros ***
upperl_c = sout[:n, j]
lowerl_c = sout[n:, j]
upperl_ones = list(_np.nonzero(upperl_c == 1)[0])
lowerl_ones = list(_np.nonzero(lowerl_c == 1)[0])
# If the jth element in this lower column is 1, it must be set to 0.
if j in lowerl_ones:
instruction_list.append(_Label('P', j))
_symp.apply_internal_gate_to_symplectic(sout, 'P', [j, ])
# Move in the 1 from the upper part of the column, and use this to set all
# other elements to 0, as in Step 1.
instruction_list.append(_Label('H', j))
_symp.apply_internal_gate_to_symplectic(sout, 'H', [j, ])
upperl_c = None
upperl_ones = None
lowerl_c = sout[n:, j]
lowerl_ones = list(_np.nonzero(lowerl_c == 1)[0])
while len(lowerl_ones) >= 2:
num_pairs = len(lowerl_ones) // 2
for i in range(0, num_pairs):
if lowerl_ones[i + 1] != j:
controlq = lowerl_ones[i + 1]
targetq = lowerl_ones[i]
del lowerl_ones[1 + i]
else:
controlq = lowerl_ones[i]
targetq = lowerl_ones[i + 1]
del lowerl_ones[i]
instruction_list.append(_Label('CNOT', (controlq, targetq)))
_symp.apply_internal_gate_to_symplectic(sout, 'CNOT', [controlq, targetq])
# Move the 1 back to the upper column.
instruction_list.append(_Label('H', j))
_symp.apply_internal_gate_to_symplectic(sout, 'H', [j, ])
# *** Step 3: Set the lower half of column j+d to the relevant identity column ***
upperl_c = sout[:n, j + n]
lowerl_c = sout[n:, j + n]
upperl_ones = list(_np.nonzero(upperl_c == 1)[0])
lowerl_ones = list(_np.nonzero(lowerl_c == 1)[0])
while len(lowerl_ones) >= 2:
num_pairs = len(lowerl_ones) // 2
for i in range(0, num_pairs):
if lowerl_ones[i + 1] != j:
controlq = lowerl_ones[i + 1]
targetq = lowerl_ones[i]
del lowerl_ones[1 + i]
else:
controlq = lowerl_ones[i]
targetq = lowerl_ones[i + 1]
del lowerl_ones[i]
instruction_list.append(_Label('CNOT', (controlq, targetq)))
_symp.apply_internal_gate_to_symplectic(sout, 'CNOT', [controlq, targetq])
# *** Step 4: Set the upper half of column j+d to all zeros ***
upperl_c = sout[:n, j + n]
lowerl_c = sout[n:, j + n]
upperl_ones = list(_np.nonzero(upperl_c == 1)[0])
lowerl_ones = list(_np.nonzero(lowerl_c == 1)[0])
# If the jth element in the upper column is 1 it must be set to zero
if j in upperl_ones:
instruction_list.append(_Label('H', j))
_symp.apply_internal_gate_to_symplectic(sout, 'H', [j, ])
instruction_list.append(_Label('P', j))
_symp.apply_internal_gate_to_symplectic(sout, 'P', [j, ])
instruction_list.append(_Label('H', j))
_symp.apply_internal_gate_to_symplectic(sout, 'H', [j, ])
# Switch in the 1 from the lower column
instruction_list.append(_Label('H', j))
_symp.apply_internal_gate_to_symplectic(sout, 'H', [j, ])
upperl_c = sout[:n, j + n]
upperl_ones = list(_np.nonzero(upperl_c == 1)[0])
lowerl_c = None
lowerl_ones = None
while len(upperl_ones) >= 2:
num_pairs = len(upperl_ones) // 2
for i in range(0, num_pairs):
if upperl_ones[i + 1] != j:
controlq = upperl_ones[i]
targetq = upperl_ones[i + 1]
del upperl_ones[1 + i]
else:
controlq = upperl_ones[i + 1]
targetq = upperl_ones[i]
del upperl_ones[i]
instruction_list.append(_Label('CNOT', (controlq, targetq)))
_symp.apply_internal_gate_to_symplectic(sout, 'CNOT', [controlq, targetq])
# Switch the 1 back to the lower column
instruction_list.append(_Label('H', j))
_symp.apply_internal_gate_to_symplectic(sout, 'H', [j], optype='row')
# If the matrix has been mapped to the identity, quit the loop as we are done.
if _np.array_equal(sout, _np.identity(2 * n, int)):
break
assert(_np.array_equal(sout, _np.identity(2 * n, int))), "Compilation has failed!"
# Operations that are the same next to each other cancel, and this algorithm can have these. So
# we go through and delete them.
j = 1
depth = len(instruction_list)
while j < depth:
if instruction_list[depth - j] == instruction_list[depth - j - 1]:
del instruction_list[depth - j]
del instruction_list[depth - j - 1]
j = j + 2
else:
j = j + 1
# We turn the instruction list into a circuit over the internal gates.
circuit = _Circuit(layer_labels=instruction_list, num_lines=n, editable=True) # ,identity='I')
# That circuit implements the inverse of s (it maps s to the identity). As all the gates in this
# set are self-inverse (up to Pauli multiplication) we just reverse the circuit to get a circuit
# for s.
circuit.reverse()
# To do the depth compression, we use the 1-qubit gate relations for the standard set of gates used
# here.
oneQgate_relations = _symp.oneQclifford_symplectic_group_relations()
circuit.compress_depth(oneQgate_relations=oneQgate_relations, verbosity=0)
# We check that the correct Clifford -- up to Pauli operators -- has been implemented.
if check:
implemented_s, implemented_p = _symp.symplectic_rep_of_clifford_circuit(circuit)
assert(_np.array_equal(s, implemented_s))
circuit.done_editing()
return circuit
def compile_symplectic_using_AG_algorithm(s, pspec=None, subsetQs=None, cnotmethod='PMH', check=False):
"""
The Aaraonson-Gottesman method for compiling a symplectic matrix using 5 CNOT circuits + local layers.
This algorithm is presented in PRA 70 052328 (2014).
- If `cnotmethod` = `GE` then the CNOT circuits are compiled using Gaussian elimination (which is O(n^2)).
There are multiple GE algorithms for compiling a CNOT in pyGSTi. This function has the over-all best
variant of this algorithm hard-coded into this function.
- If `cnotmethod` = `PMH` then the CNOT circuits are compiled using the asymptotically optimal
O(n^2/logn) CNOT circuit algorithm of PMH.
*** This function has not yet been implemented ***
"""
raise NotImplementedError("This method is not yet written!")
circuit = None
return circuit
def compile_symplectic_using_RiAG_algoritm(s, pspec, subsetQs=None, iterations=20, cnotalg='COiCAGE',
cargs=[], costfunction='2QGC:10:depth:1', check=True):
"""
Our improved version of Aaraonson-Gottesman method [PRA 70 052328 (2014)] for compiling a symplectic matrix
using 5 CNOT circuits + local layers. Our version of this algorithm uses 3 CNOT circuits, and 3 layers of
1-qubit gates. Also, note that this algorithm is randomized: there are many possible CNOT circuits (with
non-equivalent action, individually) for the 2 of the 3 CNOT stages, and we randomize over those possible
circuits. This randomization is equivalent to the randomization used in the stabilizer state/measurement
compilers.
Note that this algorithm currently performs substantially worse than 'ROGGE', even though with an upgraded
CNOT compiler it is asymptotically optimal (unlike any of the GGE methods).
Parameters
----------
s : array over [0,1]
An (2n X 2n) symplectic matrix of 0s and 1s integers.
pspec : ProcessorSpec
An nbar-qubit ProcessorSpec object that encodes the device that `s` is being compiled
for, where nbar >= n. If this is specified, the output circuit is over the gates available
in this device. If this is None, the output circuit is over the "canonical" model of CNOT gates
between all qubits, consisting of "H", "HP", "PH", "HPH", "I", "X", "Y" and "Z", which is the set
used internally for the compilation.
If nbar > n it is necessary to provide `subsetQs`, that specifies which of the qubits in `pspec`
the Clifford acts on. (All other qubits will not be part of the returned circuit, regardless of
whether that means an over-head is required to avoid using gates that act on those qubits. If these
additional qubits should be used, then the input `s` needs to be ``padded'' to be the identity
on those qubits).
The indexing `s` is assumed to be the same as that in the list pspec.qubit_labels, unless `subsetQs`
is specified. Then, the ordering is taken w.r.t the ordering of the list `subsetQs`.
subsetQs : List, optional
Required if the Clifford to compile is over less qubits than `pspec`. In this case this is a
list of the qubits to compile the Clifford for; it should be a subset of the elements of pspec.qubit_labels.
The ordering of the qubits in (`s`,`p`) is taken w.r.t the ordering of this list.
iterations : int, optional
The number of different random orderings tried. The lowest "cost" circuit obtained from the
different orderings is what is returned.
cnotalg : str, optional
The CNOT compiler to use. See `compile_cnot_circuit()` for the options. The default is *probably*
the current best CNOT circuit compiler in pyGSTI.
cargs : list, optional
Arguments handed to the CNOT compilation algorithm. For some choices of `cnotalg` this is not
optional.
costfunction : function or string, optional
If a function, it is a function that takes a circuit and `pspec` as the first and second inputs and
returns a cost (a float) for the circuit. The circuit input to this function will be over the gates in
`pspec`, if a `pspec` has been provided, and as described above if not. This costfunction is used to decide
between different compilations when randomized algorithms are used: the lowest cost circuit is chosen. If
a string it must be one of:
- '2QGC' : the cost of the circuit is the number of 2-qubit gates it contains.
- 'depth' : the cost of the circuit is the depth of the circuit.
- '2QGC:x:depth:y' : the cost of the circuit is x * the number of 2-qubit gates in the circuit +
y * the depth of the circuit, where x and y are integers.
check : bool, optional
Whether to check that the output circuit implements the correct symplectic matrix (i.e., tests for algorithm
success).
Returns
-------
Circuit
A circuit implementing the input symplectic matrix.
"""
# If the costfunction is a string, create the relevant "standard" costfunction function.
if _compat.isstr(costfunction): costfunction = create_standard_cost_function(costfunction)
mincost = _np.inf
for i in range(iterations):
circuit = compile_symplectic_using_iAG_algorithm(
s, pspec, subsetQs=subsetQs, cnotalg=cnotalg, cargs=cargs, check=False)
# Change to the native gate library
if pspec is not None: # Currently pspec is not optional, so this always happens.
circuit = circuit.copy(editable=True)
if subsetQs is None:
# ,identity=pspec.identity
circuit.change_gate_library(pspec.compilations['paulieq'], oneQgate_relations=pspec.oneQgate_relations)
else:
# identity=pspec.identity,
circuit.change_gate_library(pspec.compilations['paulieq'], allowed_filter=set(subsetQs),