-
Notifications
You must be signed in to change notification settings - Fork 54
/
Copy pathfiducialselection.py
2020 lines (1680 loc) · 93.2 KB
/
fiducialselection.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
"""
Functions for selecting a complete set of fiducials for a GST analysis.
"""
#***************************************************************************************************
# Copyright 2015, 2019, 2025 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 scipy
import random
import itertools
from warnings import warn
from math import floor
from pygsti.algorithms import grasp as _grasp
from pygsti.algorithms import scoring as _scoring
from pygsti import circuits as _circuits
from pygsti import baseobjs as _baseobjs
from pygsti.modelmembers.povms import ComplementPOVMEffect as _ComplementPOVMEffect
from pygsti.tools import frobeniusdist_squared
from pygsti.algorithms.germselection import construct_update_cache, minamide_style_inverse_trace, compact_EVD, compact_EVD_via_SVD
def find_fiducials(target_model, omit_identity=True, eq_thresh=1e-6,
ops_to_omit=None, force_empty=True, candidate_fid_counts=2,
algorithm='grasp', algorithm_kwargs=None, verbosity=1,
prep_fids=True, meas_fids=True, candidate_list=None,
return_candidate_list=False, final_test= False,
assume_clifford=False, candidate_seed=None,
max_fid_length=None):
"""
Generate prep and measurement fiducials for a given target model.
Parameters
----------
target_model : Model
The model you are aiming to implement.
omit_identity : bool, optional
Whether to remove the identity gate from the set of gates with which
fiducials are constructed. Identity gates do nothing to alter
fiducials, and so should almost always be left out.
eq_thresh : float, optional
Threshold for determining if a gate is the identity gate. If the square
Frobenius distance between a given gate and the identity gate is less
than this threshold, the gate is considered to be an identity gate and
will be removed from the list of gates from which to construct
fiducials if `omit_identity` is ``True``.
ops_to_omit : list of string, optional
List of strings identifying gates in the model that should not be
used in fiducials. Oftentimes this will include the identity gate, and
may also include entangling gates if their fidelity is anticipated to
be much worse than that of single-system gates.
force_empty : bool, optional (default is True)
Whether or not to force all fiducial sets to contain the empty gate
string as a fiducial.
candidate_fid_counts : int or dic, optional
A dictionary of *fid_length* : *count* key-value pairs, specifying
the fiducial "candidate list" - a list of potential fiducials to draw from.
*count* is either an integer specifying the number of random fiducials
considered at the given *fid_length* or the special values `"all upto"`
that considers all of the of all the fiducials of length up to
the corresponding *fid_length*. If the keyword 'all' is used for the
count value then all circuits at that particular length are added.
If and integer, all germs of up to length
that length are used, the equivalent of `{specified_int: 'all upto'}`.
algorithm : {'slack', 'grasp', 'greedy'}, optional
Specifies the algorithm to use to generate the fiducials. Current
options are:
'slack'
See :func:`_find_fiducials_integer_slack` for more details.
'grasp'
Use GRASP to generate random greedy fiducial sets and then locally
optimize them. See :func:`_find_fiducials_grasp` for more
details.
'greedy'
Use a greedy algorithm accelerated using low-rank update techniques.
See :func:`_find_fiducials_greedy` for more
details.
algorithm_kwargs : dict
Dictionary of ``{'keyword': keyword_arg}`` pairs providing keyword
arguments for the specified `algorithm` function. See the documentation
for functions referred to in the `algorithm` keyword documentation for
what options are available for each algorithm.
verbosity : int, optional
How much detail to send to stdout.
candidate_list : list of circuits, optional
A user specified manually selected list of candidate fiducial circuits.
Can speed up testing multiple objective function options, for example.
return_candidate_list: bool, optional (default False)
When True we return the full list of deduped candidate fiducials considered
along with the final fiducial lists.
final_test : bool, optional (default False)
When true a final check is performed on the returned solution for the candidate
prep and measurement lists using the function test_fiducial_list to verify
we have an acceptable candidate set (this uses a different code path in some cases so
can be used to detect errors).
assume_clifford : bool, optional (default False)
When true then we assume that all of the circuits are clifford circuits,
which allows us to use a faster deduping routine exploiting the properties
of clifford circuits.
max_fid_length : int, optional (deprecated)
The maximum number of gates to include in a fiducial. The default is
not guaranteed to work for arbitrary models (particularly for quantum
systems larger than a single qubit). This keyword is now deprecated.
The behavior of the keyword is now equivalent to passing in an int
for the candidate_fid_counts argument.
Returns
-------
prepFidList : list of Circuits
A list containing the circuits for the prep fiducials.
measFidList : list of Circuits
A list containing the circuits for the measurement fiducials.
"""
printer = _baseobjs.VerbosityPrinter.create_printer(verbosity)
#If the user hasn't specified a candidate list manually then generate one:
if candidate_list is None:
availableFidList = create_candidate_fiducial_list(target_model, omit_identity= omit_identity,
ops_to_omit = ops_to_omit,
candidate_fid_counts=candidate_fid_counts,
max_fid_length= max_fid_length,
eq_thresh= eq_thresh, candidate_seed = candidate_seed)
printer.log('Initial Length Available Fiducial List: '+ str(len(availableFidList)), 1)
printer.log('Creating cache of fiducial process matrices.', 3)
circuit_cache= create_circuit_cache(target_model, availableFidList)
printer.log('Completed cache of fiducial process matrices.', 3)
#Now that we have a cache of PTMs as numpy arrays for the initial list of available fiducials
#we can clean this list up to remove any effective identities and circuits with duplicate effects.
#Use a flag to check if we can assume these are clifford circuits in which case
#we can use a more efficient deduping routine.
cleaned_availableFidList, cleaned_circuit_cache = clean_fid_list(target_model, circuit_cache, availableFidList,
drop_identities=True, drop_duplicates=True,
eq_thresh=eq_thresh, assume_clifford=assume_clifford)
#add in logic forcing the empty fiducial into the candidate list if force_empty is true and it is not present.
if not any([len(ckt)==0 for ckt in cleaned_availableFidList]) and force_empty:
cleaned_availableFidList.append(_circuits.Circuit(_baseobjs.Label(()), line_labels= target_model.state_space.state_space_labels))
#and add this to the circuit cache.
cleaned_circuit_cache.update(create_circuit_cache(target_model, [cleaned_availableFidList[-1]]))
printer.log('Length Available Fiducial List Dropped Identities and Duplicates: ' + str(len(cleaned_availableFidList)), 1)
#TODO: I can speed this up a bit more by looking through the available fiducial list for
#circuits that are effective identities. Reducing the search space should be a big time-space
#saver.
#otherwise if the user has manually specified a list of fiducials then set cleaned_availableFidList to that and
#create the circuit cache.
else:
cleaned_availableFidList = candidate_list
cleaned_circuit_cache= create_circuit_cache(target_model, cleaned_availableFidList)
#generate a cache for the allowed preps and effects based on availableFidList
if prep_fids:
prep_cache= create_prep_cache(target_model, cleaned_availableFidList, cleaned_circuit_cache)
#TODO: I can technically speed things up even more if we're using the same
#set of available fidcuials for state prep and measurement since we only
#would need to do generate the transfer matrices for each circuit once.
#probably not the most impactful change for the short-term though, performance
#wise.
if meas_fids:
meas_cache= create_meas_cache(target_model, cleaned_availableFidList, cleaned_circuit_cache)
#define function for final test result printing
def final_result_test(final_fids, verb_printer):
if final_fids:
verb_printer.log('Final test of the candidate meas fiducial lists passed.', 1)
else:
verb_printer.log('Final test of the candidate meas fiducial lists failed.', 1)
if algorithm_kwargs is None:
# Avoid danger of using empty dict for default value.
algorithm_kwargs = {}
if algorithm == 'slack':
printer.log('Using slack algorithm.', 1)
default_kwargs = {
'fid_list': cleaned_availableFidList,
'verbosity': max(0, verbosity - 1),
'force_empty': force_empty,
'score_func': 'all',
}
if ('slack_frac' not in algorithm_kwargs
and 'fixed_slack' not in algorithm_kwargs):
algorithm_kwargs['slack_frac'] = 1.0
for key in default_kwargs:
if key not in algorithm_kwargs:
algorithm_kwargs[key] = default_kwargs[key]
prepFidList = _find_fiducials_integer_slack(model=target_model,
prep_or_meas='prep',
**algorithm_kwargs)
if prepFidList is not None:
prepScore = compute_composite_fiducial_score(
target_model, prepFidList, 'prep',
score_func=algorithm_kwargs['score_func'])
printer.log('Preparation fiducials:', 1)
printer.log(str([fid.str for fid in prepFidList]), 1)
printer.log('Score: {}'.format(prepScore.minor), 1)
#if requested do a final check with test_fiducial_list
#to verify the algorithm succeeds
if final_test:
final_test_fiducial_list = test_fiducial_list(target_model, prepFidList, 'prep',
score_func=algorithm_kwargs['score_func'], return_all=False,
threshold=algorithm_kwargs.get('threshold', 1e-6), fid_cache=prep_cache)
final_result_test(final_test_fiducial_list, printer)
measFidList = _find_fiducials_integer_slack(model=target_model,
prep_or_meas='meas',
**algorithm_kwargs)
if measFidList is not None:
measScore = compute_composite_fiducial_score(
target_model, measFidList, 'meas',
score_func=algorithm_kwargs['score_func'])
printer.log('Measurement fiducials:', 1)
printer.log(str([fid.str for fid in measFidList]), 1)
printer.log('Score: {}'.format(measScore.minor), 1)
#if requested do a final check with test_fiducial_list
#to verify the algorithm succeeds
if final_test:
final_test_fiducial_list = test_fiducial_list(target_model, measFidList, 'meas',
score_func=algorithm_kwargs['score_func'], return_all=False,
threshold=algorithm_kwargs.get('threshold', 1e-6), fid_cache=meas_cache)
final_result_test(final_test_fiducial_list, printer)
elif algorithm == 'grasp':
printer.log('Using GRASP algorithm.', 1)
default_kwargs = {
'fids_list': cleaned_availableFidList,
'alpha': 0.1, # No real reason for setting this value of alpha.
'op_penalty': 0.1,
'verbosity': max(0, verbosity - 1),
'force_empty': force_empty,
'score_func': 'all',
'return_all': False,
}
for key in default_kwargs:
if key not in algorithm_kwargs:
algorithm_kwargs[key] = default_kwargs[key]
#initialize the prep and measurement fid lists to None
#so that None gets returned if we aren't running that part
#of the fiducial search.
prepFidList=None
measFidList=None
if prep_fids:
prepFidList = _find_fiducials_grasp(model=target_model,
prep_or_meas='prep',
fid_cache= prep_cache,
**algorithm_kwargs)
if algorithm_kwargs['return_all'] and prepFidList[0] is not None:
prepScore = compute_composite_fiducial_score(
target_model, prepFidList[0], 'prep',
score_func=algorithm_kwargs['score_func'])
printer.log('Preparation fiducials:', 1)
printer.log(str([fid.str for fid in prepFidList[0]]), 1)
printer.log('Score: {}'.format(prepScore.minor), 1)
#if requested do a final check with test_fiducial_list
#to verify the algorithm succeeds
if final_test:
final_test_fiducial_list = test_fiducial_list(target_model, prepFidList[0], 'prep',
score_func=algorithm_kwargs['score_func'], return_all=False,
threshold=algorithm_kwargs.get('threshold', 1e-6), fid_cache=prep_cache)
final_result_test(final_test_fiducial_list, printer)
elif not algorithm_kwargs['return_all'] and prepFidList is not None:
prepScore = compute_composite_fiducial_score(
target_model, prepFidList, 'prep',
score_func=algorithm_kwargs['score_func'])
printer.log('Preparation fiducials:', 1)
printer.log(str([fid.str for fid in prepFidList]), 1)
printer.log('Score: {}'.format(prepScore.minor), 1)
#if requested do a final check with test_fiducial_list
#to verify the algorithm succeeds
if final_test:
final_test_fiducial_list = test_fiducial_list(target_model, prepFidList, 'prep',
score_func=algorithm_kwargs['score_func'], return_all=False,
threshold=algorithm_kwargs.get('threshold', 1e-6), fid_cache=prep_cache)
final_result_test(final_test_fiducial_list, printer)
if meas_fids:
measFidList = _find_fiducials_grasp(model=target_model,
prep_or_meas='meas',
fid_cache=meas_cache,
**algorithm_kwargs)
if algorithm_kwargs['return_all'] and measFidList[0] is not None:
measScore = compute_composite_fiducial_score(
target_model, measFidList[0], 'meas',
score_func=algorithm_kwargs['score_func'])
printer.log('Measurement fiducials:', 1)
printer.log(str([fid.str for fid in measFidList[0]]), 1)
printer.log('Score: {}'.format(measScore.minor), 1)
#if requested do a final check with test_fiducial_list
#to verify the algorithm succeeds
if final_test:
final_test_fiducial_list = test_fiducial_list(target_model, measFidList[0], 'meas',
score_func=algorithm_kwargs['score_func'], return_all=False,
threshold=algorithm_kwargs.get('threshold', 1e-6), fid_cache=meas_cache)
final_result_test(final_test_fiducial_list, printer)
elif not algorithm_kwargs['return_all'] and measFidList is not None:
measScore = compute_composite_fiducial_score(
target_model, measFidList, 'meas',
score_func=algorithm_kwargs['score_func'])
printer.log('Measurement fiducials:', 1)
printer.log(str([fid.str for fid in measFidList]), 1)
printer.log('Score: {}'.format(measScore.minor), 1)
#if requested do a final check with test_fiducial_list
#to verify the algorithm succeeds
if final_test:
final_test_fiducial_list = test_fiducial_list(target_model, measFidList, 'meas',
score_func=algorithm_kwargs['score_func'], return_all=False,
threshold=algorithm_kwargs.get('threshold', 1e-6), fid_cache=meas_cache)
final_result_test(final_test_fiducial_list, printer)
elif algorithm == 'greedy':
printer.log('Using greedy algorithm.', 1)
default_kwargs = {
'fids_list': cleaned_availableFidList,
'op_penalty': 0.1,
'verbosity': verbosity,
'force_empty': force_empty
}
#We only support 'all' for the score function with the
#greedy algorithm, so raise an error for other values.
if (algorithm_kwargs.get('score_func', None) is not None) and \
(algorithm_kwargs.get('score_func', None) != 'all'):
raise ValueError('The greedy fiducial search algorithm currently only support the score function \'all\'.')
for key in default_kwargs:
if key not in algorithm_kwargs:
algorithm_kwargs[key] = default_kwargs[key]
#initialize the prep and measurement fid lists to None
#so that None gets returned if we aren't running that part
#of the fiducial search.
prepFidList=None
measFidList=None
if prep_fids:
prepFidList, prepScore = _find_fiducials_greedy(model=target_model,
prep_or_meas='prep',
fid_cache= prep_cache,
**algorithm_kwargs)
if prepFidList is not None:
printer.log('Preparation fiducials:', 1)
printer.log(str([fid.str for fid in prepFidList]), 1)
printer.log('Score: {}'.format(prepScore.minor), 1)
#if requested do a final check with test_fiducial_list
#to verify the algorithm succeeds
if final_test:
final_test_fiducial_list = test_fiducial_list(target_model, prepFidList, 'prep',
score_func='all', return_all=False,
threshold=algorithm_kwargs.get('threshold', 1e-6), fid_cache=prep_cache)
final_result_test(final_test_fiducial_list, printer)
if meas_fids:
measFidList, measScore = _find_fiducials_greedy(model=target_model,
prep_or_meas='meas',
fid_cache=meas_cache,
**algorithm_kwargs)
if measFidList is not None:
printer.log('Measurement fiducials:', 1)
printer.log(str([fid.str for fid in measFidList]), 1)
printer.log('Score: {}'.format(measScore.minor), 1)
#if requested do a final check with test_fiducial_list
#to verify the algorithm succeeds
if final_test:
final_test_fiducial_list = test_fiducial_list(target_model, measFidList, 'meas',
score_func='all', return_all=False,
threshold=algorithm_kwargs.get('threshold', 1e-6),
fid_cache=meas_cache)
final_result_test(final_test_fiducial_list, printer)
else:
raise ValueError("'{}' is not a valid algorithm "
"identifier.".format(algorithm))
if return_candidate_list:
return prepFidList, measFidList, cleaned_availableFidList
else:
return prepFidList, measFidList
def xor(*args):
"""
Implements logical xor function for arbitrary number of inputs.
Parameters
----------
args : bool-likes
All the boolean (or boolean-like) objects to be checked for xor
satisfaction.
Returns
-------
output : bool
True if and only if one and only one element of args is True and the
rest are False. False otherwise.
"""
output = sum(bool(x) for x in args) == 1
return output
#function for cleaning up the available fiducial list to drop identities and circuits with duplicate effects
def clean_fid_list(model, circuit_cache, available_fid_list,drop_identities=True, drop_duplicates=True, eq_thresh= 1e-6, assume_clifford=False):
#initialize an identity matrix of the appropriate dimension
cleaned_circuit_cache= circuit_cache.copy()
if drop_identities:
Identity = _np.identity(model.dim, 'd')
#remove identities
for ckt_key, PTM in circuit_cache.items():
#Don't remove the empty circuit if it is in the list.
if ckt_key=='{}' or ckt_key==():
continue
#the default tolerance for allclose is probably fine.
if _np.linalg.norm(PTM- Identity)<eq_thresh:
#then delete that circuit from the cleaned dictionary
del cleaned_circuit_cache[ckt_key]
cleaned_circuit_cache_1= cleaned_circuit_cache.copy()
if drop_duplicates:
#remove circuits with duplicate PTMs
#The list of available fidcuials is typically
#generated in such a way to be listed in increasing order
#of depth, so if we search for dups in that order this should
#generally favor the shorted of a pair of duplicate PTMs.
#reverse the list so that the longer circuits are at the start and shorter
#at the end for better pop behavior.
#TODO: add an option to partition the list into smaller chunks to dedupe
#separately before regrouping and deduping as a whole. Heuristic, but should
#be a good deal faster.
if assume_clifford:
#Leverage the fact that we know that the PTMs for clifford circuits
#should correspond to signed permutation matrices. Take each of the
#permuation matrices, flatten them, then get a list of the non-zero
#indices. Then for these non-zero indices construct a second list of
#the sign of these entries. This should uniquely identify each of the
#signed permutations.
reversed_ckt_list = list(cleaned_circuit_cache_1.keys())
reversed_ckt_list.reverse()
unique_vec_perm_reps= {}
for ckt in reversed_ckt_list:
flattened_PTM= _np.ravel(cleaned_circuit_cache_1[ckt])
#round to the nearest integer.
rounded_flattened_PTM= _np.round(flattened_PTM, decimals=0)
nonzero_indices= _np.nonzero(rounded_flattened_PTM)[0]
#get the signs of the nonzero elements.
signs= _np.sign(rounded_flattened_PTM[nonzero_indices])
#concatenate these two arrays
nonzero_indices_and_signs = _np.concatenate((nonzero_indices,signs))
#cast this array to a tuple and then add it to the dictionary
#I think technically I can hash the ndarrays directly, but just
#to be safe cast these as tuples first.
#Actually, I don't think I need to do the deduping in 2 stages.
#I should be able to directly use the tuples as keys and the
#ckts as the values in a python dictionary (which is implemented
#using hash tables on the back end).
unique_vec_perm_reps[tuple(nonzero_indices_and_signs)]= ckt
#Now get the values of the unique_vec_perm_reps dictionary
#These should be the depuped circuits.
deduped_ckt_list= list(unique_vec_perm_reps.values())
#rebuild the circuit cache now that it has been de-duped:
cleaned_circuit_cache_2= {ckt_key: cleaned_circuit_cache_1[ckt_key] for ckt_key in deduped_ckt_list}
#otherwise use a more generic method that doesn't rely on the structure of cliffords (but is slower).
#TODO: There are even more heuristics that can be used to further refine the equivalence classes
#if needed for additional performance improvements down the line.
else:
cleaned_circs = _np.asarray(list(cleaned_circuit_cache_1.keys()))
#initialize an empty circuit cache for storing the deduped results.
cleaned_circuit_cache_2={}
#split the list of circuits into equivalence classes corresponding to their trace.
#if the trace of two matrices isn't the same they certainly can't be duplicates.
traces = _np.zeros(len(cleaned_circs))
for i, ckt_ptm in enumerate(cleaned_circuit_cache_1.values()):
traces[i] = _np.round(_np.trace(ckt_ptm), decimals = 7) #HARDCODED
#get the permutation that sorts the trace array.
trace_perm = _np.argsort(traces)
sorted_traces = traces[trace_perm]
sorted_circs = cleaned_circs[trace_perm]
#Now I need to split the arrays into subarrays based on the values of the trace.
_, unique_trace_counts = _np.unique(sorted_traces, return_counts=True)
if len(unique_trace_counts)>1:
trace_split_points = [unique_trace_counts[0]]
for i, unique_count in enumerate(unique_trace_counts[1:-1], start=1):
trace_split_points.append(unique_count+trace_split_points[i-1])
#now split the array
split_circs_trace= _np.split(sorted_circs, trace_split_points)
#otherwise don't split and set split_circs_trace to a list containting
#sorted_circs as a sublist
else:
split_circs_trace = [sorted_circs]
for circ_trace_sublist in split_circs_trace:
#next let's split these up into equivalence classes using the
#number of nonzero entries.
num_nonzero_entries = _np.zeros(len(circ_trace_sublist))
for i, ckt in enumerate(circ_trace_sublist):
num_nonzero_entries[i] = _np.count_nonzero(_np.abs(cleaned_circuit_cache_1[ckt])>1e-8) #HARDCODED
#now sort the list of circuits by the number of nonzero elements:
nonzero_perm = _np.argsort(num_nonzero_entries)
sorted_nonzero_entries = num_nonzero_entries[nonzero_perm]
sorted_circs_nonzero = circ_trace_sublist[nonzero_perm]
#Now I need to split the arrays into subarrays based on the values of the trace.
_, unique_nonzero_counts = _np.unique(sorted_nonzero_entries, return_counts=True)
if len(unique_nonzero_counts)>1:
nonzero_split_points = [unique_nonzero_counts[0]]
if len(unique_nonzero_counts>1):
for i, unique_count in enumerate(unique_nonzero_counts[1:-1], start=1):
nonzero_split_points.append(unique_count+nonzero_split_points[i-1])
#now split the array
split_circs_nonzero= _np.split(sorted_circs_nonzero, nonzero_split_points)
#otherwise don't split and set split_circs_nonzero to a list containting
#sorted_circs_nonzero as a sublist
else:
split_circs_nonzero = [sorted_circs_nonzero]
#Now for each of these sublists we can independently perform the deduping routine.
for circ_sublist in split_circs_nonzero:
unseen_circs = list(circ_sublist)
#with the new search routines above there is a good chance these sublists
#are not longer sorted by circuit length, so this reverse may or may not
#be useful.
unseen_circs.reverse()
deduped_ckt_list = []
#While unseen_circs is not empty
while unseen_circs:
current_ckt = unseen_circs.pop()
current_ckt_PTM = cleaned_circuit_cache_1[current_ckt]
deduped_ckt_list.append(current_ckt)
#now iterate through the remaining elements of the set of unseen circuits and remove any duplicates.
is_not_duplicate=[True]*len(unseen_circs)
for i, ckt in enumerate(unseen_circs):
test_ptm= cleaned_circuit_cache_1[ckt]
if _np.linalg.norm(test_ptm-current_ckt_PTM)<eq_thresh: #use same threshold as defined in the base find_fiducials functi
is_not_duplicate[i]=False
#reset the set of unseen circuits.
unseen_circs=list(itertools.compress(unseen_circs, is_not_duplicate))
#update the circuit cache with the deduped entries of the sublist.
cleaned_circuit_cache_2.update({ckt_key: cleaned_circuit_cache_1[ckt_key] for ckt_key in deduped_ckt_list})
#otherwise just make cleaned_circuit_cache_2 a copy of cleaned_circuit_cache from
#the identity dropping step.
else:
cleaned_circuit_cache_2= cleaned_circuit_cache.copy()
#now that we've de-duped the circuit_cache, we can pull out the keys to get the
#new list of available fiducials.
available_fid_list_strings= [ckt.str for ckt in available_fid_list]
cleaned_availableFidList=[]
for i, fid_string in enumerate(available_fid_list_strings):
if fid_string in cleaned_circuit_cache_2:
cleaned_availableFidList.append(available_fid_list[i])
return cleaned_availableFidList, cleaned_circuit_cache_2
#new function for taking a list of available fiducials and generating a cache of the PTMs
#this will also be useful trimming the list of effective identities and fiducials with
#duplicated effects.
def create_circuit_cache(model, circuit_list):
"""
Function for generating a cache of PTMs for the available fiducials.
Parameters
----------
model : Model
The model (associates operation matrices with operation labels).
ckt_list : list of Circuits
Full list of all fiducial circuits avalable for constructing an informationally complete state preparation.
Returns
-------
dictionary
A dictionary with keys given by circuits with corresponding
entries being the PTMs for that circuit.
"""
circuit_cache= {}
for circuit in circuit_list:
circuit_cache[circuit.str] = model.sim.product(circuit)
return circuit_cache
#new function for generating a cache for the elements of the prep matrices and measurement matrices
#produced by create_prep_mxs and create_meas_mxs. Will also update those two functions to take a cache as
#an argument and generate the list returned by them more efficiently.
def create_prep_cache(model, available_prep_fid_list, circuit_cache=None):
"""
Make a dictionary structure mapping native state preps and circuits to numpy
column vectors for the corresponding effective state prep.
This can then be passed into 'create_prep_mxs' to more efficiently generate the
matrices for score function evaluation.
Parameters
----------
model : Model
The model (associates operation matrices with operation labels).
available_prep_fid_list : list of Circuits
Full list of all fiducial circuits avalable for constructing an informationally complete state preparation.
circuit_cache : dict
dictionary of PTMs for the circuits in the available_prep_fid_list
Returns
-------
dictionary
A dictionary with keys given be tuples of the form (native_prep, ckt) with corresponding
entries being the numpy vectors for that state prep.
"""
prep_cache = {}
keylist=[]
if circuit_cache is not None:
for rho in model.preps.values():
new_key= rho.to_vector().tobytes()
keylist.append(new_key)
for prepFid in available_prep_fid_list:
prep_cache[(new_key,prepFid.str)] = _np.dot(circuit_cache[prepFid.str], rho.to_dense())
else:
for rho in model.preps.values():
new_key= rho.to_vector().tobytes()
keylist.append(new_key)
for prepFid in available_prep_fid_list:
prep_cache[(new_key,prepFid.str)] = _np.dot(model.sim.product(prepFid), rho.to_dense())
return prep_cache, keylist
def create_meas_cache(model, available_meas_fid_list, circuit_cache=None):
"""
Make a dictionary structure mapping native measurements and circuits to numpy
column vectors corresponding to the transpose of the effective measurement effects.
This can then be passed into 'create_meas_mxs' to more efficiently generate the
matrices for score function evaluation.
Parameters
----------
model : Model
The model (associates operation matrices with operation labels).
available_meas_fid_list : list of Circuits
Full list of all fiducial circuits avalable for constructing an informationally complete measurements.
circuit_cache : dict
dictionary of PTMs for the circuits in the available_meas_fid_list
Returns
-------
tuple with dictionary and lists of POVM and Effect Key pairs.
A dictionary with keys given be tuples of the form (native_povm, native_povm_effect, ckt) with corresponding
entries being the numpy vectors for the transpose of that effective measurement effect.
"""
meas_cache = {}
keypairlist=[]
if circuit_cache is not None:
for povm in model.povms.values():
for E in povm.values():
new_povm_effect_key_pair= (povm.to_vector().tobytes(), E.to_dense().tobytes())
keypairlist.append(new_povm_effect_key_pair)
for measFid in available_meas_fid_list:
meas_cache[(new_povm_effect_key_pair[0],new_povm_effect_key_pair[1],measFid.str)] = _np.dot(E.to_dense(), circuit_cache[measFid.str])
else:
for povm in model.povms.values():
for E in povm.values():
new_povm_effect_key_pair= (povm.to_vector().tobytes(), E.to_dense().tobytes())
keypairlist.append(new_povm_effect_key_pair)
for measFid in available_meas_fid_list:
meas_cache[(new_povm_effect_key_pair[0],new_povm_effect_key_pair[1],measFid.str)] = _np.dot(E.to_dense(), model.sim.product(measFid))
return meas_cache, keypairlist
def create_prep_mxs(model, prep_fid_list, prep_cache=None):
"""
Make a list of matrices for the model preparation operations.
Makes a list of matrices, where each matrix corresponds to a single
preparation operation in the model, and the column of each matrix is a
fiducial acting on that state preparation.
Parameters
----------
model : Model
The model (associates operation matrices with operation labels).
prep_fid_list : list of Circuits
List of fiducial circuits for constructing an informationally complete state preparation.
prep_cache : dictionary of effective state preps
Dictionary of effective state preps cache used to accelerate the generation of the matrices
used for score function evaluation. Default value is None.
Returns
-------
list
A list of matrices, each of shape `(dim, len(prep_fid_list))` where
`dim` is the dimension of `model` (4 for a single qubit). The length
of this list is equal to the number of state preparations in `model`.
"""
dimRho = model.dim
#numRho = len(model.preps)
numFid = len(prep_fid_list)
outputMatList = []
if prep_cache is not None:
for rho_key in prep_cache[1]:
outputMat = _np.zeros([dimRho, numFid], float)
for i, prepFid in enumerate(prep_fid_list):
#if the key doesn't exist in the cache for some reason then we'll revert back to
#doing the matrix multiplication again.
#Actually, this is slowing things down a good amount, let's just print a
#descriptive error message if the key is missing
try:
outputMat[:, i] = prep_cache[0][(rho_key,prepFid.str)]
except KeyError as err:
print('A (Rho, Circuit) pair is missing from the cache, all such pairs should be available is using the caching option.')
raise err
outputMatList.append(outputMat)
else:
for rho in model.preps.values():
outputMat = _np.zeros([dimRho, numFid], float)
for i, prepFid in enumerate(prep_fid_list):
outputMat[:, i] = _np.dot(model.sim.product(prepFid), rho.to_dense())
outputMatList.append(outputMat)
return outputMatList
def create_meas_mxs(model, meas_fid_list, meas_cache=None):
"""
Make a list of matrices for the model measurement operations.
Makes a list of matrices, where each matrix corresponds to a single
measurement effect in the model, and the column of each matrix is the
transpose of the measurement effect acting on a fiducial.
Parameters
----------
model : Model
The model (associates operation matrices with operation labels).
meas_fid_list : list of Circuits
List of fiducial circuits for constructing an informationally complete measurement.
meas_cache : dictionary of effective measurement effects
Dictionary of effective measurement effects cache used to accelerate the generation of the matrices
used for score function evaluation. Entries are columns of the transpose of the effects. Default value is None.
Returns
-------
list
A list of matrices, each of shape `(dim, len(meas_fid_list))` where
`dim` is the dimension of `model` (4 for a single qubit). The length
of this list is equal to the number of POVM effects in `model`.
"""
dimE = model.dim
numFid = len(meas_fid_list)
outputMatList = []
if meas_cache is not None:
for povm_key, E_key in meas_cache[1]:
outputMat = _np.zeros([dimE, numFid], float)
for i, measFid in enumerate(meas_fid_list):
#if the key doesn't exist in the cache for some reason then we'll revert back to
#doing the matrix multiplication again.
#Actually, this is slowing things down a good amount, let's just print a
#descriptive error message if the key is missing
try:
outputMat[:, i] = meas_cache[0][(povm_key, E_key, measFid.str)]
except KeyError as err:
print('A (POVM, Effect, Circuit) pair is missing from the cache, all such pairs should be available if using the caching option.')
raise err
outputMatList.append(outputMat)
else:
for povm in model.povms.values():
for E in povm.values():
outputMat = _np.zeros([dimE, numFid], float)
for i, measFid in enumerate(meas_fid_list):
outputMat[:, i] = _np.dot(E.to_dense(), model.sim.product(measFid))
outputMatList.append(outputMat)
return outputMatList
def compute_composite_fiducial_score(model, fid_list, prep_or_meas, score_func='all',
threshold=1e6, return_all=False, op_penalty=0.0,
l1_penalty=0.0, gate_penalty=None, fid_cache= None):
"""
Compute a composite score for a fiducial list.
Parameters
----------
model : Model
The model (associates operation matrices with operation labels).
fid_list : list of Circuits
List of fiducial circuits to test.
prep_or_meas : string ("prep" or "meas")
Are we testing preparation or measurement fiducials?
score_func : str ('all' or 'worst'), optional (default is 'all')
Sets the objective function for scoring a fiducial set. If 'all',
score is (number of fiducials) * sum(1/Eigenvalues of score matrix).
If 'worst', score is (number of fiducials) * 1/min(Eigenvalues of score
matrix). Note: Choosing 'worst' corresponds to trying to make the
optimizer make the "worst" direction (the one we are least sensitive to
in Hilbert-Schmidt space) as minimally bad as possible. Choosing 'all'
corresponds to trying to make the optimizer make us as sensitive as
possible to all directions in Hilbert-Schmidt space. (Also note-
because we are using a simple integer program to choose fiducials, it
is possible to get stuck in a local minimum, and choosing one or the
other objective function can help avoid such minima in different
circumstances.)
threshold : float, optional (default is 1e6)
Specifies a maximum score for the score matrix, above which the
fiducial set is rejected as informationally incomplete.
return_all : bool, optional (default is False)
Whether the spectrum should be returned along with the score.
op_penalty : float, optional (default is 0.0)
Coefficient of a penalty linear in the total number of gates in all
fiducials that is added to ``score.minor``.
l1_penalty : float, optional (default is 0.0)
Coefficient of a penalty linear in the number of fiducials that is
added to ``score.minor``.
gate_penalty : dict, optional
A dictionary with keys given by individual gates and values corresponding
to the penalty to add for each instance of that gate in the fiducial set.
fid_cache : dict, optional (default is None)
A dictionary of either effective state preparations or measurement effects
used to accelerate the generation of the matrix used for scoring.
It's assumed that the user will pass in the correct cache based on the type
of fiducial set being created (if wrong a fall back will revert to redoing all the
matrix multiplication again).
Returns
-------
score : CompositeScore
The score of the fiducials.
spectrum : numpy.array, optional
The eigenvalues of the square of the absolute value of the score
matrix.
"""
# dimRho = model.dim
if prep_or_meas == 'prep':
fidArrayList = create_prep_mxs(model, fid_list, fid_cache)
elif prep_or_meas == 'meas':
fidArrayList = create_meas_mxs(model, fid_list, fid_cache)
else:
raise ValueError('Invalid value "{}" for prep_or_meas (must be "prep" '
'or "meas")!'.format(prep_or_meas))
numFids = len(fid_list)
scoreMx = _np.concatenate(fidArrayList, axis=1) # shape = (dimRho, nFiducials*nPrepsOrEffects)
scoreSqMx = _np.dot(scoreMx, scoreMx.T) # shape = (dimRho, dimRho)
spectrum = _np.sort(_np.abs(_np.linalg.eigvalsh(scoreSqMx)))
specLen = len(spectrum)
N_nonzero = specLen- _np.count_nonzero(spectrum<10**-10) #HARDCODED Spectrum Threshold
if N_nonzero==0:
nonzero_score = _np.inf
else:
#The scoring function in list_score is meant to be generic, but for
#performance reasons I want to take advantage of the fact that I know
#certain things have already been done to the spectrum, so I'm going to
#inline the scoring here and leave list_score alone.
#don't need to check for zeros since I already counted the number
#of nonzero eigenvalues above and handled that case there
if score_func == 'all':
#no need to the absolute value since I did that above
#Non-np sum and min are faster for small arrays/lists but slower for
#large ones.
nonzero_score = numFids*_np.sum(1. /spectrum[-N_nonzero:])
elif score_func == 'worst':
nonzero_score = numFids*(1. / _np.min(spectrum[-N_nonzero:]))
else:
raise ValueError("'%s' is not a valid value for score_func. "
"Either 'all' or 'worst' must be specified!"
% score_func)
#nonzero_score = numFids * _scoring.list_score(spectrum[-N_nonzero:], score_func)
# nonzero_score = _np.inf
# for N in range(1, specLen + 1):
# print(spectrum[-N:])
# score = numFids * _scoring.list_score(spectrum[-N:], score_func)
# if score <= 0 or _np.isinf(score) or score > threshold:
# break # We've found a zero eigenvalue.
# else:
# nonzero_score = score
# N_nonzero = N
#the implementation of the above scoring loop can be made much faster
nonzero_score += l1_penalty * len(fid_list)
nonzero_score += op_penalty * sum([len(fiducial) for fiducial in fid_list])
#add the gate penalties.
if gate_penalty is not None:
for gate, penalty_value in gate_penalty.items():
#loop through each ckt in the fiducial list.
for fiducial in fid_list:
#alternative approach using the string
#representation of the ckt.
num_gate_instances= fiducial.str.count(gate)
nonzero_score+= num_gate_instances*penalty_value
score = _scoring.CompositeScore(-N_nonzero, nonzero_score, N_nonzero)
return (score, spectrum) if return_all else score
def test_fiducial_list(model, fid_list, prep_or_meas, score_func='all',
return_all=False, threshold=1e6, l1_penalty=0.0,
op_penalty=0.0, fid_cache=None):
"""
Tests a prep or measure fiducial list for informational completeness.
Parameters
----------
model : Model
The model (associates operation matrices with operation labels).
fid_list : list of Circuits
List of fiducial circuits to test.
prep_or_meas : string ("prep" or "meas")
Are we testing preparation or measurement fiducials?