/
longsequence.py
1480 lines (1242 loc) · 72.2 KB
/
longsequence.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
""" End-to-end functions for performing long-sequence GST """
from __future__ import division, print_function, absolute_import, unicode_literals
#*****************************************************************
# pyGSTi 0.9: Copyright 2015 Sandia Corporation
# This Software is released under the GPL license detailed
# in the file "license.txt" in the top-level pyGSTi directory
#*****************************************************************
import os as _os
import warnings as _warnings
import numpy as _np
import time as _time
import collections as _collections
import pickle as _pickle
from scipy.stats import chi2 as _chi2
from .. import algorithms as _alg
from .. import construction as _construction
from .. import objects as _objs
from .. import io as _io
from .. import tools as _tools
from ..tools import compattools as _compat
from ..baseobjs import DummyProfiler as _DummyProfiler
ROBUST_SUFFIX_LIST = [".robust", ".Robust", ".robust+", ".Robust+"]
DEFAULT_BAD_FIT_THRESHOLD = 2.0
def do_model_test(modelGateFilenameOrSet,
dataFilenameOrSet, targetGateFilenameOrSet,
prepStrsListOrFilename, effectStrsListOrFilename,
germsListOrFilename, maxLengths, gaugeOptParams=None,
advancedOptions=None, comm=None, memLimit=None,
output_pkl=None, verbosity=2):
"""
Tests a GateSet model against a DataSet using a specific set of structured
gate sequences (given by fiducials, maxLengths and germs).
Constructs gate strings by repeating germ strings an integer number of
times such that the length of the repeated germ is less than or equal to
the maximum length set in maxLengths. Each string thus constructed is
sandwiched between all pairs of (prep, effect) fiducial sequences.
`modelGateset` is used directly (without any optimization) as the
the gate set estimate at each maximum-length "iteration". The gate set
is given a trivial `default_gauge_group` so that it is not altered
during any gauge optimization step.
A :class:`~pygsti.report.Results` object is returned, which encapsulates
the gate set estimate and related parameters, and can be used with
report-generation routines.
Parameters
----------
modelGateFilenameOrSet : GateSet or string
The model gate set, specified either directly or by the filename of a
gateset file (text format).
dataFilenameOrSet : DataSet or string
The data set object to use for the analysis, specified either directly
or by the filename of a dataset file (assumed to be a pickled `DataSet`
if extension is 'pkl' otherwise assumed to be in pyGSTi's text format).
targetGateFilenameOrSet : GateSet or string
The target gate set, specified either directly or by the filename of a
gateset file (text format).
prepStrsListOrFilename : (list of GateStrings) or string
The state preparation fiducial gate strings, specified either directly
or by the filename of a gate string list file (text format).
effectStrsListOrFilename : (list of GateStrings) or string or None
The measurement fiducial gate strings, specified either directly or by
the filename of a gate string list file (text format). If ``None``,
then use the same strings as specified by prepStrsListOrFilename.
germsListOrFilename : (list of GateStrings) or string
The germ gate strings, specified either directly or by the filename of a
gate string list file (text format).
maxLengths : list of ints
List of integers, one per LSGST iteration, which set truncation lengths
for repeated germ strings. The list of gate strings for the i-th LSGST
iteration includes the repeated germs truncated to the L-values *up to*
and including the i-th one.
gaugeOptParams : dict, optional
A dictionary of arguments to :func:`gaugeopt_to_target`, specifying
how the final gauge optimization should be performed. The keys and
values of this dictionary may correspond to any of the arguments
of :func:`gaugeopt_to_target` *except* for the first `gateset`
argument, which is specified internally. The `targetGateset` argument,
*can* be set, but is specified internally when it isn't. If `None`,
then the dictionary `{'itemWeights': {'gates':1.0, 'spam':0.001}}`
is used. If `False`, then then *no* gauge optimization is performed.
advancedOptions : dict, optional
Specifies advanced options most of which deal with numerical details of
the objective function or expert-level functionality.
comm : mpi4py.MPI.Comm, optional
When not ``None``, an MPI communicator for distributing the computation
across multiple processors.
memLimit : int or None, optional
A rough memory limit in bytes which restricts the amount of memory
used (per core when run on multi-CPUs).
output_pkl : str or file, optional
If not None, a file(name) to `pickle.dump` the returned `Results` object
to (only the rank 0 process performs the dump when `comm` is not None).
verbosity : int, optional
The 'verbosity' option is an integer specifying the level of
detail printed to stdout during the calculation.
Returns
-------
Results
"""
#Get/load target & model gatesets
gs_model = _load_gateset(modelGateFilenameOrSet)
gs_target = _load_gateset(targetGateFilenameOrSet)
#Get/load fiducials and germs
prepStrs, effectStrs, germs = _load_fiducials_and_germs(
prepStrsListOrFilename,
effectStrsListOrFilename,
germsListOrFilename)
#Get/load dataset
ds = _load_dataset(dataFilenameOrSet, comm, verbosity)
#Construct GateString lists
lsgstLists = _get_lsgst_lists(ds, gs_target, prepStrs, effectStrs, germs,
maxLengths, advancedOptions, verbosity)
if gaugeOptParams is None: gaugeOptParams = {}
if advancedOptions is None: advancedOptions = {}
if advancedOptions.get('set trivial gauge group',True):
gs_model = gs_model.copy()
gs_model.default_gauge_group = _objs.TrivialGaugeGroup(gs_model.dim) #so no gauge opt is done
gs_lsgst_list = [ gs_model ]*len(maxLengths)
# #Starting Point - compute on rank 0 and distribute
#LGSTcompatibleGates = all([(isinstance(g,_objs.FullyParameterizedGate) or
# isinstance(g,_objs.TPParameterizedGate))
# for g in gs_target.gates.values()])
#if isinstance(lsgstLists[0],_objs.LsGermsStructure) and LGSTcompatibleGates:
# startingPt = advancedOptions.get('starting point',"LGST")
#else:
# startingPt = advancedOptions.get('starting point',"target")
#Create profiler
profile = advancedOptions.get('profile',1)
if profile == 0: profiler = _DummyProfiler()
elif profile == 1: profiler = _objs.Profiler(comm,False)
elif profile == 2: profiler = _objs.Profiler(comm,True)
else: raise ValueError("Invalid value for 'profile' argument (%s)"%profile)
parameters = _collections.OrderedDict()
parameters['objective'] = advancedOptions.get('objective','logl')
if parameters['objective'] == 'logl':
parameters['minProbClip'] = advancedOptions.get('minProbClip',1e-4)
parameters['radius'] = advancedOptions.get('radius',1e-4)
elif parameters['objective'] == 'chi2':
parameters['minProbClipForWeighting'] = advancedOptions.get(
'minProbClipForWeighting',1e-4)
else:
raise ValueError("Invalid objective: %s" % parameters['objective'])
parameters['profiler'] = profiler
parameters['gateLabelAliases'] = advancedOptions.get('gateLabelAliases',None)
parameters['truncScheme'] = advancedOptions.get('truncScheme', "whole germ powers")
parameters['weights'] = None
#Set a different default for onBadFit: don't do anything
if 'onBadFit' not in advancedOptions:
advancedOptions['onBadFit'] = [] # empty list => 'do nothing'
return _post_opt_processing('do_model_test', ds, gs_target, gs_model,
lsgstLists, parameters, None, gs_lsgst_list,
gaugeOptParams, advancedOptions, comm, memLimit,
output_pkl, verbosity, profiler)
def do_linear_gst(dataFilenameOrSet, targetGateFilenameOrSet,
prepStrsListOrFilename, effectStrsListOrFilename,
gaugeOptParams=None, advancedOptions=None, comm=None,
memLimit=None, output_pkl=None, verbosity=2):
"""
Perform Linear Gate Set Tomography (LGST).
This function differs from the lower level :function:`do_lgst` function
in that it may perform a post-LGST gauge optimization and this routine
returns a :class:`Results` object containing the LGST estimate.
Overall, this is a high-level driver routine which can be used similarly
to :function:`do_long_sequence_gst` whereas `do_lgst` is a low-level
routine used when building your own algorithms.
Parameters
----------
dataFilenameOrSet : DataSet or string
The data set object to use for the analysis, specified either directly
or by the filename of a dataset file (assumed to be a pickled `DataSet`
if extension is 'pkl' otherwise assumed to be in pyGSTi's text format).
targetGateFilenameOrSet : GateSet or string
The target gate set, specified either directly or by the filename of a
gateset file (text format).
prepStrsListOrFilename : (list of GateStrings) or string
The state preparation fiducial gate strings, specified either directly
or by the filename of a gate string list file (text format).
effectStrsListOrFilename : (list of GateStrings) or string or None
The measurement fiducial gate strings, specified either directly or by
the filename of a gate string list file (text format). If ``None``,
then use the same strings as specified by prepStrsListOrFilename.
gaugeOptParams : dict, optional
A dictionary of arguments to :func:`gaugeopt_to_target`, specifying
how the final gauge optimization should be performed. The keys and
values of this dictionary may correspond to any of the arguments
of :func:`gaugeopt_to_target` *except* for the first `gateset`
argument, which is specified internally. The `targetGateset` argument,
*can* be set, but is specified internally when it isn't. If `None`,
then the dictionary `{'itemWeights': {'gates':1.0, 'spam':0.001}}`
is used. If `False`, then then *no* gauge optimization is performed.
advancedOptions : dict, optional
Specifies advanced options most of which deal with numerical details of
the objective function or expert-level functionality. See
:function:`do_long_sequence_gst`.
comm : mpi4py.MPI.Comm, optional
When not ``None``, an MPI communicator for distributing the computation
across multiple processors. In this LGST case, this is just the gauge
optimization.
memLimit : int or None, optional
A rough memory limit in bytes which restricts the amount of memory
used (per core when run on multi-CPUs).
output_pkl : str or file, optional
If not None, a file(name) to `pickle.dump` the returned `Results` object
to (only the rank 0 process performs the dump when `comm` is not None).
verbosity : int, optional
The 'verbosity' option is an integer specifying the level of
detail printed to stdout during the calculation.
Returns
-------
Results
"""
gs_target = _load_gateset(targetGateFilenameOrSet)
germs = _construction.gatestring_list([()] + [(gl,) for gl in gs_target.gates.keys()]) # just the single gates
maxLengths = [1] # we only need maxLength == 1 when doing LGST
defAdvOptions = {'onBadFit': [], 'estimateLabel': 'LGST'}
if advancedOptions is None: advancedOptions = {}
advancedOptions.update(defAdvOptions)
advancedOptions['objective'] = 'lgst' # not override-able
return do_long_sequence_gst(dataFilenameOrSet, gs_target,
prepStrsListOrFilename,effectStrsListOrFilename,
germs, maxLengths, gaugeOptParams,
advancedOptions, comm, memLimit,
output_pkl, verbosity)
def do_long_sequence_gst(dataFilenameOrSet, targetGateFilenameOrSet,
prepStrsListOrFilename, effectStrsListOrFilename,
germsListOrFilename, maxLengths, gaugeOptParams=None,
advancedOptions=None, comm=None, memLimit=None,
output_pkl=None, verbosity=2):
"""
Perform end-to-end GST analysis using Ls and germs, with L as a maximum
length.
Constructs gate strings by repeating germ strings an integer number of
times such that the length of the repeated germ is less than or equal to
the maximum length set in maxLengths. The LGST estimate of the gates is
computed, gauge optimized, and then used as the seed for either LSGST or
MLEGST.
LSGST is iterated ``len(maxLengths)`` times with successively larger sets
of gate strings. On the i-th iteration, the repeated germs sequences
limited by ``maxLengths[i]`` are included in the growing set of strings
used by LSGST. The final iteration will use MLEGST when ``objective ==
"logl"`` to maximize the true log-likelihood instead of minimizing the
chi-squared function.
Once computed, the gate set estimates are optionally gauge optimized to
the CPTP space and then to the target gate set (using `gaugeOptRatio`
and `gaugeOptItemWeights`). A :class:`~pygsti.report.Results`
object is returned, which encapsulates the input and outputs of this GST
analysis, and can generate final end-user output such as reports and
presentations.
Parameters
----------
dataFilenameOrSet : DataSet or string
The data set object to use for the analysis, specified either directly
or by the filename of a dataset file (assumed to be a pickled `DataSet`
if extension is 'pkl' otherwise assumed to be in pyGSTi's text format).
targetGateFilenameOrSet : GateSet or string
The target gate set, specified either directly or by the filename of a
gateset file (text format).
prepStrsListOrFilename : (list of GateStrings) or string
The state preparation fiducial gate strings, specified either directly
or by the filename of a gate string list file (text format).
effectStrsListOrFilename : (list of GateStrings) or string or None
The measurement fiducial gate strings, specified either directly or by
the filename of a gate string list file (text format). If ``None``,
then use the same strings as specified by prepStrsListOrFilename.
germsListOrFilename : (list of GateStrings) or string
The germ gate strings, specified either directly or by the filename of a
gate string list file (text format).
maxLengths : list of ints
List of integers, one per LSGST iteration, which set truncation lengths
for repeated germ strings. The list of gate strings for the i-th LSGST
iteration includes the repeated germs truncated to the L-values *up to*
and including the i-th one.
gaugeOptParams : dict, optional
A dictionary of arguments to :func:`gaugeopt_to_target`, specifying
how the final gauge optimization should be performed. The keys and
values of this dictionary may correspond to any of the arguments
of :func:`gaugeopt_to_target` *except* for the first `gateset`
argument, which is specified internally. The `targetGateset` argument,
*can* be set, but is specified internally when it isn't. If `None`,
then the dictionary `{'itemWeights': {'gates':1.0, 'spam':0.001}}`
is used. If `False`, then then *no* gauge optimization is performed.
advancedOptions : dict, optional
Specifies advanced options most of which deal with numerical details of
the objective function or expert-level functionality. The allowed keys
and values include:
- objective = {'chi2', 'logl'}
- gateLabels = list of strings
- gsWeights = dict or None
- starting point = "LGST" (default) or "target" or GateSet
- depolarizeStart = float (default == 0)
- randomizeStart = float (default == 0)
- contractStartToCPTP = True / False (default)
- cptpPenaltyFactor = float (default = 0)
- tolerance = float or dict w/'relx','relf','f','jac' keys
- maxIterations = int
- fdIterations = int
- minProbClip = float
- minProbClipForWeighting = float (default == 1e-4)
- probClipInterval = tuple (default == (-1e6,1e6)
- radius = float (default == 1e-4)
- useFreqWeightedChiSq = True / False (default)
- nestedGateStringLists = True (default) / False
- includeLGST = True / False (default is True)
- distributeMethod = "default", "gatestrings" or "deriv"
- profile = int (default == 1)
- check = True / False (default)
- gateLabelAliases = dict (default = None)
- alwaysPerformMLE = bool (default = False)
- truncScheme = "whole germ powers" (default) or "truncated germ powers"
or "length as exponent"
- appendTo = Results (default = None)
- estimateLabel = str (default = "default")
- missingDataAction = {'drop','raise'} (default = 'drop')
- stringManipRules = list of (find,replace) tuples
- germLengthLimits = dict of form {germ: maxlength}
- recordOutput = bool (default = True)
comm : mpi4py.MPI.Comm, optional
When not ``None``, an MPI communicator for distributing the computation
across multiple processors.
memLimit : int or None, optional
A rough memory limit in bytes which restricts the amount of memory
used (per core when run on multi-CPUs).
output_pkl : str or file, optional
If not None, a file(name) to `pickle.dump` the returned `Results` object
to (only the rank 0 process performs the dump when `comm` is not None).
verbosity : int, optional
The 'verbosity' option is an integer specifying the level of
detail printed to stdout during the calculation.
- 0 -- prints nothing
- 1 -- shows progress bar for entire iterative GST
- 2 -- show summary details about each individual iteration
- 3 -- also shows outer iterations of LM algorithm
- 4 -- also shows inner iterations of LM algorithm
- 5 -- also shows detailed info from within jacobian
and objective function calls.
Returns
-------
Results
"""
#Now advanced options:
#gateLabels : list or tuple
# A list or tuple of the gate labels to use when generating the sets of
# gate strings used in LSGST iterations. If ``None``, then the gate
# labels of the target gateset will be used. This option is useful if
# you only want to include a *subset* of the available gates in the LSGST
# strings (e.g. leaving out the identity gate).
#
#weightsDict : dict, optional
# A dictionary with ``keys == gate strings`` and ``values ==
# multiplicative`` scaling factor for the corresponding gate string. The
# default is no weight scaling at all.
#
#gaugeOptRatio : float, optional
# The ratio spamWeight/gateWeight used for gauge optimizing to the target
# gate set.
#
#gaugeOptItemWeights : dict, optional
# Dictionary of weighting factors for individual gates and spam operators
# used during gauge optimization. Keys can be gate, state preparation,
# POVM effect, or spam labels. Values are floating point numbers. By
# default, gate weights are set to 1.0 and spam weights to gaugeOptRatio.
#profile : int, optional
# Whether or not to perform lightweight timing and memory profiling.
# Allowed values are:
#
# - 0 -- no profiling is performed
# - 1 -- profiling enabled, but don't print anything in-line
# - 2 -- profiling enabled, and print memory usage at checkpoints
#truncScheme : str, optional
# Truncation scheme used to interpret what the list of maximum lengths
# means. If unsure, leave as default. Allowed values are:
#
# - ``'whole germ powers'`` -- germs are repeated an integer number of
# times such that the length is less than or equal to the max.
# - ``'truncated germ powers'`` -- repeated germ string is truncated
# to be exactly equal to the max (partial germ at end is ok).
# - ``'length as exponent'`` -- max. length is instead interpreted
# as the germ exponent (the number of germ repetitions).
printer = _objs.VerbosityPrinter.build_printer(verbosity, comm)
if advancedOptions is None: advancedOptions = {}
if advancedOptions.get('recordOutput',True) and not printer.is_recording():
printer.start_recording()
#Get/load target gateset
gs_target = _load_gateset(targetGateFilenameOrSet)
#Get/load fiducials and germs
prepStrs, effectStrs, germs = _load_fiducials_and_germs(
prepStrsListOrFilename,
effectStrsListOrFilename,
germsListOrFilename)
#Get/load dataset
ds = _load_dataset(dataFilenameOrSet, comm, printer)
#Construct GateString lists
lsgstLists = _get_lsgst_lists(ds, gs_target, prepStrs, effectStrs, germs,
maxLengths, advancedOptions, printer)
return do_long_sequence_gst_base(ds, gs_target, lsgstLists, gaugeOptParams,
advancedOptions, comm, memLimit,
output_pkl, printer)
def do_long_sequence_gst_base(dataFilenameOrSet, targetGateFilenameOrSet,
lsgstLists, gaugeOptParams=None,
advancedOptions=None, comm=None, memLimit=None,
output_pkl=None, verbosity=2):
"""
A more fundamental interface for performing end-to-end GST.
Similar to :func:`do_long_sequence_gst` except this function takes
`lsgstLists`, a list of either raw gate string lists or of `LsGermsStruct`
gate-string-structure objects to define which gate seqences are used on
each GST iteration.
Parameters
----------
dataFilenameOrSet : DataSet or string
The data set object to use for the analysis, specified either directly
or by the filename of a dataset file (assumed to be a pickled `DataSet`
if extension is 'pkl' otherwise assumed to be in pyGSTi's text format).
targetGateFilenameOrSet : GateSet or string
The target gate set, specified either directly or by the filename of a
gateset file (text format).
lsgstLists : list of lists or LsGermsStruct(s)
An explicit list of either the raw gate string lists to be used in
the analysis or of LsGermsStruct objects, which additionally contain
the max-L, germ, and fiducial pair structure of a set of gate strings.
A single LsGermsStruct object can also be given, which is equivalent
to passing a list of successive L-value truncations of this object
(e.g. if the object has `Ls = [1,2,4]` then this is like passing
a list of three LsGermsStructs w/truncations `[1]`, `[1,2]`, and
`[1,2,4]`).
gaugeOptParams : dict, optional
A dictionary of arguments to :func:`gaugeopt_to_target`, specifying
how the final gauge optimization should be performed. The keys and
values of this dictionary may correspond to any of the arguments
of :func:`gaugeopt_to_target` *except* for the first `gateset`
argument, which is specified internally. The `targetGateset` argument,
*can* be set, but is specified internally when it isn't. If `None`,
then the dictionary `{'itemWeights': {'gates':1.0, 'spam':0.001}}`
is used. If `False`, then then *no* gauge optimization is performed.
advancedOptions : dict, optional
Specifies advanced options most of which deal with numerical details of
the objective function or expert-level functionality. See
:func:`do_long_sequence_gst` for a list of the allowed keys, with the
exception "nestedGateStringLists", "gateLabelAliases",
"includeLGST", and "truncScheme".
comm : mpi4py.MPI.Comm, optional
When not ``None``, an MPI communicator for distributing the computation
across multiple processors.
memLimit : int or None, optional
A rough memory limit in bytes which restricts the amount of memory
used (per core when run on multi-CPUs).
output_pkl : str or file, optional
If not None, a file(name) to `pickle.dump` the returned `Results` object
to (only the rank 0 process performs the dump when `comm` is not None).
verbosity : int, optional
The 'verbosity' option is an integer specifying the level of
detail printed to stdout during the calculation.
- 0 -- prints nothing
- 1 -- shows progress bar for entire iterative GST
- 2 -- show summary details about each individual iteration
- 3 -- also shows outer iterations of LM algorithm
- 4 -- also shows inner iterations of LM algorithm
- 5 -- also shows detailed info from within jacobian
and objective function calls.
Returns
-------
Results
"""
tRef = _time.time()
#Note: *don't* specify default dictionary arguments, as this is dangerous
# because they are mutable objects
if advancedOptions is None: advancedOptions = {}
if gaugeOptParams is None:
gaugeOptParams = {'itemWeights': {'gates':1.0, 'spam':0.001}}
profile = advancedOptions.get('profile',1)
if profile == 0: profiler = _DummyProfiler()
elif profile == 1: profiler = _objs.Profiler(comm,False)
elif profile == 2: profiler = _objs.Profiler(comm,True)
else: raise ValueError("Invalid value for 'profile' argument (%s)"%profile)
if 'verbosity' in advancedOptions: #for backward compatibility
_warnings.warn("'verbosity' as an advanced option is deprecated." +
" Please use the 'verbosity' argument directly.")
verbosity = advancedOptions['verbosity']
if 'memoryLimitInBytes' in advancedOptions: #for backward compatibility
_warnings.warn("'memoryLimitInBytes' as an advanced option is deprecated." +
" Please use the 'memLimit' argument directly.")
memLimit = advancedOptions['memoryLimitInBytes']
printer = _objs.VerbosityPrinter.build_printer(verbosity, comm)
if advancedOptions.get('recordOutput',True) and not printer.is_recording():
printer.start_recording()
#Get/load target gateset
gs_target = _load_gateset(targetGateFilenameOrSet)
#Get/load dataset
ds = _load_dataset(dataFilenameOrSet, comm, printer)
gate_dim = gs_target.get_dimension()
tNxt = _time.time()
profiler.add_time('do_long_sequence_gst: loading',tRef); tRef=tNxt
#Convert a single LsGermsStruct to a list if needed:
validStructTypes = (_objs.LsGermsStructure,_objs.LsGermsSerialStructure)
if isinstance(lsgstLists, validStructTypes):
master = lsgstLists
lsgstLists = [ master.truncate(Ls=master.Ls[0:i+1])
for i in range(len(master.Ls))]
#Starting Point - compute on rank 0 and distribute
LGSTcompatibleGates = all([(isinstance(g,_objs.FullyParameterizedGate) or
isinstance(g,_objs.TPParameterizedGate))
for g in gs_target.gates.values()])
if isinstance(lsgstLists[0],validStructTypes) and LGSTcompatibleGates:
startingPt = advancedOptions.get('starting point',"LGST")
else:
startingPt = advancedOptions.get('starting point',"target")
#Compute starting point
if startingPt == "LGST":
assert(isinstance(lsgstLists[0], validStructTypes)), \
"Cannot run LGST: fiducials not specified!"
gateLabels = advancedOptions.get('gateLabels',
list(gs_target.gates.keys()) +
list(gs_target.instruments.keys()) )
gs_start = _alg.do_lgst(ds, lsgstLists[0].prepStrs, lsgstLists[0].effectStrs, gs_target,
gateLabels, svdTruncateTo=gate_dim,
gateLabelAliases=lsgstLists[0].aliases,
verbosity=printer) # returns a gateset with the *same*
# parameterizations as gs_target
#In LGST case, gauge optimimize starting point to the target
# (historical; sometimes seems to help in practice, since it's gauge
# optimizing to physical gates (e.g. something in CPTP)
tol = gaugeOptParams.get('tol',1e-8) if gaugeOptParams else 1e-8
gs_start = _alg.gaugeopt_to_target(gs_start, gs_target, tol=tol, comm=comm)
#Note: use *default* gauge-opt params when optimizing
elif startingPt == "target":
gs_start = gs_target.copy()
elif isinstance(startingPt, _objs.GateSet):
gs_start = startingPt
startingPt = "User-supplied-GateSet" #for profiler log below
else:
raise ValueError("Invalid starting point: %s" % startingPt)
tNxt = _time.time()
profiler.add_time('do_long_sequence_gst: Starting Point (%s)'
% startingPt,tRef); tRef=tNxt
#Post-processing gs_start : done only on root proc in case there is any nondeterminism.
if comm is None or comm.Get_rank() == 0:
#Advanced Options can specify further manipulation of starting gate set
if advancedOptions.get('contractStartToCPTP',False):
gs_start = _alg.contract(gs_start, "CPTP")
raise ValueError("'contractStartToCPTP' has been removed b/c it can change the parameterization of a gateset")
if advancedOptions.get('depolarizeStart',0) > 0:
gs_start = gs_start.depolarize(gate_noise=advancedOptions.get('depolarizeStart',0))
if advancedOptions.get('randomizeStart',0) > 0:
v = gs_start.to_vector()
vrand = 2*(_np.random.random(len(v))-0.5) * advancedOptions.get('randomizeStart',0)
gs_start.from_vector(v + vrand)
if comm is not None: #broadcast starting gate set
#OLD: comm.bcast(gs_start, root=0)
comm.bcast(gs_start.to_vector(), root=0) # just broadcast *vector* to avoid huge pickles (if cached calcs!)
else:
#OLD: gs_start = comm.bcast(None, root=0)
v = comm.bcast(None, root=0)
gs_start.from_vector(v)
tNxt = _time.time()
profiler.add_time('do_long_sequence_gst: Prep Initial seed',tRef); tRef=tNxt
# lsgstLists can hold either gatestring lists or structures - get
# just the lists for calling core gst routines (structure is used only
# for LGST and post-analysis).
rawLists = [ l.allstrs if isinstance(l,validStructTypes) else l
for l in lsgstLists ]
aliases = lsgstLists[-1].aliases if isinstance(
lsgstLists[-1], validStructTypes) else None
aliases = advancedOptions.get('gateLabelAliases',aliases)
#Run Long-sequence GST on data
objective = advancedOptions.get('objective', 'logl')
args = dict(
dataset=ds,
startGateset=gs_start,
gateStringSetsToUseInEstimation=rawLists,
tol = advancedOptions.get('tolerance',1e-6),
cptp_penalty_factor = advancedOptions.get('cptpPenaltyFactor',0),
spam_penalty_factor = advancedOptions.get('spamPenaltyFactor',0),
maxiter = advancedOptions.get('maxIterations',100000),
fditer = advancedOptions.get('fdIterations', 1),
probClipInterval = advancedOptions.get('probClipInterval',(-1e6,1e6)),
returnAll=True,
gatestringWeightsDict=advancedOptions.get('gsWeights',None),
gateLabelAliases=aliases,
verbosity=printer,
memLimit=memLimit,
profiler=profiler,
comm=comm, distributeMethod=advancedOptions.get(
'distributeMethod',"default"),
check=advancedOptions.get('check',False),
evaltree_cache={} )
if objective == "chi2":
args['useFreqWeightedChiSq'] = advancedOptions.get(
'useFreqWeightedChiSq',False)
args['minProbClipForWeighting'] = advancedOptions.get(
'minProbClipForWeighting',1e-4)
args['check_jacobian'] = advancedOptions.get('check',False)
gs_lsgst_list = _alg.do_iterative_mc2gst(**args)
elif objective == "logl":
args['minProbClip'] = advancedOptions.get('minProbClip',1e-4)
args['radius'] = advancedOptions.get('radius',1e-4)
args['alwaysPerformMLE'] = advancedOptions.get('alwaysPerformMLE',False)
gs_lsgst_list = _alg.do_iterative_mlgst(**args)
elif objective == "lgst":
assert(startingPt == "LGST"), "Can only set objective=\"lgst\" for parameterizations compatible with LGST"
assert(len(lsgstLists) == 1), "Can only set objective=\"lgst\" with number if lists/max-lengths == 1"
gs_lsgst_list = [args['startGateset']]
else:
raise ValueError("Invalid objective: %s" % objective)
tNxt = _time.time()
profiler.add_time('do_long_sequence_gst: total long-seq. opt.',tRef); tRef=tNxt
#set parameters
parameters = _collections.OrderedDict()
parameters['objective'] = objective
parameters['memLimit'] = memLimit
parameters['starting point'] = startingPt
parameters['profiler'] = profiler
#from advanced options
parameters['minProbClip'] = \
advancedOptions.get('minProbClip',1e-4)
parameters['minProbClipForWeighting'] = \
advancedOptions.get('minProbClipForWeighting',1e-4)
parameters['probClipInterval'] = \
advancedOptions.get('probClipInterval',(-1e6,1e6))
parameters['radius'] = advancedOptions.get('radius',1e-4)
parameters['weights'] = advancedOptions.get('gsWeights',None)
parameters['cptpPenaltyFactor'] = advancedOptions.get('cptpPenaltyFactor',0)
parameters['spamPenaltyFactor'] = advancedOptions.get('spamPenaltyFactor',0)
parameters['distributeMethod'] = advancedOptions.get('distributeMethod','default')
parameters['depolarizeStart'] = advancedOptions.get('depolarizeStart',0)
parameters['randomizeStart'] = advancedOptions.get('randomizeStart',0)
parameters['contractStartToCPTP'] = advancedOptions.get('contractStartToCPTP',False)
parameters['tolerance'] = advancedOptions.get('tolerance',1e-6)
parameters['maxIterations'] = advancedOptions.get('maxIterations',100000)
parameters['useFreqWeightedChiSq'] = advancedOptions.get('useFreqWeightedChiSq',False)
parameters['nestedGateStringLists'] = advancedOptions.get('nestedGateStringLists',True)
parameters['profile'] = advancedOptions.get('profile',1)
parameters['check'] = advancedOptions.get('check',False)
parameters['truncScheme'] = advancedOptions.get('truncScheme', "whole germ powers")
parameters['gateLabelAliases'] = advancedOptions.get('gateLabelAliases',None)
parameters['includeLGST'] = advancedOptions.get('includeLGST', True)
return _post_opt_processing('do_long_sequence_gst', ds, gs_target, gs_start,
lsgstLists, parameters, args, gs_lsgst_list,
gaugeOptParams, advancedOptions, comm, memLimit,
output_pkl, printer, profiler, args['evaltree_cache'])
def do_stdpractice_gst(dataFilenameOrSet,targetGateFilenameOrSet,
prepStrsListOrFilename, effectStrsListOrFilename,
germsListOrFilename, maxLengths, modes="TP,CPTP,Target",
gaugeOptSuite=('single','unreliable2Q'),
gaugeOptTarget=None, modelsToTest=None, comm=None, memLimit=None,
advancedOptions=None, output_pkl=None, verbosity=2):
"""
Perform end-to-end GST analysis using standard practices.
This routines is an even higher-level driver than
:func:`do_long_sequence_gst`. It performs bottled, typically-useful,
runs of long sequence GST on a dataset. This essentially boils down
to running :func:`do_long_sequence_gst` one or more times using different
gate set parameterizations, and performing commonly-useful gauge
optimizations, based only on the high-level `modes` argument.
Parameters
----------
dataFilenameOrSet : DataSet or string
The data set object to use for the analysis, specified either directly
or by the filename of a dataset file (assumed to be a pickled `DataSet`
if extension is 'pkl' otherwise assumed to be in pyGSTi's text format).
targetGateFilenameOrSet : GateSet or string
The target gate set, specified either directly or by the filename of a
gateset file (text format).
prepStrsListOrFilename : (list of GateStrings) or string
The state preparation fiducial gate strings, specified either directly
or by the filename of a gate string list file (text format).
effectStrsListOrFilename : (list of GateStrings) or string or None
The measurement fiducial gate strings, specified either directly or by
the filename of a gate string list file (text format). If ``None``,
then use the same strings as specified by prepStrsListOrFilename.
germsListOrFilename : (list of GateStrings) or string
The germ gate strings, specified either directly or by the filename of a
gate string list file (text format).
maxLengths : list of ints
List of integers, one per LSGST iteration, which set truncation lengths
for repeated germ strings. The list of gate strings for the i-th LSGST
iteration includes the repeated germs truncated to the L-values *up to*
and including the i-th one.
modes : str, optional
A comma-separated list of modes which dictate what types of analyses
are performed. Currently, these correspond to different types of
parameterizations/constraints to apply to the estimated gate set.
The default value is usually fine. Allowed values are:
- "full" : full (completely unconstrained)
- "TP" : TP-constrained
- "CPTP" : Lindbladian CPTP-constrained
- "H+S" : Only Hamiltonian + Stochastic errors allowed (CPTP)
- "S" : Only Stochastic errors allowed (CPTP)
- "Target" : use the target (ideal) gates as the estimate
- <model> : any key in the `modelsToTest` argument
gaugeOptSuite : str or list or dict, optional
Specifies which gauge optimizations to perform on each estimate. A
string or list of strings (see below) specifies built-in sets of gauge
optimizations, otherwise `gaugeOptSuite` should be a dictionary of
gauge-optimization parameter dictionaries, as specified by the
`gaugeOptParams` argument of :func:`do_long_sequence_gst`. The key
names of `gaugeOptSuite` then label the gauge optimizations within
the resuling `Estimate` objects. The built-in suites are:
- "single" : performs only a single "best guess" gauge optimization.
- "varySpam" : varies spam weight and toggles SPAM penalty (0 or 1).
- "varySpamWt" : varies spam weight but no SPAM penalty.
- "varyValidSpamWt" : varies spam weight with SPAM penalty == 1.
- "toggleValidSpam" : toggles spame penalty (0 or 1); fixed SPAM wt.
- "unreliable2Q" : adds branch to a spam suite that weights 2Q gates less
- "none" : no gauge optimizations are performed.
gaugeOptTarget : GateSet, optional
If not None, a gate set to be used as the "target" for gauge-
optimization (only). This argument is useful when you want to
gauge optimize toward something other than the *ideal* target gates
given by `targetGateFilenameOrSet`, which are used as the default when
`gaugeOptTarget` is None.
modelsToTest : dict, optional
A dictionary of GateSet objects representing (gate-set) models to
test against the data. These GateSets are essentially hypotheses for
which (if any) model generated the data. The keys of this dictionary
can (and must, to actually test the models) be used within the comma-
separate list given by the `modes` argument.
comm : mpi4py.MPI.Comm, optional
When not ``None``, an MPI communicator for distributing the computation
across multiple processors.
memLimit : int or None, optional
A rough memory limit in bytes which restricts the amount of memory
used (per core when run on multi-CPUs).
advancedOptions : dict, optional
Specifies advanced options most of which deal with numerical details of
the objective function or expert-level functionality. Keys of this
dictionary can be any of the modes being computed (see the `modes`
argument) or 'all', which applies to all modes. Values are
dictionaries of advanced arguements - see :func:`do_long_sequence_gst`
for a list of the allowed keys for each such dictionary.
output_pkl : str or file, optional
If not None, a file(name) to `pickle.dump` the returned `Results` object
to (only the rank 0 process performs the dump when `comm` is not None).
verbosity : int, optional
The 'verbosity' option is an integer specifying the level of
detail printed to stdout during the calculation.
Returns
-------
Results
"""
printer = _objs.VerbosityPrinter.build_printer(verbosity, comm)
if modelsToTest is None: modelsToTest = {}
#Get/load target gateset
gs_target = _load_gateset(targetGateFilenameOrSet)
#Get/load fiducials and germs
prepStrs, effectStrs, germs = _load_fiducials_and_germs(
prepStrsListOrFilename,
effectStrsListOrFilename,
germsListOrFilename)
#Get/load dataset
ds = _load_dataset(dataFilenameOrSet, comm, printer)
ret = None
modes = modes.split(",")
with printer.progress_logging(1):
for i,mode in enumerate(modes):
printer.show_progress(i, len(modes), prefix='-- Std Practice: ', suffix=' (%s) --' % mode)
#prepare advanced options dictionary
if advancedOptions is not None:
advanced = advancedOptions.get('all',{})
advanced.update( advancedOptions.get(mode,{}) )
else: advanced = {}
if mode == "Target":
est_label = mode
tgt = gs_target.copy() #no parameterization change
tgt.default_gauge_group = _objs.TrivialGaugeGroup(tgt.dim) #so no gauge opt is done
advanced.update( {'appendTo': ret, 'estimateLabel': est_label,
'onBadFit': []} )
ret = do_model_test(gs_target, ds, tgt, prepStrs,
effectStrs, germs, maxLengths, False, advanced,
comm, memLimit, None, printer-1)
elif mode in ('full','TP','CPTP','H+S','S','static'): # mode is a parameterization
est_label = parameterization = mode #for now, 1-1 correspondence
tgt = gs_target.copy(); tgt.set_all_parameterizations(parameterization)
advanced.update( {'appendTo': ret, 'estimateLabel': est_label } )
ret = do_long_sequence_gst(ds, tgt, prepStrs, effectStrs, germs,
maxLengths, False, advanced, comm, memLimit,
None, printer-1)
elif mode in modelsToTest:
est_label = mode
tgt = gs_target.copy() #no parameterization change
tgt.default_gauge_group = _objs.TrivialGaugeGroup(tgt.dim) #so no gauge opt is done
advanced.update( {'appendTo': ret, 'estimateLabel': est_label } )
ret = do_model_test(modelsToTest[mode], ds, tgt, prepStrs,
effectStrs, germs, maxLengths, False, advanced,
comm, memLimit, None, printer-1)
else:
raise ValueError("Invalid item in 'modes' argument: %s" % mode)
#Get gauge optimization dictionary
assert(not printer.is_recording()); printer.start_recording()
gaugeOptSuite_dict = gaugeopt_suite_to_dictionary(gaugeOptSuite, tgt,
advancedOptions, printer-1)
if gaugeOptTarget is not None:
assert(isinstance(gaugeOptTarget,_objs.GateSet)),"`gaugeOptTarget` must be None or a GateSet"
for goparams in gaugeOptSuite_dict.values():
goparams_list = [goparams] if hasattr(goparams,'keys') else goparams
for goparams_dict in goparams_list:
if 'targetGateset' in goparams_dict:
_warnings.warn(("`gaugeOptTarget` argument is overriding"
"user-defined targetGateset in gauge opt"
"param dict(s)"))
goparams_dict.update( {'targetGateset': gaugeOptTarget } )
#Gauge optimize to list of gauge optimization parameters
for goLabel,goparams in gaugeOptSuite_dict.items():
printer.log("-- Performing '%s' gauge optimization on %s estimate --" % (goLabel,est_label),2)
gsStart = ret.estimates[est_label].get_start_gateset(goparams)
ret.estimates[est_label].add_gaugeoptimized(goparams, None, goLabel, comm, printer-3)
#Gauge optimize data-scaled estimate also
for suffix in ROBUST_SUFFIX_LIST:
if est_label + suffix in ret.estimates:
gsStart_robust = ret.estimates[est_label+suffix].get_start_gateset(goparams)
if gsStart_robust.frobeniusdist(gsStart) < 1e-8:
printer.log("-- Conveying '%s' gauge optimization to %s estimate --" % (goLabel,est_label+suffix),2)
params = ret.estimates[est_label].goparameters[goLabel] #no need to copy here
gsopt = ret.estimates[est_label].gatesets[goLabel].copy()
ret.estimates[est_label + suffix].add_gaugeoptimized(params, gsopt, goLabel, comm, printer-3)
else:
printer.log("-- Performing '%s' gauge optimization on %s estimate --" % (goLabel,est_label+suffix),2)
ret.estimates[est_label + suffix].add_gaugeoptimized(goparams, None, goLabel, comm, printer-3)
# Add gauge optimizations to end of any existing "stdout" meta info
if 'stdout' in ret.estimates[est_label].meta:
ret.estimates[est_label].meta['stdout'].extend(printer.stop_recording())
else:
ret.estimates[est_label].meta['stdout'] = printer.stop_recording()
#Write results to a pickle file if desired
if output_pkl and (comm is None or comm.Get_rank() == 0):
if _compat.isstr(output_pkl):
with open(output_pkl, 'wb') as pklfile:
_pickle.dump(ret, pklfile)
else:
_pickle.dump(ret, output_pkl)
return ret
def gaugeopt_suite_to_dictionary(gaugeOptSuite, gs_target, advancedOptions=None, verbosity=0):
"""
Constructs a dictionary of gauge-optimization parameter dictionaries based
on "gauge optimization suite" name(s).
This is primarily a helper function for :func:`do_stdpractice_gst`, but can
be useful in its own right for constructing the would-be gauge optimization
dictionary used in :func:`do_stdpractice_gst` and modifying it slightly before
before passing it in (`do_stdpractice_gst` will accept a raw dictionary too).
Parameters
----------
gaugeOptSuite : str or dict, optional
Specifies which gauge optimizations to perform on each estimate. An
string (see below) specifies a built-in set of gauge optimizations,
otherwise `gaugeOptSuite` should be a dictionary of gauge-optimization
parameter dictionaries, as specified by the `gaugeOptParams` argument