/
workspacetables.py
3678 lines (2967 loc) · 154 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
from pygsti.report import plothelpers as _ph
from pygsti.report import reportables as _reportables
from pygsti.report import workspaceplots as _wp
from pygsti.report.reportables import evaluate as _ev
from pygsti.report.table import ReportTable as _ReportTable
from pygsti.report.workspace import WorkspaceTable
from pygsti.report.reportableqty import ReportableQty as _ReportableQty, minimum as _rqty_minimum
from pygsti import circuits as _circuits
from pygsti import models as _models
from pygsti import baseobjs as _baseobjs
from pygsti import tools as _tools
from pygsti.algorithms import gaugeopt as _gopt
from pygsti.modelmembers import operations as _op
from pygsti.modelmembers import povms as _povm
from pygsti.modelmembers import states as _state
from pygsti.objectivefns import objectivefns as _objfns
from pygsti.circuits.circuit import Circuit as _Circuit
from pygsti.baseobjs.errorgenlabel import LocalElementaryErrorgenLabel as _LEEL
class BlankTable(WorkspaceTable):
"""
A completely blank placeholder table.
Parameters
----------
ws : Workspace
The containing (parent) workspace.
"""
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.
Parameters
----------
ws : Workspace
The containing (parent) workspace.
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).
confidence_region_info : ConfidenceRegion, optional
If not None, specifies a confidence-region
used to display error intervals.
include_hs_vec : boolean, optional
Whether or not to include Hilbert-Schmidt
vector representation columns in the table.
"""
def __init__(self, ws, models, titles=None,
display_as="boxes", confidence_region_info=None,
include_hs_vec=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).
confidence_region_info : ConfidenceRegion, optional
If not None, specifies a confidence-region
used to display error intervals.
include_hs_vec : 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, confidence_region_info,
include_hs_vec)
def _create(self, models, titles, display_as, confidence_region_info,
include_hs_vec):
if isinstance(models, _models.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 include_hs_vec:
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 confidence_region_info is not None:
colHeadings.append('%g%% C.I. half-width' % confidence_region_info.level)
formatters.append('Conversion')
table = _ReportTable(colHeadings, formatters, confidence_region_info=confidence_region_info)
for lbl in rhoLabels:
rowData = [lbl]; rowFormatters = ['Rho']
for model in models:
rhoMx = _ev(_reportables.Vec_as_stdmx(model, lbl, "prep"))
# confidence_region_info) #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.value
fig = _wp.GateMatrixPlot(self.ws, v, colorbar=False,
box_labels=True, prec='compacthp',
mx_basis=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 = confidence_region_info if confidence_region_info and \
(confidence_region_info.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 include_hs_vec:
rowData.append(models[-1].preps[lbl])
rowFormatters.append('Normal')
if confidence_region_info is not None:
intervalVec = confidence_region_info.retrieve_profile_likelihood_confidence_intervals(lbl)[:, None]
if intervalVec.shape[0] == models[-1].dim - 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.add_row(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"))
#confidence_region_info) #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.value
fig = _wp.GateMatrixPlot(self.ws, v, colorbar=False,
box_labels=True, prec='compacthp',
mx_basis=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 = confidence_region_info if confidence_region_info and \
(confidence_region_info.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 include_hs_vec:
rowData.append(models[-1].povms[povmlbl][lbl])
rowFormatters.append('Normal')
if confidence_region_info is not None:
intervalVec = confidence_region_info.retrieve_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.add_row(rowData, rowFormatters)
table.finish()
return table
class SpamParametersTable(WorkspaceTable):
"""
A table for "SPAM parameters" (dot products of SPAM vectors)
Parameters
----------
ws : Workspace
The containing (parent) workspace.
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"`.
confidence_region_info : ConfidenceRegion, optional
If not None, specifies a confidence-region
used to display error intervals.
"""
def __init__(self, ws, models, titles=None, confidence_region_info=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"`.
confidence_region_info : 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, confidence_region_info)
def _create(self, models, titles, confidence_region_info):
if isinstance(models, _models.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, confidence_region_info=confidence_region_info)
for gstitle, model in zip(titles, models):
cri = confidence_region_info if (confidence_region_info
and confidence_region_info.model.frobeniusdist(model) < 1e-6) else None
spamDotProdsQty = _ev(_reportables.Spam_dotprods(model), cri)
DPs, DPEBs = spamDotProdsQty.value_and_errorbar
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.add_row(rowData, formatters)
table.finish()
return table
class GatesTable(WorkspaceTable):
"""
Create a table showing a model's raw gates.
Parameters
----------
ws : Workspace
The containing (parent) workspace.
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).
confidence_region_info : ConfidenceRegion, optional
If not None, specifies a confidence-region
used to display error intervals for the *final*
element of `models`.
"""
def __init__(self, ws, models, titles=None, display_as="boxes",
confidence_region_info=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).
confidence_region_info : 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, confidence_region_info)
def _create(self, models, titles, display_as, confidence_region_info):
if isinstance(models, _models.Model):
models = [models]
opLabels = models[0].primitive_op_labels # use labels of 1st model
instLabels = list(models[0].instruments.keys()) # requires an explicit model!
assert(isinstance(models[0], _models.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 confidence_region_info is not None:
#Only use confidence region for the *final* model.
colHeadings.append('%g%% C.I. half-width' % confidence_region_info.level)
formatters.append('Conversion')
table = _ReportTable(colHeadings, formatters, confidence_region_info=confidence_region_info)
#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, None, 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, comp_lbl, per_model_ops in label_op_tups:
row_data = [lbl if (comp_lbl is None) else (lbl + '.' + comp_lbl)]
row_formatters = [None]
for model, op in zip(models, per_model_ops):
basis = model.basis
if display_as == "numbers":
row_data.append(op.to_dense('HilbertSchmidt'))
row_formatters.append('Brackets')
elif display_as == "boxes":
fig = _wp.GateMatrixPlot(self.ws, op.to_dense(on_space='HilbertSchmidt'),
colorbar=False,
mx_basis=basis)
row_data.append(fig)
row_formatters.append('Figure')
else:
raise ValueError("Invalid 'display_as' argument: %s" % display_as)
if confidence_region_info is not None:
intervalVec = confidence_region_info.retrieve_profile_likelihood_confidence_intervals(
lbl, comp_lbl)[:, None]
if isinstance(per_model_ops[-1], _op.FullArbitraryOp):
#then we know how to reshape into a matrix
op_dim = models[-1].dim
basis = models[-1].basis
intervalMx = intervalVec.reshape(op_dim, op_dim)
elif isinstance(per_model_ops[-1], _op.FullTPOp):
#then we know how to reshape into a matrix
op_dim = models[-1].dim
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].dim
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,
color_min=-maxAbsVal, color_max=maxAbsVal,
colorbar=False,
mx_basis=basis)
row_data.append(fig)
row_formatters.append('Figure')
else:
assert(False) # pragma: no cover
table.add_row(row_data, row_formatters)
table.finish()
return table
class ChoiTable(WorkspaceTable):
"""
A table of the Choi representations of a Model's gates
Parameters
----------
ws : Workspace
The containing (parent) workspace.
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"`.
confidence_region_info : 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.
"""
def __init__(self, ws, models, titles=None,
confidence_region_info=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"`.
confidence_region_info : 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,
confidence_region_info, display)
def _create(self, models, titles, confidence_region_info, display):
if isinstance(models, _models.Model):
models = [models]
opLabels = models[0].primitive_op_labels # use labels of 1st model
assert(isinstance(models[0], _models.ExplicitOpModel)), "%s only works with explicit models" % str(type(self))
if titles is None:
titles = [''] * len(models)
qtysList = []
for model in models:
opLabels = model.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), confidence_region_info) 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, confidence_region_info=confidence_region_info)
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].value_and_errorbar
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.value_and_errorbar
fig = _wp.GateMatrixPlot(self.ws, choiMx,
colorbar=False,
mx_basis=model.basis,
eb_matrix=EB)
row_data.append(fig)
row_formatters.append('Figure')
table.add_row(row_data, row_formatters)
table.finish()
return table
class GaugeRobustModelTable(WorkspaceTable):
"""
Create a table showing a model in a gauge-robust representation.
Parameters
----------
ws : Workspace
The containing (parent) workspace.
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).
confidence_region_info : ConfidenceRegion, optional
If not None, specifies a confidence-region
used to display error intervals.
"""
def __init__(self, ws, model, target_model, display_as="boxes",
confidence_region_info=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).
confidence_region_info : 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, confidence_region_info)
def _create(self, model, target_model, display_as, confidence_region_info):
assert(isinstance(model, _models.ExplicitOpModel)), "%s only works with explicit models" % str(type(self))
opLabels = model.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)
confidence_region_info = 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.compute_best_case_gauge_transform(G, G0, return_all=True)
U0inv = _np.linalg.inv(U0)
Uinv = _np.linalg.inv(U)
kite = _tools.compute_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, confidence_region_info=confidence_region_info)
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].to_dense(on_space='HilbertSchmidt'),
target_model.operations[gl].to_dense(on_space='HilbertSchmidt'))
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(_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(_ReportableQty(_np.nan))
row_formatters.append('Normal')
table.add_row(row_data, row_formatters)
table.finish()
return table
class GaugeRobustMetricTable(WorkspaceTable):
"""
Create a table showing a standard metric in a gauge-robust way.
Parameters
----------
ws : Workspace
The containing (parent) workspace.
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
confidence_region_info : ConfidenceRegion, optional
If not None, specifies a confidence-region
used to display error intervals.
"""
def __init__(self, ws, model, target_model, metric,
confidence_region_info=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
confidence_region_info : 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, confidence_region_info)
def _create(self, model, target_model, metric, confidence_region_info):
assert(isinstance(model, _models.ExplicitOpModel)), "%s only works with explicit models" % str(type(self))
opLabels = model.primitive_op_labels
colHeadings = [''] + ['%s' % str(lbl) for lbl in opLabels]
formatters = [None] * len(colHeadings)
confidence_region_info = 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, confidence_region_info=confidence_region_info)
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
# ** A first attempt at fixing the gauge optimization issues. ** -- "frobeniustt" should replace this.
#if metric in ("inf", "agi", "nuinf", "nuagi", "evinf", "evagi", "evnuinf", "evnuagi"):
# gmetric = "fidelity"
#elif metric in ("trace", "diamond", "evdiamond", "evnudiamond"):
# gmetric = "tracedist"
#else:
# gmetric = "frobenius"
gmetric = "frobeniustt"
mdl_in_best_gauge = []
target_mdl_in_best_gauge = []
for lbl in opLabels:
gate_mx = orig_model.operations[lbl].to_dense(on_space='HilbertSchmidt')
target_gate_mx = target_model.operations[lbl].to_dense(on_space='HilbertSchmidt')
Ugauge = _tools.compute_best_case_gauge_transform(gate_mx, target_gate_mx)
Ugg = _models.gaugegroup.FullGaugeGroupElement(_np.linalg.inv(Ugauge))
# transforms gates as Ugauge * gate * Ugauge_inv
mdl = orig_model.copy()
mdl.transform_inplace(Ugg)
#DEBUG statements for trying to figure out why we get negative off-diagonals so often.
#print("----- ",lbl,"--------")
#print("PT1:\n",mdl.strdiff(target_model))
#print("PT1b:\n",mdl.strdiff(target_model, 'inf'))
try:
_, Ugg_addl, mdl = _gopt.gaugeopt_to_target(mdl, orig_target, gates_metric=gmetric, spam_metric=gmetric,
item_weights={'spam': 0, 'gates': 1e-4, lbl: 1.0},
return_all=True, tol=1e-5, maxiter=100) # ADDITIONAL GOPT
except Exception as e:
_warnings.warn(("GaugeRobustMetricTable gauge opt failed for %s label - "
"falling back to frobenius metric! Error was:\n%s") % (lbl, str(e)))
_, Ugg_addl, mdl = _gopt.gaugeopt_to_target(mdl, orig_target, gates_metric="frobenius",
spam_metric="frobenius",
item_weights={'spam': 0, 'gates': 1e-4, lbl: 1.0},
return_all=True, tol=1e-5, maxiter=100) # ADDITIONAL GOPT
#print("PT2:\n",mdl.strdiff(target_model))
#print("PT2b:\n",mdl.strdiff(target_model, 'inf'))
mdl_in_best_gauge.append(mdl)
target_mdl = orig_target.copy()
target_mdl.transform_inplace(Ugg)
target_mdl.transform_inplace(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 = _ReportableQty(_np.nan)
elif i == j: # diagonal element
try:
el = _reportables.evaluate_opfn_by_name(
metric, mdl_in_best_gauge[i], target_model, lbl, confidence_region_info)
except Exception:
_warnings.warn("Error computing %s for %s op in gauge-robust metrics table!" % (metric, lbl))
el = _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,
confidence_region_info)
el2 = _reportables.evaluate_opfn_by_name(
metric, target_mdl_in_best_gauge[i], target_mdl_in_best_gauge[j], lbl,
confidence_region_info)
el = _rqty_minimum(el1, el2)
except Exception:
_warnings.warn("Error computing %s for %s,%s ops in gauge-robust metrics table!" %
(metric, lbl, lbl2))
el = _ReportableQty(_np.nan)
row_data.append(el)
row_formatters.append('Normal')
table.add_row(row_data, row_formatters)
table.finish()
return table