/
gst.py
2943 lines (2429 loc) · 138 KB
/
gst.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
"""
GST Protocol objects
"""
#***************************************************************************************************
# 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 collections as _collections
import copy as _copy
import os as _os
import pickle as _pickle
import time as _time
import warnings as _warnings
import numpy as _np
from scipy.stats import chi2 as _chi2
from pygsti.baseobjs.profiler import DummyProfiler as _DummyProfiler
from pygsti.baseobjs.nicelyserializable import NicelySerializable as _NicelySerializable
from pygsti.protocols.estimate import Estimate as _Estimate
from pygsti.protocols import protocol as _proto
from pygsti.protocols.modeltest import ModelTest as _ModelTest
from pygsti import algorithms as _alg
from pygsti import circuits as _circuits
from pygsti import io as _io
from pygsti import models as _models
from pygsti import optimize as _opt
from pygsti import tools as _tools
from pygsti import baseobjs as _baseobjs
from pygsti.processors import QuditProcessorSpec as _QuditProcessorSpec
from pygsti.modelmembers import operations as _op
from pygsti.models import Model as _Model
from pygsti.models.gaugegroup import GaugeGroup as _GaugeGroup, GaugeGroupElement as _GaugeGroupElement
from pygsti.objectivefns import objectivefns as _objfns, wildcardbudget as _wild
from pygsti.circuits.circuitlist import CircuitList as _CircuitList
from pygsti.baseobjs.resourceallocation import ResourceAllocation as _ResourceAllocation
from pygsti.modelmembers import states as _states, povms as _povms
from pygsti.tools.legacytools import deprecate as _deprecated_fn
#For results object:
ROBUST_SUFFIX_LIST = [".robust", ".Robust", ".robust+", ".Robust+"]
DEFAULT_BAD_FIT_THRESHOLD = 2.0
class HasProcessorSpec(object):
"""
Adds to an experiment design a `processor_spec` attribute
Parameters
----------
processorspec_filename_or_obj : QuditProcessorSpec or str
The processor API used by this experiment design.
"""
def __init__(self, processorspec_filename_or_obj):
self.processor_spec = _load_pspec(processorspec_filename_or_obj) \
if (processorspec_filename_or_obj is not None) else None
self.auxfile_types['processor_spec'] = 'serialized-object'
@_deprecated_fn('This function stub will be removed soon.')
def create_target_model(self, gate_type='auto', prep_type='auto', povm_type='auto'):
"""
Deprecated function.
"""
raise NotImplementedError(("This function has been removed because is was an API hack. To properly create"
" a model from a processor spec, you should use one of the model creation functions"
" in pygsti.models.modelconstruction"))
class GateSetTomographyDesign(_proto.CircuitListsDesign, HasProcessorSpec):
"""
Minimal experiment design needed for GST
Parameters
----------
processorspec_filename_or_obj : QuditProcessorSpec or str
The processor API used by this experiment design.
circuit_lists : list or PlaquetteGridCircuitStructure
A list whose elements are themselves lists of :class:`Circuit`
objects, specifying the data that needs to be taken. Alternatively,
a single :class:`PlaquetteGridCircuitStructure` object containing
a sequence of circuits lists, each at a different "x" value (usually
the maximum circuit depth).
all_circuits_needing_data : list, optional
A list of all the circuits in `circuit_lists` typically with duplicates removed.
qubit_labels : tuple, optional
The qubits that this experiment design applies to. If None, the line labels
of the first circuit is used.
nested : bool, optional
Whether the elements of `circuit_lists` are nested, e.g. whether
`circuit_lists[i]` is a subset of `circuit_lists[i+1]`. This
is useful to know because certain operations can be more efficient
when it is known that the lists are nested.
remove_duplicates : bool, optional
Whether to remove duplicates when automatically creating
all the circuits that need data (this argument isn't used
when `all_circuits_needing_data` is given).
"""
def __init__(self, processorspec_filename_or_obj, circuit_lists, all_circuits_needing_data=None,
qubit_labels=None, nested=False, remove_duplicates=True):
super().__init__(circuit_lists, all_circuits_needing_data, qubit_labels, nested, remove_duplicates)
HasProcessorSpec.__init__(self, processorspec_filename_or_obj)
def map_qubit_labels(self, mapper):
"""
Creates a new experiment design whose circuits' qubit labels are updated according to a given mapping.
Parameters
----------
mapper : dict or function
A dictionary whose keys are the existing self.qubit_labels values
and whose value are the new labels, or a function which takes a
single (existing qubit-label) argument and returns a new qubit-label.
Returns
-------
GateSetTomographyDesign
"""
mapped_processorspec = self.processor_spec.map_qubit_labels(mapper)
mapped_circuits = [c.map_state_space_labels(mapper) for c in self.all_circuits_needing_data]
mapped_circuit_lists = [[c.map_state_space_labels(mapper) for c in circuit_list]
for circuit_list in self.circuit_lists]
mapped_qubit_labels = self._mapped_qubit_labels(mapper)
return GateSetTomographyDesign(mapped_processorspec, mapped_circuit_lists, mapped_circuits,
mapped_qubit_labels, self.nested, remove_duplicates=False)
class StandardGSTDesign(GateSetTomographyDesign):
"""
Standard GST experiment design consisting of germ-powers sandwiched between fiducials.
Parameters
----------
processorspec_filename_or_obj : QuditProcessorSpec or str
The processor API used by this experiment design.
prep_fiducial_list_or_filename : list or str
A list of preparation fiducial :class:`Circuit` objects or the path to a filename containing them.
meas_fiducial_list_or_filename : list or str
A list of measurement fiducial :class:`Circuit` objects or the path to a filename containing them.
germ_list_or_filename : list or str
A list of germ :class:`Circuit` objects or the path to a filename containing them.
max_lengths : list
List of integers, one per LSGST iteration, which set truncation lengths
for repeated germ strings. The list of circuits for the i-th LSGST
iteration includes the repeated germs truncated to the L-values *up to*
and including the i-th one.
germ_length_limits : dict, optional
A dictionary limiting the max-length values used for specific germs.
Keys are germ sequences and values are integers. For example, if
this argument is `{('Gx',): 4}` and `max_length_list = [1,2,4,8,16]`,
then the germ `('Gx',)` is only repeated using max-lengths of 1, 2,
and 4 (whereas other germs use all the values in `max_length_list`).
fiducial_pairs : list of 2-tuples or dict, optional
Specifies a subset of all fiducial string pairs (prepStr, effectStr)
to be used in the circuit lists. If a list, each element of
fid_pairs is a (iPrepStr, iEffectStr) 2-tuple of integers, each
indexing a string within prep_strs and effect_strs, respectively, so
that prepStr = prep_strs[iPrepStr] and effectStr =
effect_strs[iEffectStr]. If a dictionary, keys are germs (elements
of germ_list) and values are lists of 2-tuples specifying the pairs
to use for that germ.
keep_fraction : float, optional
The fraction of fiducial pairs selected for each germ-power base
string. The default includes all fiducial pairs. Note that
for each germ-power the selected pairs are *different* random
sets of all possible pairs (unlike fid_pairs, which specifies the
*same* fiducial pairs for *all* same-germ base strings). If
fid_pairs is used in conjuction with keep_fraction, the pairs
specified by fid_pairs are always selected, and any additional
pairs are randomly selected.
keep_seed : int, optional
The seed used for random fiducial pair selection (only relevant
when keep_fraction < 1).
include_lgst : boolean, optional
If true, then the starting list (only applicable when
`nest == True`) is the list of LGST strings rather than the
empty list. This means that when `nest == True`, the LGST
sequences will be included in all the lists.
nest : boolean, optional
If True, the GST circuit lists are "nested", meaning
that each successive list of circuits contains all the gate
strings found in previous lists (and usually some additional
new ones). If False, then the returned circuit list for maximum
length == L contains *only* those circuits specified in the
description above, and *not* those for previous values of L.
circuit_rules : list, optional
A list of `(find,replace)` 2-tuples which specify circuit-label replacement
rules. Both `find` and `replace` are tuples of operation labels (or `Circuit` objects).
op_label_aliases : dictionary, optional
Dictionary whose keys are operation label "aliases" and whose values are tuples
corresponding to what that operation label should be expanded into before querying
the dataset. This information is stored within the returned circuit
structures. Defaults to the empty dictionary (no aliases defined)
e.g. op_label_aliases['Gx^3'] = ('Gx','Gx','Gx')
dscheck : DataSet, optional
A data set which filters the circuits used for GST. When a standard-GST
circuit is missing from this `DataSet`, action is taken according to
`action_if_missing`.
action_if_missing : {"raise","drop"}, optional
The action to take when a desired circuit is missing from
`dscheck` (only relevant when `dscheck` is not None). "raise" causes
a ValueError to be raised; "drop" causes the missing sequences to be
dropped from the returned set.
qubit_labels : tuple, optional
The qubits that this experiment design applies to. If None, the line labels
of the first circuit is used.
verbosity : int, optional
The level of output to print to stdout.
add_default_protocol : bool, optional
Whether a default :class:`StandardGST` protocol should be added to this
experiment design. Setting this to True makes it easy to analyze the data
(after it's gathered) corresponding to this design via a :class:`DefaultRunner`.
"""
def __init__(self, processorspec_filename_or_obj, prep_fiducial_list_or_filename, meas_fiducial_list_or_filename,
germ_list_or_filename, max_lengths, germ_length_limits=None, fiducial_pairs=None, keep_fraction=1,
keep_seed=None, include_lgst=True, nest=True, circuit_rules=None, op_label_aliases=None,
dscheck=None, action_if_missing="raise", qubit_labels=None, verbosity=0,
add_default_protocol=False):
#Get/load fiducials and germs
prep, meas, germs = _load_fiducials_and_germs(
prep_fiducial_list_or_filename,
meas_fiducial_list_or_filename,
germ_list_or_filename)
self.prep_fiducials = prep
self.meas_fiducials = meas
self.germs = germs
self.maxlengths = max_lengths
self.germ_length_limits = germ_length_limits
self.include_lgst = include_lgst
self.aliases = op_label_aliases
self.circuit_rules = circuit_rules
#Hardcoded for now... - include so gets written when serialized
self.truncation_method = "whole germ powers"
self.nested = nest
#FPR support
self.fiducial_pairs = fiducial_pairs
self.fpr_keep_fraction = keep_fraction
self.fpr_keep_seed = keep_seed
#TODO: add a line_labels arg to create_lsgst_circuit_lists and pass qubit_labels in?
processor_spec_or_model = _load_pspec_or_model(processorspec_filename_or_obj)
lists = _circuits.create_lsgst_circuit_lists(
processor_spec_or_model, self.prep_fiducials, self.meas_fiducials, self.germs,
self.maxlengths, self.fiducial_pairs, self.truncation_method, self.nested,
self.fpr_keep_fraction, self.fpr_keep_seed, self.include_lgst,
self.aliases, self.circuit_rules, dscheck, action_if_missing,
self.germ_length_limits, verbosity)
#FUTURE: add support for "advanced options" (probably not in __init__ though?):
# trunc_scheme=advancedOptions.get('truncScheme', "whole germ powers")
try:
processor_spec = processor_spec_or_model.create_processor_spec() \
if isinstance(processor_spec_or_model, _Model) else processor_spec_or_model
except Exception:
_warnings.warn("Given model failed to create a processor spec for StdGST experiment design!")
processor_spec = None # allow this to bail out
super().__init__(processor_spec, lists, None, qubit_labels, self.nested)
self.auxfile_types['prep_fiducials'] = 'text-circuit-list'
self.auxfile_types['meas_fiducials'] = 'text-circuit-list'
self.auxfile_types['germs'] = 'text-circuit-list'
self.auxfile_types['germ_length_limits'] = 'circuit-str-json'
self.auxfile_types['fiducial_pairs'] = 'circuit-str-json'
if add_default_protocol:
self.add_default_protocol(StandardGST(name='StdGST'))
def copy_with_maxlengths(self, max_lengths, germ_length_limits=None,
dscheck=None, action_if_missing='raise', verbosity=0):
"""
Copies this GST experiment design to one with the same data except a different set of maximum lengths.
Parameters
----------
max_lengths_to_keep : list
A list of the maximum lengths that should be present in the
returned experiment design.
germ_length_limits : dict, optional
A dictionary limiting the max-length values to keep for specific germs.
Keys are germ sequences and values are integers. If `None`, then the
current length limits are used.
dscheck : DataSet, optional
A data set which filters the circuits used for GST. When a standard-GST
circuit is missing from this `DataSet`, action is taken according to
`action_if_missing`.
action_if_missing : {"raise","drop"}, optional
The action to take when a desired circuit is missing from
`dscheck` (only relevant when `dscheck` is not None). "raise" causes
a ValueError to be raised; "drop" causes the missing sequences to be
dropped from the returned set.
Returns
-------
StandardGSTDesign
"""
if germ_length_limits is None:
gll = self.germ_length_limits
else:
gll = self.germ_length_limits.copy() if (self.germ_length_limits is not None) else {}
gll.update(germ_length_limits)
ret = StandardGSTDesign(self.processor_spec, self.prep_fiducials, self.meas_fiducials,
self.germs, max_lengths, gll, self.fiducial_pairs,
self.fpr_keep_fraction, self.fpr_keep_seed, self.include_lgst, self.nested,
self.circuit_rules, self.aliases, dscheck, action_if_missing, self.qubit_labels,
verbosity, add_default_protocol=False)
#filter the circuit lists in `ret` using those in `self` (in case self includes only a subset of
# the circuits dictated by the germs, fiducials, and fidpairs).
ret = ret.truncate_to_design(self)
ret.nested = self.nested # must set nested flag again because truncate_to_design resets to False to be safe
return ret
def map_qubit_labels(self, mapper):
"""
Creates a new experiment design whose circuits' qubit labels are updated according to a given mapping.
Parameters
----------
mapper : dict or function
A dictionary whose keys are the existing self.qubit_labels values
and whose value are the new labels, or a function which takes a
single (existing qubit-label) argument and returns a new qubit-label.
Returns
-------
StandardGSTDesign
"""
pspec = self.processor_spec.map_qudit_labels(mapper)
prep_fiducials = [c.map_state_space_labels(mapper) for c in self.prep_fiducials]
meas_fiducials = [c.map_state_space_labels(mapper) for c in self.meas_fiducials]
germs = [c.map_state_space_labels(mapper) for c in self.germs]
qubit_labels = self._mapped_qubit_labels(mapper)
if isinstance(self.fiducial_pairs, dict):
fiducial_pairs = {c.map_state_space_labels(mapper): v for c, v in self.fiducial_pairs.items()}
else:
fiducial_pairs = self.fiducial_pairs
if not (self.circuit_rules is None and self.aliases is None):
raise NotImplementedError(("Mapping qubit labels for a StandardGSTDesign with circuit rules"
" and/or aliases is not implemented yet."))
dscheck = None; action_if_missing = 'raise'; verbosity = 0 # values we could add as arguments later if desired.
return StandardGSTDesign(pspec, prep_fiducials, meas_fiducials,
germs, self.maxlengths, self.germ_length_limits, fiducial_pairs,
self.fpr_keep_fraction, self.fpr_keep_seed, self.include_lgst, self.nested,
self.circuit_rules, self.aliases, dscheck, action_if_missing, qubit_labels,
verbosity, add_default_protocol=False)
class GSTInitialModel(_NicelySerializable):
"""
Specification of a starting point for GST.
Parameters
----------
model : Model, optional
The model to start at, given explicitly.
starting_point : {"target", "User-supplied-Model", "LGST", "LGST-if-possible"}, optional
The starting point type. If `None`, then defaults to `"User-supplied-Model"` if
`model` is given, otherwise to `"target"`.
depolarize_start : float, optional
Amount to depolarize the starting model just prior to running GST.
randomize_start : float, optional
Amount to randomly kick the starting model just prior to running GST.
lgst_gaugeopt_tol : float, optional
Gauge-optimization tolerance for the post-LGST gauge optimization that is
performed when `starting_point == "LGST"` or possibly when `"starting_point == "LGST-if-possible"`.
contract_start_to_cptp : bool, optional
Whether the Model should be forced ("contracted") to being CPTP just prior to running GST.
"""
@classmethod
def cast(cls, obj):
"""
Cast `obj` to a :class:`GSTInitialModel` object.
Parameters
----------
obj : object
object to cast. Can be a `GSTInitialModel` (naturally) or a :class:`Model`.
Returns
-------
GSTInitialModel
"""
return obj if isinstance(obj, GSTInitialModel) else cls(obj)
def __init__(self, model=None, target_model=None, starting_point=None, depolarize_start=0, randomize_start=0,
lgst_gaugeopt_tol=1e-6, contract_start_to_cptp=False):
# Note: starting_point can be an initial model or string
super().__init__()
self.model = model
self.target_model = target_model
if starting_point is None:
self.starting_point = "target" if (model is None) else "User-supplied-Model"
else:
self.starting_point = starting_point
self.lgst_gaugeopt_tol = lgst_gaugeopt_tol
self.contract_start_to_cptp = contract_start_to_cptp
self.depolarize_start = depolarize_start
self.randomize_start = randomize_start
def retrieve_model(self, edesign, gaugeopt_target, dataset, comm):
"""
Retrieve the starting-point :class:`Model` used to seed a long-sequence GST run.
Parameters
----------
edesign : ExperimentDesign
The experiment design containing the circuits being used, the qubit labels,
and (possibly) a target model (for use when `starting_point == "target"`) and
fiducial circuits (for LGST).
gaugeopt_target : Model
The gauge-optimization target, i.e. distance to this model is the objective function
within the post-LGST gauge-optimization step.
dataset : DataSet
Data used to execute LGST when needed.
comm : mpi4py.MPI.Comm
A MPI communicator to divide workload amoung multiple processors.
Returns
-------
Model
"""
#Get starting point (model), which is used to compute other quantities
# Note: should compute on rank 0 and distribute?
starting_pt = self.starting_point
if starting_pt == "User-supplied-Model":
mdl_start = self.model.copy()
elif starting_pt in ("LGST", "LGST-if-possible"):
#lgst_advanced = advancedOptions.copy(); lgst_advanced.update({'estimateLabel': "LGST", 'onBadFit': []})
if self.model is not None:
mdl_start = self.model.copy()
elif self.target_model is not None:
mdl_start = self.target_model.copy()
else:
mdl_start = None
if mdl_start is None:
raise ValueError(("LGST requires a model. Specify an initial model or use an experiment"
" design with a processor specification"))
lgst = LGST(mdl_start,
gaugeopt_suite=GSTGaugeOptSuite(
gaugeopt_argument_dicts={'lgst_gaugeopt': {'tol': self.lgst_gaugeopt_tol}},
gaugeopt_target=gaugeopt_target),
badfit_options=None, name="LGST")
try: # see if LGST can be run on this data
if isinstance(edesign, StandardGSTDesign) and len(edesign.maxlengths) > 0:
lgst_design = edesign.copy_with_maxlengths([edesign.maxlengths[0]], dscheck=dataset,
action_if_missing='drop')
else:
lgst_design = edesign # just use the whole edesign
lgst_data = _proto.ProtocolData(lgst_design, dataset)
lgst.check_if_runnable(lgst_data)
starting_pt = "LGST"
except ValueError as e:
if starting_pt == "LGST": raise e # error if we *can't* run LGST
#Fall back to target or custom model
if self.model is not None:
starting_pt = "User-supplied-Model"
mdl_start = self.model.copy()
else:
starting_pt = "target"
# mdl_start = mdl_start (either the target model or constructed from edesign pspec)
if starting_pt == "LGST":
lgst_results = lgst.run(lgst_data)
mdl_start = lgst_results.estimates['LGST'].models['lgst_gaugeopt']
elif starting_pt == "target":
if self.target_model is not None:
mdl_start = self.target_model.copy()
else:
raise ValueError("Starting point == 'target' and target model not specified!")
else:
raise ValueError("Invalid starting point: %s" % starting_pt)
if mdl_start is None:
raise ValueError("Could not create or obtain an initial model!")
#Post-processing mdl_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 model
if self.contract_start_to_cptp:
mdl_start = _alg.contract(mdl_start, "CPTP")
raise ValueError(
"'contractStartToCPTP' has been removed b/c it can change the parameterization of a model")
if self.depolarize_start > 0:
mdl_start = mdl_start.depolarize(op_noise=self.depolarize_start)
if self.randomize_start > 0:
v = mdl_start.to_vector()
vrand = 2 * (_np.random.random(len(v)) - 0.5) * self.randomize_start
mdl_start.from_vector(v + vrand)
if comm is not None: # broadcast starting model
#OLD: comm.bcast(mdl_start, root=0)
# just broadcast *vector* to avoid huge pickles (if cached calcs!)
comm.bcast(mdl_start.to_vector(), root=0)
else:
#OLD: mdl_start = comm.bcast(None, root=0)
v = comm.bcast(None, root=0)
mdl_start.from_vector(v)
return mdl_start
def _to_nice_serialization(self):
state = super()._to_nice_serialization()
state.update({'starting_point': self.starting_point, # can be initial model? if so need to memoize...
'depolarize_start': self.depolarize_start,
'randomize_start': self.randomize_start,
'contract_start_to_cptp': self.contract_start_to_cptp,
'lgst_gaugeopt_tol': self.lgst_gaugeopt_tol,
'model': self.model.to_nice_serialization() if (self.model is not None) else None,
'target_model': (self.target_model.to_nice_serialization()
if (self.target_model is not None) else None),
})
return state
@classmethod
def _from_nice_serialization(cls, state): # memo holds already de-serialized objects
model = _Model.from_nice_serialization(state['model']) \
if (state['model'] is not None) else None
target_model = _Model.from_nice_serialization(state['target_model']) \
if (state['target_model'] is not None) else None
return cls(model, target_model, state['starting_point'], state['depolarize_start'],
state['randomize_start'], state['lgst_gaugeopt_tol'], state['contract_start_to_cptp'])
class GSTBadFitOptions(_NicelySerializable):
"""
Options for post-processing a GST fit that was unsatisfactory.
Parameters
----------
threshold : float, optional
A threshold, given in number-of-standard-deviations, below which a
GST fit is considered satisfactory (and no "bad-fit" processing is needed).
actions : tuple, optional
Actions to take when a GST fit is unsatisfactory. Allowed actions include:
* 'wildcard': Find an admissable wildcard model.
* 'ddist_wildcard': Fits a single parameter wildcard model in which
the amount of wildcard error added to an operation is proportional
to the diamond distance between that operation and the target.
* 'robust': scale data according out "robust statistics v1" algorithm,
where we drastically scale down (reduce) the data due to especially
poorly fitting circuits. Namely, if a circuit's log-likelihood ratio
exceeds the 95% confidence region about its expected value (the # of
degrees of freedom in the circuits outcomes), then the data is scaled
by the `expected_value / actual_value`, so that the new value exactly
matches what would be expected. Ideally there are only a few of these
"outlier" circuits, which correspond errors in the measurement apparatus.
* 'Robust': same as 'robust', but re-optimize the final objective function
(usually the log-likelihood) after performing the scaling to get the
final estimate.
* 'robust+': scale data according out "robust statistics v2" algorithm,
which performs the v1 algorithm (see 'robust' above) and then further
rescales all the circuit data to achieve the desired chi2 distribution
of per-circuit goodness-of-fit values *without reordering* these values.
* 'Robust+': same as 'robust+', but re-optimize the final objective function
(usually the log-likelihood) after performing the scaling to get the
final estimate.
* 'do nothing': do not perform any additional actions. Used to help avoid
the need for special cases when working with multiple types of bad-fit actions.
wildcard_budget_includes_spam : bool, optional
Include a SPAM budget within the wildcard budget used to process
the `"wildcard"` action.
wildcard_L1_weights : np.array, optional
An array of weights affecting the L1 penalty term used to select a feasible
wildcard error vector `w_i` that minimizes `sum_i weight_i* |w_i|` (a weighted
L1 norm). Elements of this array must correspond to those of the wildcard budget
being optimized, typically the primitive operations of the estimated model - but
to get the order right you should specify `wildcard_primitive_op_labels` to be sure.
If `None`, then all weights are assumed to be 1.
wildcard_primitive_op_labels: list, optional
The primitive operation labels used to construct the :class:`PrimitiveOpsWildcardBudget`
that is optimized. If `None`, equal to `model.primitive_op_labels + model.primitive_instrument_labels`
where `model` is the estimated model, with `'SPAM'` at the end if `wildcard_budget_includes_spam`
is True. When specified, should contain a subset of the default values.
wildcard_methods: tuple, optional
A list of the methods to use to optimize the wildcard error vector. Default is `("neldermead",)`.
Options include `"neldermead"`, `"barrier"`, `"cvxopt"`, `"cvxopt_smoothed"`, `"cvxopt_small"`,
and `"cvxpy_noagg"`. So many methods exist because different convex solvers behave differently
(unfortunately). Leave as the default as a safe option, but `"barrier"` is pretty reliable and much
faster than `"neldermead"`, and is a good option so long as it runs.
wildcard_inadmissable_action: {"print", "raise"}, optional
What to do when an inadmissable wildcard error vector is found. The default just prints this
information and continues, while `"raise"` raises a `ValueError`. Often you just want this information
printed so that when the wildcard analysis fails in this way it doesn't cause the rest of an analysis
to abort.
"""
@classmethod
def cast(cls, obj):
"""
Cast `obj` to a :class:`GSTBadFitOptions` object.
Parameters
----------
obj : object
Object to cast. Can be a `GSTBadFitOptions` (naturally) or a dictionary
of constructor arguments.
Returns
-------
GSTBadFitOptions
"""
if isinstance(obj, GSTBadFitOptions):
return obj
else: # assum obj is a dict of arguments
return cls(**obj) if obj else cls() # allow obj to be None => defaults
def __init__(self, threshold=DEFAULT_BAD_FIT_THRESHOLD, actions=(),
wildcard_budget_includes_spam=True,
wildcard_L1_weights=None, wildcard_primitive_op_labels=None,
wildcard_initial_budget=None, wildcard_methods=('neldermead',),
wildcard_inadmissable_action='print', wildcard1d_reference='diamond distance'):
super().__init__()
valid_actions = ('wildcard', 'wildcard1d', 'Robust+', 'Robust', 'robust+', 'robust', 'do nothing')
if not all([(action in valid_actions) for action in actions]):
raise ValueError("Invalid action in %s! Allowed actions are %s" % (str(actions), str(valid_actions)))
self.threshold = float(threshold)
self.actions = tuple(actions) # e.g. ("wildcard", "Robust+"); empty list => 'do nothing'
self.wildcard_budget_includes_spam = bool(wildcard_budget_includes_spam)
self.wildcard_L1_weights = wildcard_L1_weights
self.wildcard_primitive_op_labels = wildcard_primitive_op_labels
self.wildcard_initial_budget = wildcard_initial_budget
self.wildcard_methods = wildcard_methods
self.wildcard_inadmissable_action = wildcard_inadmissable_action # can be 'raise' or 'print'
self.wildcard1d_reference = wildcard1d_reference
def _to_nice_serialization(self):
state = super()._to_nice_serialization()
state.update({'threshold': self.threshold,
'actions': self.actions,
'wildcard': {'budget_includes_spam': self.wildcard_budget_includes_spam,
'L1_weights': self.wildcard_L1_weights, # an array?
'primitive_op_labels': self.wildcard_primitive_op_labels,
'initial_budget': self.wildcard_initial_budget, # serializable?
'methods': self.wildcard_methods,
'indadmissable_action': self.wildcard_inadmissable_action,
'1d_reference': self.wildcard1d_reference},
})
return state
@classmethod
def _from_nice_serialization(cls, state): # memo holds already de-serialized objects
wildcard = state.get('wildcard', {})
return cls(state['threshold'], tuple(state['actions']),
wildcard.get('budget_includes_spam', True),
wildcard.get('L1_weights', None),
wildcard.get('primitive_op_labels', None),
wildcard.get('initial_budget', None),
tuple(wildcard.get('methods', ['neldermead'])),
wildcard.get('inadmissable_action', 'print'),
wildcard.get('1d_reference', 'diamond distance'))
class GSTObjFnBuilders(_NicelySerializable):
"""
Holds the objective-function builders needed for long-sequence GST.
Parameters
----------
iteration_builders : list or tuple
A list of :class:`ObjectiveFunctionBuilder` objects used (sequentially)
on each GST iteration.
final_builders : list or tuple, optional
A list of :class:`ObjectiveFunctionBuilder` objects used (sequentially)
on the final GST iteration.
"""
@classmethod
def cast(cls, obj):
"""
Cast `obj` to a :class:`GSTObjFnBuilders` object.
Parameters
----------
obj : object
Object to cast. Can be a `GSTObjFnBuilders` (naturally), a
dictionary of :meth:`create_from` arguments (or None), or a
list or tuple of the `(iteration_builders, final_builders)` constructor arguments.
Returns
-------
GSTObjFnBuilders
"""
if isinstance(obj, cls): return obj
elif obj is None: return cls.create_from()
elif isinstance(obj, dict): return cls.create_from(**obj)
elif isinstance(obj, (list, tuple)): return cls(*obj)
else: raise ValueError("Cannot create an %s object from '%s'" % (cls.__name__, str(type(obj))))
@classmethod
def create_from(cls, objective='logl', freq_weighted_chi2=False, always_perform_mle=False, only_perform_mle=False):
"""
Creates a common :class:`GSTObjFnBuilders` object from several arguments.
Parameters
----------
objective : {'logl', 'chi2'}, optional
Whether to create builders for maximum-likelihood or minimum-chi-squared GST.
freq_weighted_chi2 : bool, optional
Whether chi-squared objectives use frequency-weighting. If you're not sure
what this is, leave it as `False`.
always_perform_mle : bool, optional
Perform a ML-GST step on *each* iteration (usually this is only done for the
final iteration).
only_perform_mle : bool, optional
Only perform a ML-GST step on each iteration, i.e. do *not* perform any chi2
minimization to "seed" the ML-GST step.
Returns
-------
GSTObjFnBuilders
"""
chi2_builder = _objfns.ObjectiveFunctionBuilder.create_from('chi2', freq_weighted_chi2)
mle_builder = _objfns.ObjectiveFunctionBuilder.create_from('logl')
if objective == "chi2":
iteration_builders = [chi2_builder]
final_builders = []
elif objective == "logl":
if always_perform_mle:
iteration_builders = [mle_builder] if only_perform_mle else [chi2_builder, mle_builder]
final_builders = []
else:
iteration_builders = [chi2_builder]
final_builders = [mle_builder]
else:
raise ValueError("Invalid objective: %s" % objective)
return cls(iteration_builders, final_builders)
def __init__(self, iteration_builders, final_builders=()):
super().__init__()
self.iteration_builders = iteration_builders
self.final_builders = final_builders
def _to_nice_serialization(self):
state = super()._to_nice_serialization()
state.update({
'iteration_builders': [b.to_nice_serialization() for b in self.iteration_builders],
'final_builders': [b.to_nice_serialization() for b in self.final_builders]
})
return state
@classmethod
def _from_nice_serialization(cls, state):
iteration_builders = [_objfns.ObjectiveFunctionBuilder.from_nice_serialization(b)
for b in state['iteration_builders']]
final_builders = [_objfns.ObjectiveFunctionBuilder.from_nice_serialization(b)
for b in state['final_builders']]
return cls(iteration_builders, final_builders)
class GSTGaugeOptSuite(_NicelySerializable):
"""
Holds directives to perform one or more gauge optimizations on a model.
Usually this gauge optimization is done after fitting a parameterized
model to data (e.g. after GST), as the data cannot (by definition)
prefer any particular gauge choice.
Parameters
----------
gaugeopt_suite_names : str or list of strs, optional
Names one or more gauge optimization suites to perform. A string or
list of strings (see below) specifies built-in sets of gauge optimizations.
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.
gaugeopt_argument_dicts : dict, optional
A dictionary whose string-valued keys label different gauge optimizations (e.g. within a
resulting `Estimate` object). Each corresponding value can be either a dictionary
of arguments to :func:`gaugeopt_to_target` or a list of such dictionaries which then
describe the different stages of a multi-stage gauge optimization.
gaugeopt_target : Model, optional
If not None, a model 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 the target model, which are used as the default when
`gaugeopt_target` is None.
"""
@classmethod
def cast(cls, obj):
if obj is None:
return cls() # None -> gaugeopt suite with default args (empty suite)
elif isinstance(obj, GSTGaugeOptSuite):
return obj
elif isinstance(obj, (str, tuple, list)):
return cls(gaugeopt_suite_names=obj)
elif isinstance(obj, dict):
return cls(gaugeopt_argument_dicts=obj)
else:
raise ValueError("Could not convert %s object to a gauge optimization suite!" % str(type(obj)))
def __init__(self, gaugeopt_suite_names=None, gaugeopt_argument_dicts=None, gaugeopt_target=None):
super().__init__()
if gaugeopt_suite_names is not None:
self.gaugeopt_suite_names = (gaugeopt_suite_names,) \
if isinstance(gaugeopt_suite_names, str) else tuple(gaugeopt_suite_names)
else:
self.gaugeopt_suite_names = None
if gaugeopt_argument_dicts is not None:
self.gaugeopt_argument_dicts = gaugeopt_argument_dicts.copy()
else:
self.gaugeopt_argument_dicts = None
self.gaugeopt_target = gaugeopt_target
def is_empty(self):
"""
Whether this suite is completely empty, i.e., contains NO gauge optimization instructions.
This is a useful check before constructing quantities needed by gauge optimization,
e.g. a target model, which can just be skipped when no gauge optimization will be performed.
Returns
-------
bool
"""
return (self.gaugeopt_suite_names is None) and (self.gaugeopt_argument_dicts is None)
def to_dictionary(self, model, unreliable_ops=(), verbosity=0):
"""
Converts this gauge optimization suite into a raw dictionary of dictionaries.
Constructs a dictionary of gauge-optimization parameter dictionaries based
on "gauge optimization suite" name(s).
This essentially renders the gauge-optimization directives within this object
in an "expanded" form for either running gauge optimization (e.g. within
a :meth:`GateSetTomography.run` call) or for constructing the would-be gauge
optimization call arguments so they can be slightly modeified before passing
them in as the actual gauge-optimization suite used in an analysis (the
resulting dictionary can be used to initialize a new `GSTGaugeOptSuite` object
via the `gaugeopt_argument_dicts` argument.
Parameters
----------
model : Model
A model which specifies the dimension (i.e. parameterization) of the
gauge-optimization and the basis. Typically the model that is optimized
or the ideal model using the same parameterization and having the correct
default-gauge-group as the model that is optimized.
unreliable_ops : tuple, optional
A tuple of gate (or circuit-layer) labels that count as "unreliable operations".
Typically these are the multi-qubit (2-qubit) gates.
verbosity : int
The verbosity to attach to the various gauge optimization parameter
dictionaries.
Returns
-------
dict
A dictionary whose keys are the labels of the different gauge
optimizations to perform and whose values are the corresponding
dictionaries of arguments to :func:`gaugeopt_to_target` (or lists
of such dictionaries for a multi-stage gauge optimization).
"""
printer = _baseobjs.VerbosityPrinter.create_printer(verbosity)
#Build ordered dict of gauge optimization parameters
gaugeopt_suite_dict = _collections.OrderedDict()
if self.gaugeopt_suite_names is not None:
for gaugeopt_suite_name in self.gaugeopt_suite_names:
self._update_gaugeopt_dict_from_suitename(gaugeopt_suite_dict, gaugeopt_suite_name,
gaugeopt_suite_name, model, unreliable_ops, printer)
if self.gaugeopt_argument_dicts is not None:
for lbl, goparams in self.gaugeopt_argument_dicts.items():
if hasattr(goparams, 'keys'): # goparams is a simple dict
gaugeopt_suite_dict[lbl] = goparams.copy()
gaugeopt_suite_dict[lbl].update({'verbosity': printer})
else: # assume goparams is an iterable
assert(isinstance(goparams, (list, tuple))), \
"If not a dictionary, gauge opt params should be a list or tuple of dicts!"
gaugeopt_suite_dict[lbl] = []
for goparams_stage in goparams:
dct = goparams_stage.copy()
dct.update({'verbosity': printer})
gaugeopt_suite_dict[lbl].append(dct)
if self.gaugeopt_target is not None:
assert(isinstance(self.gaugeopt_target, _Model)), "`gaugeopt_target` must be None or a Model"
for goparams in gaugeopt_suite_dict.values():
goparams_list = [goparams] if hasattr(goparams, 'keys') else goparams
for goparams_dict in goparams_list:
if 'target_model' in goparams_dict:
_warnings.warn(("`gaugeOptTarget` argument is overriding"
" user-defined target_model in gauge opt"
" param dict(s)"))
goparams_dict.update({'target_model': self.gaugeopt_target})
return gaugeopt_suite_dict
def _update_gaugeopt_dict_from_suitename(self, gaugeopt_suite_dict, root_lbl, suite_name, model,
unreliable_ops, printer):
if suite_name in ("stdgaugeopt", "stdgaugeopt-unreliable2Q", "stdgaugeopt-tt", "stdgaugeopt-safe",
"stdgaugeopt-noconversion", "stdgaugeopt-noconversion-safe"):
stages = [] # multi-stage gauge opt
gg = model.default_gauge_group
convert_to = {'to_type': "full TP", 'flatten_structure': True, 'set_default_gauge_group': True} \
if ('noconversion' not in suite_name and gg.name not in ("Full", "TP")) else None
if isinstance(gg, _models.gaugegroup.TrivialGaugeGroup) and convert_to is None:
if suite_name == "stdgaugeopt-unreliable2Q" and model.dim == 16:
if any([gl in model.operations.keys() for gl in unreliable_ops]):
gaugeopt_suite_dict[root_lbl] = {'verbosity': printer}
else:
#just do a single-stage "trivial" gauge opts using default group
gaugeopt_suite_dict[root_lbl] = {'verbosity': printer}
elif gg is not None:
metric = 'frobeniustt' if suite_name == 'stdgaugeopt-tt' else 'frobenius'
#Stage 1: plain vanilla gauge opt to get into "right ballpark"
if gg.name in ("Full", "TP"):
stages.append(
{
'gates_metric': metric, 'spam_metric': metric,
'item_weights': {'gates': 1.0, 'spam': 1.0},
'verbosity': printer
})