/
results.py
2281 lines (1826 loc) · 109 KB
/
results.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
""" Defines the Results class and supporting functionality."""
import sys as _sys
import os as _os
import re as _re
import collections as _collections
import matplotlib as _matplotlib
import AnalysisTools as _AT
import ReportGeneration as _RG
import LatexUtil as _LU
import gatestring as _gatestring
from Core import getRhoAndESpecs as _getRhoAndESpecs
from Core import getRhoAndEStrs as _getRhoAndEStrs
from Core import optimizeGauge as _optimizeGauge
class Results(object):
"""
Encapsulates a set of GST results.
A Results object is constructed from the input parameters and raw output
gatesets from a GST calculation, typically performed by one of the
"do<something>" methods of GST.Core, and acts as a end-output factory
(creating reports, presentations, etc), and a derived-results cache
(so derived quantities don't need to be recomputed many times for
different output formats).
"""
def __init__(self, restrictToFormats=None, templatePath=None, latexCmd="pdflatex"):
"""
Initialize a Results object.
Parameters
----------
restrictToFormats : tuple or None
A tuple of format names to restrict internal computation
to. This parameter should be left as None unless you
know what you're doing.
templatePath : string or None
A local path to the stored GST report template files. The
default value of None means to use the default path, which
is almost always what you want.
"""
self.confidenceRegions = {} # key == confidence level, val = ConfidenceRegion
self.tables = {} #dict of dicts. Outer dict key is confidence level
self.figures = {} #plain dict. Key is figure name (a figure applies to all confidence levels)
self.specials = {} #plain dict. Key is name of "special" object
if restrictToFormats is not None:
self.formatsToCompute = restrictToFormats
else:
self.formatsToCompute = ('py','html','latex','ppt') #all formats
self.longTables = False
self.tableClass = "dataTable"
self.templatePath = None
self.latexCmd = latexCmd
self.bEssentialResultsSet = False
self.LsAndGermInfoSet = False
self.setAdditionalInfo() #set all default values of additional info
def init_single(self, objective, targetGateset, dataset, gatesetEstimate,
gateStringList, constrainToTP, gatesetEstimate_noGaugeOpt=None):
"""
Initialize this Results object from the inputs and outputs of a
single (non-iterative) GST method.
Parameters
----------
objective : {'chi2', 'logL'}
Whether gateset was obtained by minimizing chi^2 or
maximizing the log-likelihood.
targetGateset : GateSet
The target gateset used when optimizing the objective.
dataset : DataSet
The dataset used when optimizing the objective.
gatesetEstimate : GateSet
The (single) gate set obtained which optimizes the objective.
gateStringList : list of GateStrings
The list of gate strings used to optimize the objective.
constrainToTP : boolean
Whether or not the gatesetEstimate was constrained to lie
within TP during the objective optimization.
gatesetEstimate_noGaugeOpt : GateSet, optional
The value of the estimated gate set *before* any gauge
optimization was performed on it.
Returns
-------
None
"""
# Set essential info: gateset estimates(s) but no particular
# structure known about gateStringLists.
self.gsTarget = targetGateset
self.gatesets = [ gatesetEstimate ]
self.gsBestEstimate = gatesetEstimate
self.gateStringLists = [ gateStringList ]
self.bestGateStringList = gateStringList
self.dataset = dataset
self.objective = objective
self.constrainToTP = constrainToTP
if gatesetEstimate_noGaugeOpt is not None:
self.gatesetEstimates_noGO = [ gatesetEstimate_noGaugeOpt ]
else:
self.gatesetEstimates_noGO = None
self.gsSeed = None
self.bEssentialResultsSet = True
def init_LsAndGerms(self, objective, targetGateset, dataset,
seedGateset, Ls, germs, gatesetsByL, gateStringListByL,
rhoStrs, EStrs, truncFn, constrainToTP, rhoEPairs=None,
gatesetsByL_noGaugeOpt=None):
"""
Initialize this Results object from the inputs and outputs of
an iterative GST method based on gate string lists containing
germs repeated up to a maximum-L value that increases with
iteration.
Parameters
----------
objective : {'chi2', 'logL'}
Whether gateset was obtained by minimizing chi^2 or
maximizing the log-likelihood.
targetGateset : GateSet
The target gateset used when optimizing the objective.
dataset : DataSet
The dataset used when optimizing the objective.
seedGateset : GateSet
The initial gateset used to seed the iterative part
of the objective optimization. Typically this is
obtained via LGST.
Ls : list of ints
List of maximum-L values used in the iterations.
germs : list of GateStrings
List of germ gate strings used in the objective optimization.
gatesetsByL : list of GateSets
The estimated gateset at each L value.
gateStringListByL : list of lists of GateStrings
The gate string list used at each L value.
rhoStrs : list of GateStrings
The list of state preparation fiducial strings
in the objective optimization.
EStrs : list of GateStrings
The list of measurement fiducial strings
in the objective optimization.
truncFn : function
The truncation function used, indicating how a
germ should be repeated "L times". Function should
take parameters (germ, L) and return the repeated
gate string. For example, see
GST.GateStringTools.repeatWithMaxLength.
constrainToTP : boolean
Whether or not the gatesetEstimate was constrained to lie
within TP during the objective optimization.
rhoEPairs : list of 2-tuples, optional
Specifies a subset of all rhoStr,EStr string pairs to be used in this
analysis. Each element of rhoEPairs is a (iRhoStr, iEStr) 2-tuple of integers,
which index a string within the state preparation and measurement fiducial
strings respectively.
gatesetsByL_noGaugeOpt : list of GateSets, optional
The value of the estimated gate sets *before* any gauge
optimization was performed on it.
Returns
-------
None
"""
assert(len(gateStringListByL) == len(gatesetsByL) == len(Ls))
# Set essential info: gateset estimates(s) but no particular
# structure known about gateStringLists.
self.gsTarget = targetGateset
self.gsSeed = seedGateset
self.gatesets = gatesetsByL
self.gsBestEstimate = gatesetsByL[-1]
self.gateStringLists = gateStringListByL
self.bestGateStringList = gateStringListByL[-1]
self.dataset = dataset
self.objective = objective
self.constrainToTP = constrainToTP
if gatesetsByL_noGaugeOpt is not None:
self.gatesetEstimates_noGO = gatesetsByL_noGaugeOpt
else:
self.gatesetEstimates_noGO = None
self.bEssentialResultsSet = True
#Set "Ls and germs" info: gives particular structure
# to the gateStringLists used to obtain estimates
self.rhoStrs = rhoStrs
self.EStrs = EStrs
self.germs = germs
self.Ls = Ls
self.rhoEPairs = rhoEPairs
self.L_germ_tuple_to_baseStr_dict = { (L,germ):truncFn(germ,L) for L in Ls for germ in germs}
self.LsAndGermInfoSet = True
def setAdditionalInfo(self,minProbClip=1e-6, minProbClipForWeighting=1e-4,
probClipInterval=(-1e6,1e6), radius=1e-4,
weightsDict=None, defaultDirectory=None, defaultBasename=None):
"""
Set advanced parameters for producing derived outputs. Usually the default
values are fine (which is why setting these inputs is separated into a
separate function).
Parameters
----------
minProbClip : float, optional
The minimum probability treated normally in the evaluation of the log-likelihood.
A penalty function replaces the true log-likelihood for probabilities that lie
below this threshold so that the log-likelihood never becomes undefined (which improves
optimizer performance).
minProbClipForWeighting : float, optional
Sets the minimum and maximum probability p allowed in the chi^2 weights: N/(p*(1-p))
by clipping probability p values to lie within the interval
[ minProbClipForWeighting, 1-minProbClipForWeighting ].
probClipInterval : 2-tuple or None, optional
(min,max) values used to clip the probabilities predicted by gatesets during the
least squares search for an optimal gateset (if not None).
radius : float, optional
Specifies the severity of rounding used to "patch" the zero-frequency
terms of the log-likelihood.
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.
defaultDirectory : string, optional
Path to the default directory for generated reports and presentations.
defaultBasename : string, optional
Default basename for generated reports and presentations.
Returns
-------
None
"""
self.additionalInfo = { 'weights': weightsDict,
'minProbClip': minProbClip,
'minProbClipForWeighting': minProbClipForWeighting,
'probClipInterval': probClipInterval,
'radius': radius,
'hessianProjection': 'std',
'defaultDirectory': defaultDirectory,
'defaultBasename': defaultBasename }
def setTemplatePath(self, pathToTemplates):
"""
Sets the location of GST report and presentation templates.
Parameters
----------
pathToTemplates : string
The path to a folder containing GST's template files.
Usually this can be determined automatically (the default).
"""
self.templatePath = pathToTemplates
def setLatexCmd(self, latexCmd):
"""
Sets the shell command used for compiling latex reports and
presentations.
Parameters
----------
latexCmd : string
The command to run to invoke the latex compiler,
typically just 'pdflatex' when it is on the system
path.
"""
self.latexCmd = latexCmd
def getConfidenceRegion(self, confidenceLevel):
"""
Get the ConfidenceRegion object associated with a given confidence level.
One will be created and cached the first time given level is requested,
and future requests will return the cached object.
Parameters
----------
confidenceLevel : float
The confidence level (between 0 and 100).
Returns
-------
ConfidenceRegion
"""
assert(self.bEssentialResultsSet)
if confidenceLevel is None:
return None
if confidenceLevel not in self.confidenceRegions:
if self.objective == "logL":
cr = _RG.constructLogLConfidenceRegion(self.gsBestEstimate, self.dataset, confidenceLevel, self.constrainToTP,
self.bestGateStringList, self.additionalInfo['probClipInterval'],
self.additionalInfo['minProbClip'], self.additionalInfo['radius'],
self.additionalInfo['hessianProjection'])
elif self.objective == "chi2":
cr = _RG.constructChi2ConfidenceRegion(self.gsBestEstimate, self.dataset, confidenceLevel, self.constrainToTP,
self.bestGateStringList, self.additionalInfo['probClipInterval'],
self.additionalInfo['minProbClipForWeighting'], self.additionalInfo['hessianProjection'])
else:
raise ValueError("Invalid objective given in essential info: %s" % self.objective)
self.confidenceRegions[confidenceLevel] = cr
return self.confidenceRegions[confidenceLevel]
def getTable(self, tableName, confidenceLevel=None, fmt="py", verbosity=0):
"""
Get a report table in a specified format. Tables are created on
the first request then cached for later requests for the same table.
This method is typically used internally by other Results methods.
Parameters
----------
tableName : string
The name of the table.
confidenceLevel : float, optional
If not None, then the confidence level (between 0 and 100) used to
put error bars on the table's values (if possible). If None, no
confidence regions or intervals are included.
fmt : { 'py', 'html', 'latex', 'ppt' }, optional
The format of the table to be returned.
verbosity : int, optional
How much detail to send to stdout.
Returns
-------
string or object
The requested table in the requested format. 'py' and 'ppt'
tables are objects, 'html' and 'latex' tables are strings.
"""
assert(self.bEssentialResultsSet)
if self.tables.has_key(confidenceLevel) == False:
self.tables[confidenceLevel] = {}
if tableName not in self.tables[confidenceLevel]:
self.tables[confidenceLevel][tableName] = self._generateTable(tableName, confidenceLevel, verbosity)
return self.tables[confidenceLevel][tableName][fmt]
def _generateTable(self, tableName, confidenceLevel, verbosity):
"""
Switchboard method for actually creating a table (including computation
of its values.
"""
assert(self.bEssentialResultsSet)
gaugeOptAppendixTablenames = [ 'best%sGateset%sTable' % (a,b) for a in ('Target','TargetSpam','TargetGates','CPTP','TP') \
for b in ('Spam','SpamParameters','Gates','Choi','Decomp','ClosestUnitary','VsTarget') ]
if verbosity > 0:
print "Generating %s table..." % tableName; _sys.stdout.flush()
# target gateset tables
if tableName == 'targetSpamTable':
return _RG.getGatesetSPAMTable(self.gsTarget, self.formatsToCompute, self.tableClass, self.longTables)
elif tableName == 'targetGatesTable':
return _RG.getUnitaryGatesetGatesTable(self.gsTarget, self.formatsToCompute, self.tableClass, self.longTables)
# dataset and gatestring list tables
elif tableName == 'datasetOverviewTable':
return _RG.getDatasetOverviewTable(self.dataset, self.formatsToCompute, self.tableClass, self.longTables)
elif tableName == 'fiducialListTable':
return _RG.getGatestringMultiTable([self.rhoStrs, self.EStrs], ["Prep.","Measure"],self.formatsToCompute,
self.tableClass, self.longTables, "Fiducials")
elif tableName == 'rhoStrListTable':
return _RG.getGatestringTable(self.rhoStrs, "Preparation Fiducial", self.formatsToCompute, self.tableClass, self.longTables)
elif tableName == 'EStrListTable':
return _RG.getGatestringTable(self.EStrs, "Measurement Fiducial", self.formatsToCompute, self.tableClass, self.longTables)
elif tableName == 'germListTable':
return _RG.getGatestringTable(self.germs, "Germ", self.formatsToCompute, self.tableClass, self.longTables)
# Estimated gateset tables
elif tableName == 'bestGatesetSpamTable':
cri = self.getConfidenceRegion(confidenceLevel)
return _RG.getGatesetSPAMTable(self.gsBestEstimate, self.formatsToCompute, self.tableClass, self.longTables, cri)
elif tableName == 'bestGatesetSpamParametersTable':
cri = self.getConfidenceRegion(confidenceLevel)
return _RG.getGatesetSPAMParametersTable(self.gsBestEstimate, self.formatsToCompute, self.tableClass, self.longTables, cri)
elif tableName == 'bestGatesetGatesTable':
cri = self.getConfidenceRegion(confidenceLevel)
return _RG.getGatesetGatesTable(self.gsBestEstimate, self.formatsToCompute, self.tableClass, self.longTables, cri)
elif tableName == 'bestGatesetChoiTable':
cri = self.getConfidenceRegion(confidenceLevel)
return _RG.getGatesetChoiTable(self.gsBestEstimate, self.formatsToCompute, self.tableClass, self.longTables, cri)
elif tableName == 'bestGatesetDecompTable':
cri = self.getConfidenceRegion(confidenceLevel)
return _RG.getGatesetDecompTable(self.gsBestEstimate, self.formatsToCompute, self.tableClass, self.longTables, cri)
elif tableName == 'bestGatesetRotnAxisTable':
cri = self.getConfidenceRegion(confidenceLevel)
return _RG.getGatesetRotnAxisTable(self.gsBestEstimate, self.formatsToCompute, self.tableClass, self.longTables, cri)
elif tableName == 'bestGatesetClosestUnitaryTable':
#cri = self.getConfidenceRegion(confidenceLevel)
return _RG.getGatesetClosestUnitaryTable(self.gsBestEstimate, self.formatsToCompute, self.tableClass, self.longTables) #, cri)
elif tableName == 'bestGatesetVsTargetTable':
cri = self.getConfidenceRegion(confidenceLevel)
return _RG.getGatesetVsTargetTable(self.gsBestEstimate, self.gsTarget, self.formatsToCompute, self.tableClass, self.longTables, cri)
elif tableName == 'bestGatesetErrorGenTable':
cri = self.getConfidenceRegion(confidenceLevel)
return _RG.getGatesetVsTargetErrGenTable(self.gsBestEstimate, self.gsTarget, self.formatsToCompute, self.tableClass, self.longTables, cri)
# progress tables
elif tableName == 'chi2ProgressTable':
assert(self.LsAndGermInfoSet)
return _RG.getChi2ProgressTable(self.Ls, self.gatesets, self.gateStringLists, self.dataset, self.constrainToTP,
self.formatsToCompute, self.tableClass, self.longTables)
elif tableName == 'logLProgressTable':
assert(self.LsAndGermInfoSet)
return _RG.getLogLProgressTable(self.Ls, self.gatesets, self.gateStringLists, self.dataset, self.constrainToTP,
self.formatsToCompute, self.tableClass, self.longTables)
else:
raise ValueError("Invalid table name: %s" % tableName)
def getFigure(self, figureName, verbosity=0):
"""
Get a report figure. Figures are created on the first
request then cached for later requests for the same figure.
This method is typically used internally by other Results methods.
Parameters
----------
figureName : string
The name of the figure.
verbosity : int, optional
How much detail to send to stdout.
Returns
-------
GSTFigure
The requested figure object.
"""
assert(self.bEssentialResultsSet)
if figureName not in self.figures:
self.figures[figureName] = self._generateFigure(figureName, verbosity)
return self.figures[figureName]
def _generateFigure(self, figureName, verbosity):
"""
Switchboard method for actually creating a figure (including computation
of its values.
"""
assert(self.bEssentialResultsSet)
assert(self.LsAndGermInfoSet)
if verbosity > 0:
print "Generating %s figure..." % figureName; _sys.stdout.flush()
if self.objective == "chi2":
plotFn = _AT.ChiSqBoxPlot
directPlotFn = _AT.DirectChiSqBoxPlot
whackAMolePlotFn = _AT.WhackAChiSqMoleBoxPlot
#plotFnName,plotFnLatex = "Chi2", "$\chi^2$"
mpc = self.additionalInfo['minProbClipForWeighting']
elif self.objective == "logL":
plotFn = _AT.LogLBoxPlot
directPlotFn = _AT.DirectLogLBoxPlot
whackAMolePlotFn = _AT.WhackALogLMoleBoxPlot
#plotFnName,plotFnLatex = "LogL", "$\\log(\\mathcal{L})$"
mpc = self.additionalInfo['minProbClip']
else:
raise ValueError("Invalid objective value: %s" % self.objective)
m = 0
M = 10
baseStr_dict = self._getBaseStrDict()
strs = self.rhoStrs, self.EStrs
st = 1 if self.Ls[0] == 0 else 0 #start index: skips LGST column in report color box plots
if figureName == "bestEstimateColorBoxPlot":
fig = plotFn( self.Ls[st:], self.germs, baseStr_dict, self.dataset, self.gsBestEstimate, strs,
"L", "germ", M=M, m=m, scale=1.0, sumUp=False, histogram=True, title="", rhoEPairs=self.rhoEPairs,
minProbClipForWeighting=mpc, saveTo="", ticSize=20)
elif figureName == "invertedBestEstimateColorBoxPlot":
fig = plotFn( self.Ls[st:], self.germs, baseStr_dict, self.dataset, self.gsBestEstimate, strs,
"L", "germ", M=M, m=m, scale=1.0, sumUp=False, histogram=True, title="", rhoEPairs=self.rhoEPairs,
saveTo="", ticSize=20, minProbClipForWeighting=mpc, invert=True)
elif figureName == "bestEstimateSummedColorBoxPlot":
sumScale = len(self.rhoStrs)*len(self.EStrs) if self.rhoEPairs is None else len(self.rhoEPairs)
fig = plotFn( self.Ls[st:], self.germs, baseStr_dict, self.dataset, self.gsBestEstimate, strs,
"L", "germ", M=M*sumScale, m=m*sumScale, scale=1.0, sumUp=True, histogram=False,
title="", rhoEPairs=self.rhoEPairs, minProbClipForWeighting=mpc, saveTo="", ticSize=14)
elif figureName.startswith("estimateForLIndex") and figureName.endswith("ColorBoxPlot"):
i = int(figureName[len("estimateForLIndex"):-len("ColorBoxPlot")])
fig = plotFn( self.Ls[st:i+1], self.germs, baseStr_dict, self.dataset, self.gatesets[i],
strs, "L", "germ", M=M, m=m, scale=1.0, sumUp=False, histogram=False, title="",
rhoEPairs=self.rhoEPairs, saveTo="", minProbClipForWeighting=mpc, ticSize=20 )
elif figureName == "blankBoxPlot":
#TODO - have BlankBoxPlot return a GSTFigure object
raise ValueError("not implemented")
fig = _AT.BlankBoxPlot( self.Ls, self.germs, baseStr_dict, strs, "L", "germ", scale=1.0, title="",
sumUp=False, saveTo="", ticSize=20)
elif figureName == "blankSummedBoxPlot":
#TODO - have BlankBoxPlot return a GSTFigure object
raise ValueError("not implemented")
fig = _AT.BlankBoxPlot( self.Ls, self.germs, baseStr_dict, strs, "L", "germ", scale=1.0, title="",
sumUp=True, saveTo="", ticSize=20)
elif figureName == "directLGSTColorBoxPlot":
directLGST = self.getSpecial('DirectLGSTGatesets')
fig = directPlotFn( self.Ls[st:], self.germs, baseStr_dict, self.dataset, directLGST, strs,
"L", "germ", M=M, m=m, scale=1.0, sumUp=False, title="", minProbClipForWeighting=mpc,
rhoEPairs=self.rhoEPairs, saveTo="", ticSize=20)
elif figureName == "directLongSeqGSTColorBoxPlot":
directLongSeqGST = self.getSpecial('DirectLongSeqGatesets')
fig = directPlotFn( self.Ls[st:], self.germs, baseStr_dict, self.dataset, directLongSeqGST, strs,
"L", "germ", M=M, m=m, scale=1.0, sumUp=False, title="",minProbClipForWeighting=mpc,
rhoEPairs=self.rhoEPairs, saveTo="", ticSize=20)
elif figureName == "directLGSTDeviationColorBoxPlot":
directLGST = self.getSpecial('DirectLGSTGatesets')
fig = _AT.DirectDeviationBoxPlot( self.Ls[st:], self.germs, baseStr_dict, self.dataset, self.gsBestEstimate, directLGST,
"L", "germ", m=0, scale=1.0, prec=-1, title="", saveTo="", ticSize=20)
elif figureName == "directLongSeqGSTDeviationColorBoxPlot":
directLongSeqGST = self.getSpecial('DirectLongSeqGatesets')
fig = _AT.DirectDeviationBoxPlot( self.Ls[st:], self.germs, baseStr_dict, self.dataset, self.gsBestEstimate, directLongSeqGST,
"L", "germ", m=0, scale=1.0, prec=-1, title="", saveTo="", ticSize=20)
elif figureName == "smallEigvalErrRateColorBoxPlot":
directLongSeqGST = self.getSpecial('DirectLongSeqGatesets')
fig = _AT.SmallEigvalErrRateBoxPlot( self.Ls[st:], self.germs, baseStr_dict, self.dataset, directLongSeqGST,
"L", "germ", m=0, scale=1.0, title="", saveTo="", ticSize=20)
elif figureName.startswith("whack") and figureName.endswith("MoleBoxes"):
gateLabel = figureName[len("whack"):-len("MoleBoxes")]
highestL = self.Ls[-1]; allGateStrings = self.gateStringLists[-1]; hammerWeight = 10.0
len1GermFirstEls = [ g[0] for g in self.germs if len(g) == 1 ]
assert(gateLabel in len1GermFirstEls) #only these whack-a-mole plots are available
strToWhack = _gatestring.GateString( (gateLabel,)*highestL )
fig = whackAMolePlotFn( strToWhack, allGateStrings, self.Ls[st:], self.germs, baseStr_dict, self.dataset,
self.gsBestEstimate, strs, "L", "germ", scale=1.0, sumUp=False, title="", whackWith=hammerWeight,
saveTo="", minProbClipForWeighting=mpc, ticSize=20, rhoEPairs=self.rhoEPairs, m=0)
elif figureName.startswith("whack") and figureName.endswith("MoleBoxesSummed"):
gateLabel = figureName[len("whack"):-len("MoleBoxesSummed")]
highestL = self.Ls[-1]; allGateStrings = self.gateStringLists[-1]; hammerWeight = 10.0
len1GermFirstEls = [ g[0] for g in self.germs if len(g) == 1 ]
assert(gateLabel in len1GermFirstEls) #only these whack-a-mole plots are available
strToWhack = _gatestring.GateString( (gateLabel,)*highestL )
fig = whackAMolePlotFn( strToWhack, allGateStrings, self.Ls[st:], self.germs, baseStr_dict, self.dataset,
self.gsBestEstimate, strs, "L", "germ", scale=1.0, sumUp=True, title="", whackWith=hammerWeight,
saveTo="", minProbClipForWeighting=mpc, ticSize=20, rhoEPairs=self.rhoEPairs, m=0)
else:
raise ValueError("Invalid figure name: %s" % figureName)
return fig
def getSpecial(self, specialName, verbosity=0):
"""
Get a "special item", which can be almost anything used in report
or presentation construction. This method is almost solely used
internally by other Results methods.
Parameters
----------
tableName : string
The name of the special item.
verbosity : int, optional
How much detail to send to stdout.
Returns
-------
special item (type varies)
"""
if specialName not in self.specials:
self.specials[specialName] = self._generateSpecial(specialName, verbosity)
return self.specials[specialName]
def _generateSpecial(self, specialName, verbosity):
""" Switchboard function for creating "special" items """
if specialName == 'gaugeOptAppendixGatesets':
assert(self.bEssentialResultsSet)
if verbosity > 0:
print "Performing gauge transforms for appendix..."; _sys.stdout.flush()
best_gs_gauges = _collections.OrderedDict()
best_gs_gauges['Target'] = _optimizeGauge(self.gsBestEstimate, "target", targetGateset=self.gsTarget,
constrainToTP=self.constrainToTP, gateWeight=1.0, spamWeight=1.0, verbosity=2)
best_gs_gauges['TargetSpam'] = _optimizeGauge(self.gsBestEstimate, "target", targetGateset=self.gsTarget, verbosity=2,
gateWeight=0.01, spamWeight=0.99, constrainToTP=self.constrainToTP)
best_gs_gauges['TargetGates'] = _optimizeGauge(self.gsBestEstimate, "target", targetGateset=self.gsTarget, verbosity=2,
gateWeight=0.99, spamWeight=0.01, constrainToTP=self.constrainToTP)
best_gs_gauges['CPTP'] = _optimizeGauge(self.gsBestEstimate, "CPTP and target", targetGateset=self.gsTarget, verbosity=2,
targetFactor=1.0e-7, constrainToTP=self.constrainToTP)
if self.constrainToTP:
best_gs_gauges['TP'] = best_gs_gauges['Target'].copy() #assume best_gs is already in TP, so just optimize to target (done above)
else:
best_gs_gauges['TP'] = _optimizeGauge(self.gsBestEstimate, "TP and target", targetGateset=self.gsTarget, targetFactor=1.0e-7)
return best_gs_gauges
elif specialName == 'gaugeOptAppendixTables':
assert(self.bEssentialResultsSet)
best_gs_gauges = self.getSpecial('gaugeOptAppendixGatesets')
ret = {}
for gaugeKey,gopt_gs in best_gs_gauges.iteritems():
#FUTURE: add confidence region support to these appendices? -- would need to compute confidenceRegionInfo (cri)
# for each gauge-optimized gateset, gopt_gs and pass to appropriate functions below
ret['best%sGatesetSpamTable' % gaugeKey] = \
_RG.getGatesetSPAMTable(gopt_gs, self.formatsToCompute, self.tableClass, self.longTables)
ret['best%sGatesetSpamParametersTable' % gaugeKey] = \
_RG.getGatesetSPAMParametersTable(gopt_gs, self.formatsToCompute, self.tableClass, self.longTables)
ret['best%sGatesetGatesTable' % gaugeKey] = \
_RG.getGatesetGatesTable(gopt_gs, self.formatsToCompute, self.tableClass, self.longTables)
ret['best%sGatesetChoiTable' % gaugeKey] = \
_RG.getGatesetChoiTable(gopt_gs, self.formatsToCompute, self.tableClass, self.longTables)
ret['best%sGatesetDecompTable' % gaugeKey] = \
_RG.getGatesetDecompTable(gopt_gs, self.formatsToCompute, self.tableClass, self.longTables)
ret['best%sGatesetRotnAxisTable' % gaugeKey] = \
_RG.getGatesetRotnAxisTable(gopt_gs, self.formatsToCompute, self.tableClass, self.longTables)
ret['best%sGatesetClosestUnitaryTable' % gaugeKey] = \
_RG.getGatesetClosestUnitaryTable(gopt_gs, self.formatsToCompute, self.tableClass, self.longTables)
ret['best%sGatesetVsTargetTable' % gaugeKey] = \
_RG.getGatesetVsTargetTable(gopt_gs, self.gsTarget, self.formatsToCompute, self.tableClass, self.longTables)
ret['best%sGatesetErrorGenTable' % gaugeKey] = \
_RG.getGatesetVsTargetErrGenTable(gopt_gs, self.gsTarget, self.formatsToCompute, self.tableClass, self.longTables)
return ret
elif specialName == 'blankGaugeOptAppendixTables':
assert(self.bEssentialResultsSet)
ret = {}
for gaugeKey in ('Target','TargetSpam', 'TargetGates', 'CPTP', 'TP'):
ret['best%sGatesetSpamTable' % gaugeKey] = _RG.getBlankTable(self.formatsToCompute)
ret['best%sGatesetSpamParametersTable' % gaugeKey] = _RG.getBlankTable(self.formatsToCompute)
ret['best%sGatesetGatesTable' % gaugeKey] = _RG.getBlankTable(self.formatsToCompute)
ret['best%sGatesetChoiTable' % gaugeKey] = _RG.getBlankTable(self.formatsToCompute)
ret['best%sGatesetDecompTable' % gaugeKey] = _RG.getBlankTable(self.formatsToCompute)
ret['best%sGatesetRotnAxisTable' % gaugeKey] = _RG.getBlankTable(self.formatsToCompute)
ret['best%sGatesetClosestUnitaryTable' % gaugeKey] = _RG.getBlankTable(self.formatsToCompute)
ret['best%sGatesetVsTargetTable' % gaugeKey] = _RG.getBlankTable(self.formatsToCompute)
ret['best%sGatesetErrorGenTable' % gaugeKey] = _RG.getBlankTable(self.formatsToCompute)
return ret
elif specialName == "DirectLGSTGatesets":
assert(self.bEssentialResultsSet)
assert(self.LsAndGermInfoSet)
direct_specs = _getRhoAndESpecs(rhoStrs=self.rhoStrs, EStrs=self.EStrs, EVecInds=self.gsTarget.getEVecIndices() )
baseStrs = [] # (L,germ) base strings without duplicates
for L in self.Ls:
for germ in self.germs:
if self.L_germ_tuple_to_baseStr_dict[(L,germ)] not in baseStrs:
baseStrs.append( self.L_germ_tuple_to_baseStr_dict[(L,germ)] )
return _AT.DirectLGSTGatesets( baseStrs, self.dataset, direct_specs, self.gsTarget, svdTruncateTo=4, verbosity=0) #TODO: svdTruncateTo set elegantly?
elif specialName == "DirectLongSeqGatesets":
assert(self.bEssentialResultsSet)
assert(self.LsAndGermInfoSet)
direct_specs = _getRhoAndESpecs(rhoStrs=self.rhoStrs, EStrs=self.EStrs, EVecInds=self.gsTarget.getEVecIndices() )
baseStrs = [] # (L,germ) base strings without duplicates
for L in self.Ls:
for germ in self.germs:
if self.L_germ_tuple_to_baseStr_dict[(L,germ)] not in baseStrs:
baseStrs.append( self.L_germ_tuple_to_baseStr_dict[(L,germ)] )
if self.objective == "chi2":
return _AT.DirectLSGSTGatesets(baseStrs, self.dataset, direct_specs, self.gsTarget, svdTruncateTo=self.gsTarget.get_dimension(),
minProbClipForWeighting=self.additionalInfo['minProbClipForWeighting'],
probClipInterval=self.additionalInfo['probClipInterval'], verbosity=0)
elif self.objective == "logL":
return _AT.DirectMLEGSTGatesets(baseStrs, self.dataset, direct_specs, self.gsTarget, svdTruncateTo=self.gsTarget.get_dimension(),
minProbClip=self.additionalInfo['minProbClip'],
probClipInterval=self.additionalInfo['probClipInterval'], verbosity=0)
else:
raise ValueError("Invalid Objective: %s" % self.objective)
else:
raise ValueError("Invalid special name: %s" % specialName)
def _merge_template(self, qtys, templateFilename, outputFilename):
if self.templatePath is None:
templateFilename = _os.path.join( _os.path.dirname(_os.path.abspath(__file__)),
"templates", templateFilename )
else:
templateFilename = _os.path.join( self.templatePath, templateFilename )
template = open(templateFilename,"r").read()
template = template.replace("{", "{{").replace("}", "}}") #double curly braces (for format processing)
# Replace template field markers with `str.format` fields.
template = _re.sub( r"\\putfield\{\{([^}]+)\}\}\{\{[^}]*\}\}", "{\\1}", template)
# Replace str.format fields with values and write to output file
template = template.format(**qtys)
open(outputFilename,'w').write(template)
def _getBaseStrDict(self, remove_dups = True):
#if remove_dups == True, remove duplicates in
# L_germ_tuple_to_baseStr_dict by replacing with None
assert(self.bEssentialResultsSet)
assert(self.LsAndGermInfoSet)
baseStr_dict = {}
st = 1 if self.Ls[0] == 0 else 0 #start index: skips LGST column in report color box plots
tmpRunningList = []
for L in self.Ls[st:]:
for germ in self.germs:
if remove_dups and self.L_germ_tuple_to_baseStr_dict[(L,germ)] in tmpRunningList:
baseStr_dict[(L,germ)] = None
else:
tmpRunningList.append( self.L_germ_tuple_to_baseStr_dict[(L,germ)] )
baseStr_dict[(L,germ)] = self.L_germ_tuple_to_baseStr_dict[(L,germ)]
return baseStr_dict
def createFullReportPDF(self, confidenceLevel=None, filename="auto",
title="auto", datasetLabel="auto", suffix="",
debugAidsAppendix=False, gaugeOptAppendix=False,
pixelPlotAppendix=False, whackamoleAppendix=False,
m=0, M=10, verbosity=0):
"""
Create a "full" GST report. This report is the most detailed of any of
the GST reports, and includes background and explanation text to help
the user interpret the contained results.
Parameters
----------
confidenceLevel : float, optional
If not None, then the confidence level (between 0 and 100) used in
the computation of confidence regions/intervals. If None, no
confidence regions or intervals are computed.
filename : string, optional
The output filename where the report file(s) will be saved. Specifying
"auto" will use the default directory and base name (specified in
setAdditionalInfo) if given, otherwise the file "GSTReport.pdf" will
be output to the current directoy.
title : string, optional
The title of the report. "auto" uses a default title which
specifyies the label of the dataset as well.
datasetLabel : string, optional
A label given to the dataset. If set to "auto", then the label
will be the base name of the dataset filename without extension
(if given) or "$\\mathcal{D}$" (if not).
suffix : string, optional
A suffix to add to the end of the report filename. Useful when
filename is "auto" and you generate different reports using
the same dataset.
debugAidsAppendix : bool, optional
Whether to include the "debugging aids" appendix. This
appendix contains comparisons of GST and Direct-GST and small-
eigenvalue error rates among other quantities potentially
useful for figuring out why the GST estimate did not fit
the data as well as expected.
gaugeOptAppendix : bool, optional
Whether to include the "gauge optimization" appendix. This
appendix shows the results of gauge optimizing GST's best
estimate gate set in several different ways, and thus shows
how various report quantities can vary by a different gauge
choice.
pixelPlotAppendix : bool, optional
Whether to include the "pixel plots" appendix, which shows
the goodness of fit, in the form of color box plots, for the
intermediate iterations of the GST algortihm.
whackamoleAppendix : bool, optional
Whether to include the "whack-a-mole" appendix, which contains
colr box plots showing the effect of reducing ("whacking") one
particular part of the overall goodness of fit box plot.
m, M : float, optional
Minimum and Maximum values of the color scale used in the report's
color box plots.
verbosity : int, optional
How much detail to send to stdout.
Returns
-------
None
"""
assert(self.bEssentialResultsSet)
#Get report output filename
default_dir = self.additionalInfo['defaultDirectory']
default_base = self.additionalInfo['defaultBasename']
if filename != "auto":
report_dir = _os.path.dirname(filename)
report_base = _os.path.splitext( _os.path.basename(filename) )[0] + suffix
else:
cwd = _os.getcwd()
report_dir = default_dir if (default_dir is not None) else cwd
report_base = default_base if (default_base is not None) else "GSTReport"
report_base += suffix
if datasetLabel == "auto":
if default_base is not None:
datasetLabel = _LU.latex_escaped( default_base )
else:
datasetLabel = "$\\mathcal{D}$"
if title == "auto": title = "GST report for %s" % datasetLabel
###### Generate Report ######
#Steps:
# 1) generate latex tables
# 2) generate plots
# 3) populate template latex file => report latex file
# 4) compile report latex file into PDF
# 5) remove auxiliary files generated during compilation
# FUTURE?? determine what we need to compute & plot by reading through the template file?
baseStr_dict = self._getBaseStrDict()
#Note: for now, we assume the best gateset corresponds to the last L-value
best_gs = self.gsBestEstimate
if not self.LsAndGermInfoSet: #cannot create appendices which depend on this structure
debugAidsAppendix = False
pixelPlotAppendix = False
whackamoleAppendix = False
qtys = {} # dictionary to store all latex strings to be inserted into report template
qtys['title'] = title
qtys['datasetLabel'] = datasetLabel
qtys['settoggles'] = "\\togglefalse{confidences}\n" if confidenceLevel is None else "\\toggletrue{confidences}\n"
qtys['settoggles'] = "\\toggletrue{LsAndGermsSet}\n" if self.LsAndGermInfoSet else "\\toggletrue{LsAndGermsSet}\n"
qtys['settoggles'] += "\\toggletrue{debuggingaidsappendix}\n" if debugAidsAppendix else "\\togglefalse{debuggingaidsappendix}\n"
qtys['settoggles'] += "\\toggletrue{gaugeoptappendix}\n" if gaugeOptAppendix else "\\togglefalse{gaugeoptappendix}\n"
qtys['settoggles'] += "\\toggletrue{pixelplotsappendix}\n" if pixelPlotAppendix else "\\togglefalse{pixelplotsappendix}\n"
qtys['settoggles'] += "\\toggletrue{whackamoleappendix}\n" if whackamoleAppendix else "\\togglefalse{whackamoleappendix}\n"
qtys['confidenceLevel'] = "%g" % confidenceLevel if confidenceLevel is not None else "NOT-SET"
if confidenceLevel is not None:
cri = self.getConfidenceRegion(confidenceLevel)
qtys['confidenceIntervalScaleFctr'] = "%.3g" % cri.intervalScaling
qtys['confidenceIntervalNumNonGaugeParams'] = "%d" % cri.nNonGaugeParams
else:
cri = None
qtys['confidenceIntervalScaleFctr'] = "NOT-SET"
qtys['confidenceIntervalNumNonGaugeParams'] = "NOT-SET"
# 1) get latex tables
if verbosity > 0:
print "*** Generating tables ***"; _sys.stdout.flush()
required_tables = ('targetSpamTable','targetGatesTable','datasetOverviewTable',
'bestGatesetSpamTable','bestGatesetSpamParametersTable','bestGatesetGatesTable','bestGatesetChoiTable',
'bestGatesetDecompTable','bestGatesetRotnAxisTable','bestGatesetClosestUnitaryTable',
'bestGatesetVsTargetTable','bestGatesetErrorGenTable')
if self.LsAndGermInfoSet:
progress_tbl = 'logLProgressTable' if self.objective == "logL" else 'chi2ProgressTable'
required_tables += ('fiducialListTable','rhoStrListTable','EStrListTable','germListTable', progress_tbl)
for key in required_tables:
qtys[key] = self.getTable(key, confidenceLevel, 'latex', verbosity)
if gaugeOptAppendix: #get appendix tables if needed
goaTables = self.getSpecial('gaugeOptAppendixTables', verbosity)
qtys.update( { key : goaTables[key]['latex'] for key in goaTables } )
elif any((debugAidsAppendix, pixelPlotAppendix, whackamoleAppendix)): # if other appendices used,
goaTables = self.getSpecial('blankGaugeOptAppendixTables', verbosity) # fill keys with blank tables
qtys.update( { key : goaTables[key]['latex'] for key in goaTables } ) # for format substitution
# 2) generate plots
if verbosity > 0:
print "*** Generating plots ***"; _sys.stdout.flush()
if _matplotlib.is_interactive():
_matplotlib.pyplot.ioff()
bWasInteractive = True
else: bWasInteractive = False
strs = self.rhoStrs, self.EStrs
D = report_base + "_files" #figure directory relative to reportDir
if not _os.path.isdir( _os.path.join(report_dir,D)):
_os.mkdir( _os.path.join(report_dir,D))
maxW,maxH = 6.5,9.0 #max width and height of graphic in latex document (in inches)
#Chi2 or logL plots
if self.LsAndGermInfoSet:
st = 1 if self.Ls[0] == 0 else 0 #start index: skips LGST column in report color box plots
nPlots = (len(self.Ls[st:])-1)+2 if pixelPlotAppendix else 2
if self.objective == "chi2":
plotFnName,plotFnLatex = "Chi2", "$\chi^2$"
elif self.objective == "logL":
plotFnName,plotFnLatex = "LogL", "$\\log(\\mathcal{L})$"
else:
raise ValueError("Invalid objective value: %s" % self.objective)
if verbosity > 0:
print " -- %s plots (%d): " % (plotFnName, nPlots),; _sys.stdout.flush()
if verbosity > 0:
print "1 ",; _sys.stdout.flush()
fig = self.getFigure("bestEstimateColorBoxPlot",verbosity)
fig.saveTo(_os.path.join(report_dir, D,"best%sBoxes.pdf" % plotFnName))
maxX = fig.getExtraInfo()['nUsedXs']; maxY = fig.getExtraInfo()['nUsedYs']
if verbosity > 0:
print "2 ",; _sys.stdout.flush()
fig = self.getFigure("invertedBestEstimateColorBoxPlot",verbosity)
fig.saveTo(_os.path.join(report_dir, D,"best%sBoxes_inverted.pdf" % plotFnName))
pixplots = ""
if pixelPlotAppendix:
for i in range(st,len(self.Ls)-1):
if verbosity > 0:
print "%d " % (i-st+3),; _sys.stdout.flush()
fig = self.getFigure("estimateForLIndex%dColorBoxPlot" % i, verbosity)
fig.saveTo( _os.path.join(report_dir, D,"L%d_%sBoxes.pdf" % (i,plotFnName)) )
lx = fig.getExtraInfo()['nUsedXs']; ly = fig.getExtraInfo()['nUsedYs']
W = float(lx+1)/float(maxX+1) * maxW #scale figure size according to number of rows
H = float(ly) /float(maxY) * maxH # and columns+1 (+1 for labels ~ another col) relative to initial plot
pixplots += "\n"
pixplots += "\\begin{figure}\n"
pixplots += "\\begin{center}\n"
pixplots += "\\includegraphics[width=%fin,height=%fin,keepaspectratio]{%s/L%d_%sBoxes.pdf}\n" % (W,H,D,i,plotFnName)
pixplots += "\\caption{Box plot of iteration %d (L=%d) gateset %s values.\label{L%dGateset%sBoxPlot}}\n" % (i,self.Ls[i],plotFnLatex,i,plotFnName)
pixplots += "\\end{center}\n"
pixplots += "\\end{figure}\n"
if verbosity > 0:
print ""; _sys.stdout.flush()