/
workspacetables.py
3036 lines (2458 loc) · 132 KB
/
workspacetables.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
""" Classes corresponding to tables within a Workspace context."""
#***************************************************************************************************
# 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 warnings as _warnings
import numpy as _np
import scipy.sparse as _sps
from .. import construction as _cnst
from .. import tools as _tools
from .. import objects as _objs
from . import reportables as _reportables
from .reportables import evaluate as _ev
from ..objects.label import Label as _Lbl
from ..objects.basis import DirectSumBasis as _DirectSumBasis
from ..algorithms import gaugeopt as _gopt
from .table import ReportTable as _ReportTable
from .workspace import WorkspaceTable
from . import workspaceplots as _wp
from . import plothelpers as _ph
class BlankTable(WorkspaceTable):
"""A completely blank placeholder table."""
def __init__(self, ws):
"""A completely blank placeholder table."""
super(BlankTable, self).__init__(ws, self._create)
def _create(self):
table = _ReportTable(['Blank'], [None])
table.finish()
return table
class SpamTable(WorkspaceTable):
""" A table of one or more model's SPAM elements. """
def __init__(self, ws, models, titles=None,
display_as="boxes", confidenceRegionInfo=None,
includeHSVec=True):
"""
A table of one or more model's SPAM elements.
Parameters
----------
models : Model or list of Models
The Model(s) whose SPAM elements should be displayed. If
multiple Models are given, they should have the same SPAM
elements..
titles : list of strs, optional
Titles correponding to elements of `models`, e.g. `"Target"`.
display_as : {"numbers", "boxes"}, optional
How to display the SPAM matrices, as either numerical
grids (fine for small matrices) or as a plot of colored
boxes (space-conserving and better for large matrices).
confidenceRegionInfo : ConfidenceRegion, optional
If not None, specifies a confidence-region
used to display error intervals.
includeHSVec : boolean, optional
Whether or not to include Hilbert-Schmidt
vector representation columns in the table.
"""
super(SpamTable, self).__init__(ws, self._create, models,
titles, display_as, confidenceRegionInfo,
includeHSVec)
def _create(self, models, titles, display_as, confidenceRegionInfo,
includeHSVec):
if isinstance(models, _objs.Model):
models = [models]
rhoLabels = list(models[0].preps.keys()) # use labels of 1st model
povmLabels = list(models[0].povms.keys()) # use labels of 1st model
if titles is None:
titles = [''] * len(models)
colHeadings = ['Operator']
for model, title in zip(models, titles):
colHeadings.append('%sMatrix' % (title + ' ' if title else ''))
for model, title in zip(models, titles):
colHeadings.append('%sEigenvals' % (title + ' ' if title else ''))
formatters = [None] * len(colHeadings)
if includeHSVec:
model = models[-1] # only show HSVec for last model
basisNm = _tools.basis_longname(model.basis)
colHeadings.append('Hilbert-Schmidt vector (%s basis)' % basisNm)
formatters.append(None)
if confidenceRegionInfo is not None:
colHeadings.append('%g%% C.I. half-width' % confidenceRegionInfo.level)
formatters.append('Conversion')
table = _ReportTable(colHeadings, formatters, confidenceRegionInfo=confidenceRegionInfo)
for lbl in rhoLabels:
rowData = [lbl]; rowFormatters = ['Rho']
for model in models:
rhoMx = _ev(_reportables.Vec_as_stdmx(model, lbl, "prep"))
# confidenceRegionInfo) #don't put CIs on matrices for now
if display_as == "numbers":
rowData.append(rhoMx)
rowFormatters.append('Brackets')
elif display_as == "boxes":
rhoMx_real = rhoMx.hermitian_to_real()
v = rhoMx_real.get_value()
fig = _wp.GateMatrixPlot(self.ws, v, colorbar=False,
boxLabels=True, prec='compacthp',
mxBasis=None) # no basis labels
rowData.append(fig)
rowFormatters.append('Figure')
else:
raise ValueError("Invalid 'display_as' argument: %s" % display_as)
for model in models:
cri = confidenceRegionInfo if confidenceRegionInfo and \
(confidenceRegionInfo.model.frobeniusdist(model) < 1e-6) else None
evals = _ev(_reportables.Vec_as_stdmx_eigenvalues(model, lbl, "prep"),
cri)
rowData.append(evals)
rowFormatters.append('Brackets')
if includeHSVec:
rowData.append(models[-1].preps[lbl])
rowFormatters.append('Normal')
if confidenceRegionInfo is not None:
intervalVec = confidenceRegionInfo.get_profile_likelihood_confidence_intervals(lbl)[:, None]
if intervalVec.shape[0] == models[-1].get_dimension() - 1:
#TP constrained, so pad with zero top row
intervalVec = _np.concatenate((_np.zeros((1, 1), 'd'), intervalVec), axis=0)
rowData.append(intervalVec); rowFormatters.append('Normal')
#Note: no dependence on confidence region (yet) when HS vector is not shown...
table.addrow(rowData, rowFormatters)
for povmlbl in povmLabels:
for lbl in models[0].povms[povmlbl].keys():
povmAndELbl = str(povmlbl) + ":" + lbl # format for ModelFunction objs
# show POVM name if there's more than one of them
rowData = [lbl] if (len(povmLabels) == 1) else [povmAndELbl]
rowFormatters = ['Effect']
for model in models:
EMx = _ev(_reportables.Vec_as_stdmx(model, povmAndELbl, "effect"))
#confidenceRegionInfo) #don't put CIs on matrices for now
if display_as == "numbers":
rowData.append(EMx)
rowFormatters.append('Brackets')
elif display_as == "boxes":
EMx_real = EMx.hermitian_to_real()
v = EMx_real.get_value()
fig = _wp.GateMatrixPlot(self.ws, v, colorbar=False,
boxLabels=True, prec='compacthp',
mxBasis=None) # no basis labels
rowData.append(fig)
rowFormatters.append('Figure')
else:
raise ValueError("Invalid 'display_as' argument: %s" % display_as) # pragma: no cover
for model in models:
cri = confidenceRegionInfo if confidenceRegionInfo and \
(confidenceRegionInfo.model.frobeniusdist(model) < 1e-6) else None
evals = _ev(_reportables.Vec_as_stdmx_eigenvalues(model, povmAndELbl, "effect"),
cri)
rowData.append(evals)
rowFormatters.append('Brackets')
if includeHSVec:
rowData.append(models[-1].povms[povmlbl][lbl])
rowFormatters.append('Normal')
if confidenceRegionInfo is not None:
intervalVec = confidenceRegionInfo.get_profile_likelihood_confidence_intervals(povmlbl)[
:, None] # for all povm params
intervalVec = intervalVec[models[-1].povms[povmlbl][lbl].gpindices] # specific to this effect
rowData.append(intervalVec); rowFormatters.append('Normal')
#Note: no dependence on confidence region (yet) when HS vector is not shown...
table.addrow(rowData, rowFormatters)
table.finish()
return table
class SpamParametersTable(WorkspaceTable):
""" A table for "SPAM parameters" (dot products of SPAM vectors)"""
def __init__(self, ws, models, titles=None, confidenceRegionInfo=None):
"""
Create a table for model's "SPAM parameters", that is, the
dot products of prep-vectors and effect-vectors.
Parameters
----------
models : Model or list of Models
The Model(s) whose SPAM parameters should be displayed. If
multiple Models are given, they should have the same gates.
titles : list of strs, optional
Titles correponding to elements of `models`, e.g. `"Target"`.
confidenceRegionInfo : ConfidenceRegion, optional
If not None, specifies a confidence-region
used to display error intervals.
Returns
-------
ReportTable
"""
super(SpamParametersTable, self).__init__(ws, self._create, models, titles, confidenceRegionInfo)
def _create(self, models, titles, confidenceRegionInfo):
if isinstance(models, _objs.Model):
models = [models]
if titles is None:
titles = [''] * len(models)
if len(models[0].povms) == 1:
povmKey = list(models[0].povms.keys())[0]
effectLbls = [eLbl for eLbl in models[0].povms[povmKey]]
else:
effectLbls = [povmLbl + "." + eLbl
for povmLbl, povm in models[0].povms.items()
for eLbl in povm.keys()]
colHeadings = [''] + effectLbls
formatters = [None] + ['Effect'] * len(effectLbls)
table = _ReportTable(colHeadings, formatters, confidenceRegionInfo=confidenceRegionInfo)
for gstitle, model in zip(titles, models):
cri = confidenceRegionInfo if (confidenceRegionInfo
and confidenceRegionInfo.model.frobeniusdist(model) < 1e-6) else None
spamDotProdsQty = _ev(_reportables.Spam_dotprods(model), cri)
DPs, DPEBs = spamDotProdsQty.get_value_and_err_bar()
assert(DPs.shape[1] == len(effectLbls)), \
"Models must have the same number of POVMs & effects"
formatters = ['Rho'] + ['Normal'] * len(effectLbls) # for rows below
for ii, prepLabel in enumerate(model.preps.keys()): # ii enumerates rhoLabels to index DPs
prefix = gstitle + " " if len(gstitle) else ""
rowData = [prefix + str(prepLabel)]
for jj, _ in enumerate(effectLbls): # jj enumerates eLabels to index DPs
if cri is None:
rowData.append((DPs[ii, jj], None))
else:
rowData.append((DPs[ii, jj], DPEBs[ii, jj]))
table.addrow(rowData, formatters)
table.finish()
return table
class GatesTable(WorkspaceTable):
""" Create a table showing a model's raw gates. """
def __init__(self, ws, models, titles=None, display_as="boxes",
confidenceRegionInfo=None):
"""
Create a table showing a model's raw gates.
Parameters
----------
models : Model or list of Models
The Model(s) whose gates should be displayed. If multiple
Models are given, they should have the same operation labels.
titles : list of strings, optional
A list of titles corresponding to the models, used to
prefix the column(s) for that model. E.g. `"Target"`.
display_as : {"numbers", "boxes"}, optional
How to display the operation matrices, as either numerical
grids (fine for small matrices) or as a plot of colored
boxes (space-conserving and better for large matrices).
confidenceRegionInfo : ConfidenceRegion, optional
If not None, specifies a confidence-region
used to display error intervals for the *final*
element of `models`.
Returns
-------
ReportTable
"""
super(GatesTable, self).__init__(ws, self._create, models, titles,
display_as, confidenceRegionInfo)
def _create(self, models, titles, display_as, confidenceRegionInfo):
if isinstance(models, _objs.Model):
models = [models]
opLabels = models[0].get_primitive_op_labels() # use labels of 1st model
instLabels = list(models[0].instruments.keys()) # requires an explicit model!
assert(isinstance(models[0], _objs.ExplicitOpModel)), "%s only works with explicit models" % str(type(self))
if titles is None:
titles = [''] * len(models)
colHeadings = ['Gate']
for model, title in zip(models, titles):
basisLongNm = _tools.basis_longname(model.basis)
pre = (title + ' ' if title else '')
colHeadings.append('%sSuperoperator (%s basis)' % (pre, basisLongNm))
formatters = [None] * len(colHeadings)
if confidenceRegionInfo is not None:
#Only use confidence region for the *final* model.
colHeadings.append('%g%% C.I. half-width' % confidenceRegionInfo.level)
formatters.append('Conversion')
table = _ReportTable(colHeadings, formatters, confidenceRegionInfo=confidenceRegionInfo)
#Create list of labels and gate-like objects, allowing instruments to be included:
label_op_tups = []
for gl in opLabels:
# may want to gracefully handle index error here?
tup_of_ops = tuple([model.operations[gl] for model in models])
label_op_tups.append((gl, tup_of_ops))
for il in instLabels:
for comp_lbl in models[0].instruments[il].keys():
tup_of_ops = tuple([model.instruments[il][comp_lbl] for model in models]
) # may want to gracefully handle index error here?
label_op_tups.append((il + "." + comp_lbl, tup_of_ops))
for lbl, per_model_ops in label_op_tups:
row_data = [lbl]
row_formatters = [None]
for model, op in zip(models, per_model_ops):
basis = model.basis
if display_as == "numbers":
row_data.append(op)
row_formatters.append('Brackets')
elif display_as == "boxes":
fig = _wp.GateMatrixPlot(self.ws, op.todense(),
colorbar=False,
mxBasis=basis)
row_data.append(fig)
row_formatters.append('Figure')
else:
raise ValueError("Invalid 'display_as' argument: %s" % display_as)
if confidenceRegionInfo is not None:
intervalVec = confidenceRegionInfo.get_profile_likelihood_confidence_intervals(
lbl)[:, None] # TODO: won't work for instruments
if isinstance(per_model_ops[-1], _objs.FullDenseOp):
#then we know how to reshape into a matrix
op_dim = models[-1].get_dimension()
basis = models[-1].basis
intervalMx = intervalVec.reshape(op_dim, op_dim)
elif isinstance(per_model_ops[-1], _objs.TPDenseOp):
#then we know how to reshape into a matrix
op_dim = models[-1].get_dimension()
basis = models[-1].basis
intervalMx = _np.concatenate((_np.zeros((1, op_dim), 'd'),
intervalVec.reshape(op_dim - 1, op_dim)), axis=0)
else:
# we don't know how best to reshape interval matrix for gate, so
# use derivative
op_dim = models[-1].get_dimension()
basis = models[-1].basis
op_deriv = per_model_ops[-1].deriv_wrt_params()
intervalMx = _np.abs(_np.dot(op_deriv, intervalVec).reshape(op_dim, op_dim))
if display_as == "numbers":
row_data.append(intervalMx)
row_formatters.append('Brackets')
elif display_as == "boxes":
maxAbsVal = _np.max(_np.abs(intervalMx))
fig = _wp.GateMatrixPlot(self.ws, intervalMx,
m=-maxAbsVal, M=maxAbsVal,
colorbar=False,
mxBasis=basis)
row_data.append(fig)
row_formatters.append('Figure')
else:
assert(False) # pragma: no cover
table.addrow(row_data, row_formatters)
table.finish()
return table
class ChoiTable(WorkspaceTable):
"""A table of the Choi representations of a Model's gates"""
def __init__(self, ws, models, titles=None,
confidenceRegionInfo=None,
display=("matrix", "eigenvalues", "barplot")):
"""
Create a table of the Choi matrices and/or their eigenvalues of
a model's gates.
Parameters
----------
models : Model or list of Models
The Model(s) whose Choi info should be displayed. If multiple
Models are given, they should have the same operation labels.
titles : list of strings, optional
A list of titles corresponding to the models, used to
prefix the column(s) for that model. E.g. `"Target"`.
confidenceRegionInfo : ConfidenceRegion, optional
If not None, specifies a confidence-region
used to display eigenvalue error intervals for the
*final* Model in `models`.
display : tuple/list of {"matrices","eigenvalues","barplot","boxplot"}
Which columns to display: the Choi matrices (as numerical grids),
the Choi matrix eigenvalues (as a numerical list), the eigenvalues
on a bar plot, and/or the matrix as a plot of colored boxes.
Returns
-------
ReportTable
"""
super(ChoiTable, self).__init__(ws, self._create, models, titles,
confidenceRegionInfo, display)
def _create(self, models, titles, confidenceRegionInfo, display):
if isinstance(models, _objs.Model):
models = [models]
opLabels = models[0].get_primitive_op_labels() # use labels of 1st model
assert(isinstance(models[0], _objs.ExplicitOpModel)), "%s only works with explicit models" % str(type(self))
if titles is None:
titles = [''] * len(models)
qtysList = []
for model in models:
opLabels = model.get_primitive_op_labels() # operation labels
#qtys_to_compute = []
if 'matrix' in display or 'boxplot' in display:
choiMxs = [_ev(_reportables.Choi_matrix(model, gl)) for gl in opLabels]
else:
choiMxs = None
if 'eigenvalues' in display or 'barplot' in display:
evals = [_ev(_reportables.Choi_evals(model, gl), confidenceRegionInfo) for gl in opLabels]
else:
evals = None
qtysList.append((choiMxs, evals))
colHeadings = ['Gate']
for disp in display:
if disp == "matrix":
for model, title in zip(models, titles):
basisLongNm = _tools.basis_longname(model.basis)
pre = (title + ' ' if title else '')
colHeadings.append('%sChoi matrix (%s basis)' % (pre, basisLongNm))
elif disp == "eigenvalues":
for model, title in zip(models, titles):
pre = (title + ' ' if title else '')
colHeadings.append('%sEigenvalues' % pre)
elif disp == "barplot":
for model, title in zip(models, titles):
pre = (title + ' ' if title else '')
colHeadings.append('%sEigenvalue Magnitudes' % pre)
elif disp == "boxplot":
for model, title in zip(models, titles):
basisLongNm = _tools.basis_longname(model.basis)
pre = (title + ' ' if title else '')
colHeadings.append('%sChoi matrix (%s basis)' % (pre, basisLongNm))
else:
raise ValueError("Invalid element of `display`: %s" % disp)
formatters = [None] * len(colHeadings)
table = _ReportTable(colHeadings, formatters, confidenceRegionInfo=confidenceRegionInfo)
for i, gl in enumerate(opLabels):
#Note: currently, we don't use confidence region...
row_data = [gl]
row_formatters = [None]
for disp in display:
if disp == "matrix":
for model, (choiMxs, _) in zip(models, qtysList):
row_data.append(choiMxs[i])
row_formatters.append('Brackets')
elif disp == "eigenvalues":
for model, (_, evals) in zip(models, qtysList):
try:
evals[i] = evals[i].reshape(evals[i].size // 4, 4)
#assumes len(evals) is multiple of 4!
except: # if it isn't try 3 (qutrits)
evals[i] = evals[i].reshape(evals[i].size // 3, 3)
#assumes len(evals) is multiple of 3!
row_data.append(evals[i])
row_formatters.append('Normal')
elif disp == "barplot":
for model, (_, evals) in zip(models, qtysList):
evs, evsEB = evals[i].get_value_and_err_bar()
fig = _wp.ChoiEigenvalueBarPlot(self.ws, evs, evsEB)
row_data.append(fig)
row_formatters.append('Figure')
elif disp == "boxplot":
for model, (choiMxs, _) in zip(models, qtysList):
choiMx_real = choiMxs[i].hermitian_to_real()
choiMx, EB = choiMx_real.get_value_and_err_bar()
fig = _wp.GateMatrixPlot(self.ws, choiMx,
colorbar=False,
mxBasis=model.basis,
EBmatrix=EB)
row_data.append(fig)
row_formatters.append('Figure')
table.addrow(row_data, row_formatters)
table.finish()
return table
class GaugeRobustModelTable(WorkspaceTable):
""" Create a table showing a model in a gauge-robust representation. """
def __init__(self, ws, model, target_model, display_as="boxes",
confidenceRegionInfo=None):
"""
Create a table showing a gauge-invariant representation of a model.
Parameters
----------
model : Model
The Model to display.
target_model : Model
The (usually ideal) reference model to compute gauge-invariant
quantities with respect to.
display_as : {"numbers", "boxes"}, optional
How to display the operation matrices, as either numerical
grids (fine for small matrices) or as a plot of colored
boxes (space-conserving and better for large matrices).
confidenceRegionInfo : ConfidenceRegion, optional
If not None, specifies a confidence-region
used to display error intervals.
Returns
-------
ReportTable
"""
super(GaugeRobustModelTable, self).__init__(ws, self._create, model, target_model,
display_as, confidenceRegionInfo)
def _create(self, model, target_model, display_as, confidenceRegionInfo):
assert(isinstance(model, _objs.ExplicitOpModel)), "%s only works with explicit models" % str(type(self))
opLabels = model.get_primitive_op_labels() # use labels of 1st model
colHeadings = ['Gate', 'M - I'] + ['FinvF(%s) - I' % str(lbl) for lbl in opLabels]
formatters = [None] * len(colHeadings)
confidenceRegionInfo = None # Don't deal with CIs yet...
def get_gig_decomp(mx, tmx): # "Gauge invariant gateset" decomposition
G0, G = tmx, mx
#ev0, U0 = _tools.sorted_eig(G0)
#ev, U = _tools.sorted_eig(G)
#U0inv = _np.linalg.inv(U0)
#Uinv = _np.linalg.inv(U)
_, U, U0, ev0 = _tools.get_a_best_case_gauge_transform(G, G0, returnAll=True)
U0inv = _np.linalg.inv(U0)
Uinv = _np.linalg.inv(U)
kite = _tools.get_kite(ev0)
F = _tools.find_zero_communtant_connection(U, Uinv, U0, U0inv, kite) # Uinv * F * U0 is block diag
Finv = _np.linalg.inv(F)
# if G0 = U0 * E0 * U0inv then
# Uinv * F * G0 * Finv * U = D * E0 * Dinv = E0 b/c D is block diagonal w/E0's degenercies
# so F * G0 * Finv = U * E0 * Uinv = Gp ==> Finv * G * F = M * G0
M = _np.dot(Finv, _np.dot(G, _np.dot(F, _np.linalg.inv(G0))))
assert(_np.linalg.norm(M.imag) < 1e-8)
M0 = _np.dot(U0inv, _np.dot(M, U0)) # M in G0's eigenbasis
assert(_np.linalg.norm(_tools.project_onto_antikite(M0, kite)) < 1e-8) # should be block diagonal
assert(_np.allclose(G, _np.dot(F, _np.dot(M, _np.dot(G0, Finv))))) # this is desired decomp
assert(_np.linalg.norm(M.imag) < 1e-6 and _np.linalg.norm(F.imag) < 1e-6) # and everthing should be real
return F, M, Finv
table = _ReportTable(colHeadings, formatters, confidenceRegionInfo=confidenceRegionInfo)
I = _np.identity(model.dim, 'd')
M = 0.0 # max abs for colorscale
op_decomps = {}
for gl in opLabels:
try:
op_decomps[gl] = get_gig_decomp(model.operations[gl].todense(),
target_model.operations[gl].todense())
M = max(M, max(_np.abs((op_decomps[gl][1] - I).flat))) # update max
except Exception as e:
_warnings.warn("Failed gauge-robust decomposition of %s op:\n%s" % (gl, str(e)))
for i, lbl in enumerate(opLabels):
if lbl not in op_decomps: continue
for j, lbl2 in enumerate(opLabels):
if lbl2 not in op_decomps: continue
if i == j: continue
val = _np.dot(op_decomps[lbl][2], op_decomps[lbl2][0]) - I # value plotted below
M = max(M, max(_np.abs(val).flat)) # update max
#FUTURE: instruments too?
for i, lbl in enumerate(opLabels):
row_data = [lbl]
row_formatters = [None]
if lbl in op_decomps:
Fi, Mi, Finvi = op_decomps[lbl]
#Print "M" matrix
if display_as == "numbers":
row_data.append(Mi - I)
row_formatters.append('Brackets')
elif display_as == "boxes":
fig = _wp.GateMatrixPlot(self.ws, Mi - I, -M, M, colorbar=False)
row_data.append(fig)
row_formatters.append('Figure')
else:
raise ValueError("Invalid 'display_as' argument: %s" % display_as)
else:
row_data.append(_objs.reportableqty.ReportableQty(_np.nan))
row_formatters.append('Normal')
for j, lbl2 in enumerate(opLabels):
if i == j:
row_data.append("0")
row_formatters.append(None)
elif (lbl in op_decomps and lbl2 in op_decomps):
val = _np.dot(Finvi, op_decomps[lbl2][0])
#Print "Finv*F" matrix
if display_as == "numbers":
row_data.append(val - I)
row_formatters.append('Brackets')
elif display_as == "boxes":
fig = _wp.GateMatrixPlot(self.ws, val - I, -M, M, colorbar=False)
row_data.append(fig)
row_formatters.append('Figure')
else:
raise ValueError("Invalid 'display_as' argument: %s" % display_as)
else:
row_data.append(_objs.reportableqty.ReportableQty(_np.nan))
row_formatters.append('Normal')
table.addrow(row_data, row_formatters)
table.finish()
return table
class GaugeRobustMetricTable(WorkspaceTable):
""" Create a table showing a standard metric in a gauge-robust way. """
def __init__(self, ws, model, target_model, metric,
confidenceRegionInfo=None):
"""
Create a table showing a standard metric in a gauge-robust way.
Parameters
----------
model : Model
The Model to display.
target_model : Model
The (usually ideal) reference model to compute gauge-invariant
quantities with respect to.
metric : str
The abbreviation for the metric to use. Allowed values are:
- "inf" : entanglement infidelity
- "agi" : average gate infidelity
- "trace" : 1/2 trace distance
- "diamond" : 1/2 diamond norm distance
- "nuinf" : non-unitary entanglement infidelity
- "nuagi" : non-unitary entanglement infidelity
- "evinf" : eigenvalue entanglement infidelity
- "evagi" : eigenvalue average gate infidelity
- "evnuinf" : eigenvalue non-unitary entanglement infidelity
- "evnuagi" : eigenvalue non-unitary entanglement infidelity
- "evdiamond" : eigenvalue 1/2 diamond norm distance
- "evnudiamond" : eigenvalue non-unitary 1/2 diamond norm distance
- "frob" : frobenius distance
confidenceRegionInfo : ConfidenceRegion, optional
If not None, specifies a confidence-region
used to display error intervals.
Returns
-------
ReportTable
"""
super(GaugeRobustMetricTable, self).__init__(ws, self._create, model, target_model,
metric, confidenceRegionInfo)
def _create(self, model, target_model, metric, confidenceRegionInfo):
assert(isinstance(model, _objs.ExplicitOpModel)), "%s only works with explicit models" % str(type(self))
opLabels = model.get_primitive_op_labels()
colHeadings = [''] + ['%s' % str(lbl) for lbl in opLabels]
formatters = [None] * len(colHeadings)
confidenceRegionInfo = None # Don't deal with CIs yet...
# Table will essentially be a matrix whose diagonal elements are
# --> metric(GateA_in_As_best_gauge, TargetA)
# where a "best gauge" of a gate is one where it is co-diagonal with its target (same evecs can diag both).
# Off-diagonal elements are given by:
# --> min( metric(TargetA_in_Bs_best_gauge, TargetA), metric(TargetB_in_As_best_gauge, TargetB) )
#
# Thus, the diagonal elements tell us how much worse a (target) gate gets when just it's eigenvalues are
# replaced with those of the actual estimated gate, and the off-diagonal elements tell us the least amount of
# damage that must be done to a pair of (target) gates when just changing their eigenvectors to be consistent
# with the actual estimated gates.
table = _ReportTable(colHeadings, formatters, confidenceRegionInfo=confidenceRegionInfo)
orig_model = model.copy()
orig_model.set_all_parameterizations("full") # so we can freely gauge transform this
orig_target = target_model.copy()
orig_target.set_all_parameterizations("full") # so we can freely gauge transform this
mdl_in_best_gauge = []
target_mdl_in_best_gauge = []
for lbl in opLabels:
gate_mx = orig_model.operations[lbl].todense()
target_gate_mx = target_model.operations[lbl].todense()
Ugauge = _tools.get_a_best_case_gauge_transform(gate_mx, target_gate_mx)
Ugg = _objs.FullGaugeGroupElement(_np.linalg.inv(Ugauge)) # transforms gates as Ugauge * gate * Ugauge_inv
mdl = orig_model.copy()
mdl.transform(Ugg)
_, Ugg_addl, mdl = _gopt.gaugeopt_to_target(mdl, orig_target,
itemWeights={'spam': 0, 'gates': 1e-4, lbl: 1.0},
returnAll=True) # ADDITIONAL GOPT
mdl_in_best_gauge.append(mdl)
target_mdl = orig_target.copy()
target_mdl.transform(Ugg)
target_mdl.transform(Ugg_addl) # ADDITIONAL GOPT
target_mdl_in_best_gauge.append(target_mdl)
#FUTURE: instruments too?
for i, lbl in enumerate(opLabels):
row_data = [lbl]
row_formatters = [None]
for j, lbl2 in enumerate(opLabels):
if i > j: # leave lower diagonal blank
el = _objs.reportableqty.ReportableQty(_np.nan)
elif i == j: # diagonal element
try:
el = _reportables.evaluate_opfn_by_name(
metric, mdl_in_best_gauge[i], target_model, lbl, confidenceRegionInfo)
except Exception:
_warnings.warn("Error computing %s for %s op in gauge-robust metrics table!" % (metric, lbl))
el = _objs.reportableqty.ReportableQty(_np.nan)
else: # off-diagonal element
try:
el1 = _reportables.evaluate_opfn_by_name(
metric, target_mdl_in_best_gauge[i],
target_mdl_in_best_gauge[j], lbl2,
confidenceRegionInfo)
el2 = _reportables.evaluate_opfn_by_name(
metric, target_mdl_in_best_gauge[i], target_mdl_in_best_gauge[j], lbl, confidenceRegionInfo)
el = _objs.reportableqty.minimum(el1, el2)
except Exception:
_warnings.warn("Error computing %s for %s,%s ops in gauge-robust metrics table!" %
(metric, lbl, lbl2))
el = _objs.reportableqty.ReportableQty(_np.nan)
row_data.append(el)
row_formatters.append('Normal')
table.addrow(row_data, row_formatters)
table.finish()
return table
class ModelVsTargetTable(WorkspaceTable):
""" Table comparing a Model (as a whole) to a target """
def __init__(self, ws, model, targetModel, clifford_compilation, confidenceRegionInfo=None):
"""
Create a table comparing a model (as a whole) to a target model
using metrics that can be evaluatd for an entire model.
Parameters
----------
model, targetModel : Model
The models to compare
clifford_compilation : dict
A dictionary of operation sequences, one for each Clifford operation
in the Clifford group relevant to the model Hilbert space. If
None, then rows requiring a clifford compilation are omitted.
confidenceRegionInfo : ConfidenceRegion, optional
If not None, specifies a confidence-region
used to display error intervals.
Returns
-------
ReportTable
"""
super(ModelVsTargetTable, self).__init__(ws, self._create, model,
targetModel, clifford_compilation,
confidenceRegionInfo)
def _create(self, model, targetModel, clifford_compilation, confidenceRegionInfo):
colHeadings = ('Metric', "Value")
formatters = (None, None)
tooltips = colHeadings
table = _ReportTable(colHeadings, formatters, colHeadingLabels=tooltips,
confidenceRegionInfo=confidenceRegionInfo)
#Leave this off for now, as it's primary use is to compare with RB and the predicted RB number is better
#for this.
#pAGsI = _ev(_reportables.Average_gateset_infidelity(model, targetModel), confidenceRegionInfo)
#table.addrow(("Avg. primitive model infidelity", pAGsI), (None, 'Normal') )
pRBnum = _ev(_reportables.Predicted_rb_number(model, targetModel), confidenceRegionInfo)
table.addrow(("Predicted primitive RB number", pRBnum), (None, 'Normal'))
if clifford_compilation:
clifford_model = _cnst.build_explicit_alias_model(model, clifford_compilation)
clifford_targetModel = _cnst.build_explicit_alias_model(targetModel, clifford_compilation)
##For clifford versions we don't have a confidence region - so no error bars
#AGsI = _ev(_reportables.Average_gateset_infidelity(clifford_model, clifford_targetModel))
#table.addrow(("Avg. clifford model infidelity", AGsI), (None, 'Normal') )
RBnum = _ev(_reportables.Predicted_rb_number(clifford_model, clifford_targetModel))
table.addrow(("Predicted Clifford RB number", RBnum), (None, 'Normal'))
table.finish()
return table
class GatesVsTargetTable(WorkspaceTable):
""" Table comparing a Model's gates to those of a target model """
def __init__(self, ws, model, targetModel, confidenceRegionInfo=None,
display=('inf', 'agi', 'trace', 'diamond', 'nuinf', 'nuagi'),
virtual_ops=None, wildcard=None):
"""
Create a table comparing a model's gates to a target model using
metrics such as the infidelity, diamond-norm distance, and trace distance.
Parameters
----------
model, targetModel : Model
The models to compare
confidenceRegionInfo : ConfidenceRegion, optional
If not None, specifies a confidence-region
used to display error intervals.
display : tuple, optional
A tuple of one or more of the allowed options (see below) which
specify which columns are displayed in the table.
- "inf" : entanglement infidelity
- "agi" : average gate infidelity
- "trace" : 1/2 trace distance
- "diamond" : 1/2 diamond norm distance
- "nuinf" : non-unitary entanglement infidelity
- "nuagi" : non-unitary entanglement infidelity
- "evinf" : eigenvalue entanglement infidelity
- "evagi" : eigenvalue average gate infidelity
- "evnuinf" : eigenvalue non-unitary entanglement infidelity
- "evnuagi" : eigenvalue non-unitary entanglement infidelity
- "evdiamond" : eigenvalue 1/2 diamond norm distance
- "evnudiamond" : eigenvalue non-unitary 1/2 diamond norm distance
- "frob" : frobenius distance
- "unmodeled" : unmodeled "wildcard" budget
virtual_ops : list, optional
If not None, a list of `Circuit` objects specifying additional "gates"
(i.e. processes) to compute eigenvalues of. Length-1 operation sequences are
automatically discarded so they are not displayed twice.
wildcard: PrimitiveOpsWildcardBudget
A wildcard budget with a `get_op_budget` method that is used to
fill in the "unmodeled" error column when it is requested.
Returns
-------
ReportTable
"""
super(GatesVsTargetTable, self).__init__(ws, self._create, model,
targetModel, confidenceRegionInfo,
display, virtual_ops, wildcard)
def _create(self, model, targetModel, confidenceRegionInfo,
display, virtual_ops, wildcard):
opLabels = model.get_primitive_op_labels() # operation labels
instLabels = list(model.instruments.keys()) # requires an explicit model!
assert(isinstance(model, _objs.ExplicitOpModel)), "%s only works with explicit models" % str(type(self))
colHeadings = ['Gate'] if (virtual_ops is None) else ['Gate or Germ']
tooltips = ['Gate'] if (virtual_ops is None) else ['Gate or Germ']
for disp in display:
if disp == "unmodeled" and not wildcard: continue # skip wildcard column if there is no wilcard info
try:
heading, tooltip = _reportables.info_of_opfn_by_name(disp)
except ValueError:
raise ValueError("Invalid display column name: %s" % disp)
colHeadings.append(heading)
tooltips.append(tooltip)
formatters = (None,) + ('Conversion',) * (len(colHeadings) - 1)
table = _ReportTable(colHeadings, formatters, colHeadingLabels=tooltips,
confidenceRegionInfo=confidenceRegionInfo)
formatters = (None,) + ('Normal',) * (len(colHeadings) - 1)
if virtual_ops is None:
iterOver = opLabels
else:
iterOver = opLabels + tuple((v for v in virtual_ops if len(v) > 1))
for gl in iterOver:
#Note: gl may be a operation label (a string) or a Circuit
row_data = [str(gl)]
for disp in display:
if disp == "unmodeled": # a special case for now
if wildcard:
row_data.append(_objs.reportableqty.ReportableQty(
wildcard.get_op_budget(gl)))
continue # Note: don't append anything if 'not wildcard'
#import time as _time #DEBUG
#tStart = _time.time() #DEBUG
if targetModel is None:
qty = _objs.reportableqty.ReportableQty(_np.nan)
else:
qty = _reportables.evaluate_opfn_by_name(
disp, model, targetModel, gl, confidenceRegionInfo)
#tm = _time.time()-tStart #DEBUG
#if tm > 0.01: print("DB: Evaluated %s in %gs" % (disp, tm)) #DEBUG
row_data.append(qty)
table.addrow(row_data, formatters)
#Iterate over instruments
for il in instLabels:
row_data = [str(il)]
inst = model.instruments[il]
tinst = targetModel.instruments[il]
basis = model.basis
#Note: could move this to a reportables function in future for easier
# confidence region support - for now, no CI support:
for disp in display:
if disp == "unmodeled": # a special case for now
if wildcard:
row_data.append(_objs.reportableqty.ReportableQty(
wildcard.get_op_budget(il)))
continue # Note: don't append anything if 'not wildcard'
if disp == "inf":
sqrt_component_fidelities = [_np.sqrt(_reportables.entanglement_fidelity(inst[l], tinst[l], basis))
for l in inst.keys()]
qty = 1 - sum(sqrt_component_fidelities)**2
row_data.append(_objs.reportableqty.ReportableQty(qty))