/
core.py
3171 lines (2547 loc) · 147 KB
/
core.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
#*****************************************************************
# pyGSTi 0.9: Copyright 2015 Sandia Corporation
# This Software is released under the GPL license detailed
# in the file "license.txt" in the top-level pyGSTi directory
#*****************************************************************
""" Core GST algorithms """
import sys as _sys
import numpy as _np
import scipy.optimize as _spo
import scipy.stats as _stats
import warnings as _warnings
from .. import optimize as _opt
from .. import tools as _tools
from .. import objects as _objs
#Note on where 4x4 or possibly other integral-qubit dimensions are needed:
# 1) Need to use Jamiol. Isomorphism to contract to CPTP or even gauge optimize to CPTP
# since we need to know a Choi matrix basis to perform the Jamiol. isomorphism
# 2) Need pauilVector <=> matrix in contractToValidSpam
# 3) use Jamiol. Iso in print_gateset_info(...)
###################################################################################
# Linear Inversion GST (LGST)
###################################################################################
def do_lgst(dataset, specs, targetGateset=None, gateLabels=None, gateLabelAliases={},
spamDict=None, guessGatesetForGauge=None, svdTruncateTo=0, identityVec=None, verbosity=0):
"""
Performs Linear-inversion Gate Set Tomography on the dataset.
Parameters
----------
dataset : DataSet
The data used to generate the LGST estimates
specs : 2-tuple
A (rhoSpecs,ESpecs) tuple usually generated by calling build_spam_specs(...)
targetGateset : GateSet, optional
A gateset used to specify which gate labels should be estimated, a guess
for the in which gauge these estimates should be returned, and the SPAM
labels used to connect the dataset values to rhoVec and EVec indices.
gateLabels : list, optional
A list of which gate labels (or aliases) should be estimated.
Defaults to the gate labels in targetGateset.
e.g. ['Gi','Gx','Gy','Gx2']
gateLabelAliases : dictionary, optional
Dictionary whose keys are gate label "aliases" and whose values are tuples
corresponding to what that gate label should be expanded into before querying
the dataset.
Defaults to the empty dictionary (no aliases defined)
e.g. gateLabelAliases['Gx^3'] = ('Gx','Gx','Gx')
spamDict : dictionary, optional
Dictionary mapping (rhoVec_index,EVec_index) integer tuples to string spam labels.
Defaults to the spam dictionary of targetGateset
e.g. spamDict[(0,0)] == "plus"
guessGatesetForGauge : GateSet, optional
A gateset used to compute a gauge transformation that is applied to
the LGST estimates before they are returned. This gauge transformation
is computed such that if the estimated gates matched the gateset given,
then the gate matrices would match, i.e. the gauge would be the same as
the gateset supplied.
Defaults to targetGateset.
svdTruncateTo : int, optional
The Hilbert space dimension to truncate the gate matrices to using
a SVD to keep only the largest svdToTruncateTo singular values of
the I_tildle LGST matrix.
Defaults to 0 (no truncation)
identityVec : numpy array, optional
The vectorized identity density matrix in whatever basis is being
used. Size should be [ dmDim^2, 1], e.g. numpy.array([[1.41],[0],[0],[0]]).
Defaults to that of the targetGateset.
verbosity : int, optional
How much detail to send to stdout.
Returns
-------
Gateset
A gateset containing all of the estimated labels (or aliases)
"""
#Notes:
# We compute,
# I_tilde = AB (trunc,trunc), where trunc <= K = min(nRhoSpecs,nESpecs)
# X_tilde = AXB (trunc,trunc)
# and A, B for *target* gateset. (but target gateset may need dimension increase to get to trunc... and then A,B are rank deficient)
# We would like to get X or it's gauge equivalent.
# We do: 1) (I^-1)*AXB ~= B^-1 X B := Xhat -- we solve Ii*A*B = identity for Ii
# 2) B * Xhat * B^-1 ==> X (but what if B is non-invertible -- say rectangular) Want B*(something) ~ identity ??
# for lower rank target gatesets, want a gauge tranformation that brings Xhat => X of "increased dim" gateset
# want "B^-1" such that B(gsDim,nRhoSpecs) "B^-1"(nRhoSpecs,gsDim) ~ Identity(gsDim)
# Ub,sb,Vb = svd(B) so B = Ub*diag(sb)*Vb where Ub = (gsDim,M), s = (M,M), Vb = (M,rhoSpecs)
# if B^-1 := VbT*sb^-1*Ub^-1 then B*B^-1 = I(gsDim)
# similarly, can get want "A^-1" such that "A^-1"(gsDim,nESpecs) A(nESpecs,gsDim) ~ Identity(gsDim)
# or do we want not Ii*A*B = I but B*Ii*A = I(gsDim), so something like Ii = (B^-1)(A^-1) using pseudoinversese above.
# (but we can't do this, since we only have AB, not A and B separately)
# A is (trunc, gsDim)
# B is (gsDim, trunc)
# With no svd truncation (but we always truncate; this is just for reference)
# AXB = (nESpecs, nRhoSpecs)
# I (=AB) = (nESpecs, nRhoSpecs)
# A = (nESpecs, gsDim)
# B = (gsDim, nRhoSpecs)
#Process input parameters
rhoSpecs, ESpecs = specs
K = min(len(rhoSpecs), len(ESpecs))
if gateLabels is not None:
gateLabelsToEstimate = gateLabels
elif targetGateset is not None:
gateLabelsToEstimate = targetGateset.keys()
else: raise ValueError("do_lgst cannot determine gate labels to estimate from supplied parameters")
if spamDict is None:
if targetGateset is not None:
spamDict = targetGateset.get_spam_label_dict()
else: raise ValueError("do_lgst cannot determine SPAM dictionary from supplied parameters")
if guessGatesetForGauge is None:
guessGatesetForGauge = targetGateset # (which may also be None)
if identityVec is None and guessGatesetForGauge is not None:
identityVec = guessGatesetForGauge.identityVec
if identityVec is None: #check again in case targetGateset.identityVec == None
for (ir,ie) in spamDict.keys():
if ie == -1 and ir != -1: #then identityVec is required b/c this spamlabel represents Evec = identityVec - sum(other_Evecs)
raise ValueError("do_lgst cannot determine the identity vector from supplied parameters")
#otherwise identityVec is not required, so OK if it's None
#OLD
#if guessGatesetForGauge is not None: # apply svdTruncation necessary for gauge transformation if guessGatesetForGauge is given
# truncNeeded = len(guessGatesetForGauge.rhoVecs[0])
# if svdTruncateTo > 0 and svdTruncateTo != truncNeeded:
# raise ValueError("svdTruncateTo == %d is not equal to the gateset dimension (%d) used to guess the LGST gauge" % (svdTruncateTo,truncNeeded))
# svdTruncateTo = truncNeeded
#assert(len(ESpecs) == len(rhoSpecs)) #specify the same number of rho's and E's (for now)
lgstGateset = _objs.GateSet()
#Create truncation projector -- just trims columns (Pj) or rows (Pjt) of a matrix.
# note K = min(nRhoSpecs,nESpecs), and dot(Pjt,Pj) == identity(trunc)
trunc = svdTruncateTo if svdTruncateTo > 0 else K
assert(trunc <= K)
Pj = _np.zeros( (K,trunc), 'd') # shape = (K, trunc) projector with only trunc columns
for i in range(trunc): Pj[i,i] = 1.0
Pjt = _np.transpose(Pj) # shape = (trunc, K)
ABMat = _constructAB(rhoSpecs, ESpecs, spamDict, dataset) # shape = (nESpecs, nRhoSpecs)
U,s,V = _np.linalg.svd(ABMat, full_matrices=False)
if verbosity > 2: print "LGST: Singular values of I_tilde (truncating to first %d of %d) = \n" % (trunc,len(s)) ,s
Ud,Vd = _np.transpose(_np.conjugate(U)), _np.transpose(_np.conjugate(V)) # Udagger, Vdagger
ABMat_p = _np.dot(Pjt, _np.dot(_np.diag(s), Pj)) #truncate ABMat => ABMat' (note diag(s) = Ud*ABMat*Vd), shape = (trunc, trunc)
# U shape = (nESpecs, K)
# V shape = (K, nRhoSpecs)
# Ud shape = (K, nESpecs)
# Vd shape = (nRhoSpecs, K)
#print "DEBUG: dataset = ",dataset
#print "DEBUG: ABmat = \n",ABMat
#print "DEBUG: Evals(ABmat) = \n",_np.linalg.eigvals(ABMat)
rankAB = _np.linalg.matrix_rank(ABMat_p)
if rankAB < ABMat_p.shape[0]:
raise ValueError("LGST AB matrix is rank %d < %d. Choose better rhoSpecs and/or ESpecs, or decrease svdTruncateTo" \
% (rankAB, ABMat_p.shape[0]))
invABMat_p = _np.dot(Pjt, _np.dot(_np.diag(1.0/s), Pj)) # (trunc,trunc)
assert( _np.linalg.norm( _np.linalg.inv(ABMat_p) - invABMat_p ) < 1e-8 ) #check inverse is correct (TODO: comment out later)
assert( len( (_np.isnan(invABMat_p)).nonzero()[0] ) == 0 )
for gateLabel in gateLabelsToEstimate:
gateLabelTuple = gateLabelAliases.get(gateLabel, (gateLabel,))
X = _constructXMatrix(rhoSpecs, ESpecs, spamDict, gateLabelTuple, dataset) # shape (nESpecs, nRhoSpecs)
X2 = _np.dot(Ud, _np.dot(X, Vd)) # shape (K,K) this should be close to rank "svdTruncateTo" (which is <= K) -- TODO: check this
if svdTruncateTo > 0 and verbosity > 4:
print "LGST DEBUG: %s before trunc to first %d row and cols = \n" % (gateLabel,svdTruncateTo)
_tools.print_mx(X2)
X_p = _np.dot(Pjt, _np.dot(X2, Pj)) #truncate X => X', shape (trunc, trunc)
lgstGateset.set_gate(gateLabel, _objs.FullyParameterizedGate(_np.dot(invABMat_p,X_p))) # shape (trunc,trunc)
#print "DEBUG: X(%s) = \n" % gateLabel,X
#print "DEBUG: Evals(X) = \n",_np.linalg.eigvals(X)
#print "DEBUG: %s = \n" % gateLabel,lgstGateset[ gateLabel ]
# Form EVecs
nEVecs = max( [ b for (a,b) in spamDict.keys() ] ) + 1
for iEVec in range(nEVecs):
EVec = _np.zeros( (1,len(rhoSpecs)) ) # shape (1,nRhoSpecs)
for i,rhospec in enumerate(rhoSpecs):
gateString = rhospec.str; spamLabel = spamDict[ (rhospec.i,iEVec) ]
dsRow = dataset[ gateString ]
EVec[0,i] = dsRow.fraction(spamLabel)
EVec_p = _np.dot( _np.dot(EVec, Vd), Pj ) #truncate Evec => Evec', shape (1,trunc)
lgstGateset.set_evec( _np.transpose(EVec_p), iEVec )
# Form rhoVecs
nrhoVecs = max( [ a for (a,b) in spamDict.keys() ] ) + 1
for irhoVec in range(nrhoVecs):
rhoVec = _np.zeros((len(ESpecs),1)) # shape (nESpecs,1)
for i,espec in enumerate(ESpecs):
gateString = espec.str; spamLabel = spamDict[ (irhoVec, espec.i) ]
dsRow = dataset[ gateString ]
rhoVec[i] = dsRow.fraction(spamLabel)
rhoVec_p = _np.dot( Pjt, _np.dot(Ud, rhoVec) ) #truncate rhoVec => rhoVec', shape (trunc, 1)
rhoVec_p = _np.dot(invABMat_p,rhoVec_p)
lgstGateset.set_rhovec( rhoVec_p, irhoVec )
# Add identity vector to gateset (needed before adding spam labels)
# Pad with zeros if needed (ROBIN - is this correct?)
if identityVec is not None:
Idim = identityVec.shape[0]
assert(Idim <= trunc)
if Idim < trunc:
padded_identityVec = _np.concatenate( (identityVec, _np.zeros( (trunc-Idim,1), 'd')) )
else:
padded_identityVec = identityVec
lgstGateset.set_identity_vec( padded_identityVec )
# Add SPAM label info to gateset
for (rhoIndex, EIndex) in spamDict.keys():
lgstGateset.add_spam_label( rhoIndex, EIndex, spamDict[ (rhoIndex,EIndex) ] )
# Perform "guess" gauge transformation by computing the "B" matrix
# assuming rhos, Es, and gates are those of a guesstimate of the gateset
if guessGatesetForGauge is not None:
guessTrunc = len(guessGatesetForGauge.rhoVecs[0]) # dimension of guess gateset == the truncation to apply to it's B matrix
assert(guessTrunc <= trunc) # the dimension of the gateset for gauge guessing cannot exceed the dimension of the gateset being estimated
guessPj = _np.zeros( (K,guessTrunc), 'd') # shape = (K, guessTrunc) projector with only trunc columns
for i in range(guessTrunc): guessPj[i,i] = 1.0
guessPjt = _np.transpose(guessPj) # shape = (guessTrunc, K)
AMat = _constructA(ESpecs, guessGatesetForGauge) # shape = (nESpecs, gsDim)
AMat_p = _np.dot( guessPjt, _np.dot(Ud, AMat)) #truncate Evec => Evec', shape (guessTrunc,gsDim) (square!)
BMat = _constructB(rhoSpecs, guessGatesetForGauge) # shape = (gsDim, nRhoSpecs)
BMat_p = _np.dot( _np.dot(BMat, Vd), guessPj ) #truncate Evec => Evec', shape (gsDim,guessTrunc) (square!)
if verbosity > 3:
guess_ABMat = _np.dot(AMat,BMat)
guess_U,guess_s,guess_V = _np.linalg.svd(guess_ABMat, full_matrices=False)
print "LGST: Singular values of target I_tilde (truncating to first %d of %d) = \n" % (guessTrunc,len(guess_s)) ,guess_s
if guessTrunc < trunc: # if the dimension of the gauge-guess gateset is smaller than the matrices being estimated, pad B with identity
if verbosity > 2:
print "LGST: Padding target B with sqrt of low singular values of I_tilde: \n", s[guessTrunc:trunc]
BMat_p_padded = _np.identity(trunc, 'd')
BMat_p_padded[0:guessTrunc, 0:guessTrunc] = BMat_p
for i in range(guessTrunc,trunc):
BMat_p_padded[i,i] = _np.sqrt( s[i] ) #set diagonal as sqrt of actual AB matrix's singular values
lgstGateset.transform( S=_np.linalg.inv(BMat_p_padded), Si=BMat_p_padded )
else:
lgstGateset.transform( S=_np.linalg.inv(BMat_p), Si=BMat_p )
# RESET identity vector after lgstGateset.transform since this transforms gateset back to what we think is
# close to the basis of guessGatesetForGauge. The only reason we set it earlier is as a placeholder
# so that lgstGateset.add_spam_label doesn't fail.
lgstGateset.set_identity_vec( padded_identityVec )
# Force lgstGateset to have gates parameterized in the same was as those in guessGatesetForGauge
for gateLabel in gateLabelsToEstimate:
if gateLabel in guessGatesetForGauge:
new_gate = guessGatesetForGauge.get_gate(gateLabel).copy()
_objs.gate.optimize_gate( new_gate, lgstGateset.get_gate(gateLabel), bG0=True )
lgstGateset.set_gate( gateLabel, new_gate )
#inv_BMat_p = _np.dot(invABMat_p, AMat_p) # should be equal to inv(BMat_p) when trunc == gsDim ?? check??
#lgstGateset.transform( S=_np.dot(invABMat_p, AMat_p), Si=BMat_p ) # lgstGateset had dim trunc, so after transform is has dim gsDim
lgstGateset.log("Created by LGST", {'rhoSpecs': rhoSpecs, 'ESpecs': ESpecs })
if verbosity > 2: print ""
if verbosity > 1: print "--- LGST ---"
if verbosity > 4:
print "Resulting gate set:\n", lgstGateset
return lgstGateset
def _constructAB(rhoSpecs, ESpecs, spamDict, dataset):
AB = _np.empty( (len(ESpecs),len(rhoSpecs)) )
for i,espec in enumerate(ESpecs):
for j,rhospec in enumerate(rhoSpecs):
gateLabelString = rhospec.str + espec.str # LEXICOGRAPHICAL VS MATRIX ORDER
spamLabel = spamDict[ (rhospec.i,espec.i) ]
dsRow = dataset[gateLabelString]
AB[i,j] = dsRow.fraction(spamLabel)
#print "DEBUG: AB[%d,%d] = (" % (i,j), espec + rhospec, ") = ", AB[i,j] #DEBUG
return AB
def _constructXMatrix(rhoSpecs, ESpecs, spamDict, gateLabelTuple, dataset):
X = _np.empty( (len(ESpecs),len(rhoSpecs)) )
for i,espec in enumerate(ESpecs):
for j,rhospec in enumerate(rhoSpecs):
gateLabelString = rhospec.str + _objs.GateString(gateLabelTuple) + espec.str # LEXICOGRAPHICAL VS MATRIX ORDER
spamLabel = spamDict[ (rhospec.i,espec.i) ]
try:
dsRow = dataset[gateLabelString]
except:
raise KeyError("Missing data needed to construct X matrix for " + str(gateLabelTuple) \
+ ": gate string " + str(gateLabelString))
X[i,j] = dsRow.fraction(spamLabel)
return X
def _constructA(ESpecs, gs):
n = len(ESpecs); dim = gs.get_dimension()
A = _np.empty( (n,dim) )
for k,espec in enumerate(ESpecs):
#Build fiducial < E_k | := < EVec[ ESpec[0] ] | Gatestring(ESpec[1:])
st = _np.dot( _np.transpose( gs.EVecs[ espec.i ] ), gs.product(espec.str) ) # 1xN vector
A[k,:] = st[0,:] # E_k == kth row of A
return A
def _constructB(rhoSpecs, gs):
n = len(rhoSpecs); dim = gs.get_dimension()
B = _np.empty( (dim,n) )
for k,rhospec in enumerate(rhoSpecs):
#Build fiducial | rho_k > := Gatestring(rhoSpec[0:-1]) | rhoVec[ rhoSpec[-1] ] >
st = _np.dot( gs.product(rhospec.str), gs.rhoVecs[ rhospec.i ] ) # Nx1 vector
B[:,k] = st[:,0] # rho_k == kth column of B
return B
def gram_rank_and_evals(dataset, specs, targetGateset=None, spamDict=None):
"""
Returns the rank and eigenvalues of the Gram matrix for a dataset.
Parameters
----------
dataset : DataSet
The data used to populate the Gram matrix
specs : 2-tuple
A (rhoSpecs,ESpecs) tuple usually generated by calling build_spam_specs(...)
targetGateset : GateSet, optional
A gateset used to specify the SPAM labels used to connect
the dataset values to rhoVec and EVec indices.
spamDict : dictionary, optional
Dictionary mapping (rhoVec_index,EVec_index) integer tuples to string spam labels.
Defaults to the spam dictionary of targetGateset
e.g. spamDict[(0,0)] == "plus"
Returns
-------
rank : int
the rank of the Gram matrix
eigenvalues : numpy array
the eigenvalues of the Gram matrix
"""
rhoSpecs, ESpecs = specs
if spamDict is None:
if targetGateset is not None:
spamDict = targetGateset.get_spam_label_dict()
else: raise ValueError("do_lgst cannot determine SPAM dictionary from supplied parameters")
ABMat = _constructAB(rhoSpecs, ESpecs, spamDict, dataset)
U,s,V = _np.linalg.svd(ABMat)
return _np.linalg.matrix_rank(ABMat), s #_np.linalg.eigvals(ABMat)
###################################################################################
# Extended Linear GST (ExLGST)
##################################################################################
#Given dataset D
# Chi2 statistic = sum_k (p_k-f_k)^2/ (N f_kt(1-f_kt) ) where f_kt ~ f_k with +1/+2 to avoid zero denom
def do_exlgst(dataset, startGateset, gateStringsToUseInEstimation, specs,
targetGateset=None, spamDict=None, guessGatesetForGauge=None,
svdTruncateTo=0, maxiter=100000, maxfev=None, tol=1e-6,
opt_gates=True, opt_G0=True, regularizeFactor=0, verbosity=0,
check_jacobian=False):
"""
Performs Extended Linear-inversion Gate Set Tomography on the dataset.
Parameters
----------
dataset : DataSet
The data used to generate Extended-LGST estimates
startGateset : GateSet
The GateSet used as a starting point for the least-squares
optimization.
gateStringsToUseInEstimation : list of (tuples or GateStrings)
Each element of this list specifies a gate string that is
estimated using LGST and used in the overall least-squares
fit that determines the final "extended LGST" gateset.
e.g. [ (), ('Gx',), ('Gx','Gy') ]
specs : 2-tuple
A (rhoSpecs,ESpecs) tuple usually generated by calling build_spam_specs(...)
targetGateset : GateSet, optional
A gateset used to provide a guess for gauge in which LGST estimates should be returned,
and the SPAM labels used to connect the dataset values to rhoVec and EVec indices.
spamDict : dictionary, optional
Dictionary mapping (rhoVec_index,EVec_index) integer tuples to string spam labels.
Defaults to the spam dictionary of targetGateset
e.g. spamDict[(0,0)] == "plus"
guessGatesetForGauge : GateSet, optional
A gateset used to compute a gauge transformation that is applied to
the LGST estimates before they are returned.
Defaults to targetGateset.
svdTruncateTo : int, optional
The Hilbert space dimension to truncate the gate matrices to using
a SVD to keep only the largest svdToTruncateTo singular values of
the I_tildle LGST matrix.
Defaults to 0 (no truncation)
maxiter : int, optional
Maximum number of iterations for the least squares optimization
maxfev : int, optional
Maximum number of function evaluations for the least squares optimization
Defaults to maxiter
tol : float, optional
The tolerance for the least squares optimization.
opt_gates : bool, optional
Whether the gate matrices should be optimized
Defaults to True
opt_G0 : bool, optional
Whether the first row of gate matrices should be optimized. If False, then
when the startGateset has TP gates this will now be changed during the
optimization and the resulting gates are guaranteed to be TP.
regularizeFactor : float, optional
Multiplicative prefactor of L2-like regularization term that penalizes gateset entries
which have absolute value greater than 1. When set to 0, no regularization is applied.
verbosity : int, optional
How much detail to send to stdout.
check_jacobian : bool, optional
If True, compare the analytic jacobian with a forward finite difference jacobean
and print warning messages if there is disagreement. Defaults to False.
Returns
-------
numpy array
The minimum error vector v = f(x_min), where f(x)**2 is the function being minimized.
Gateset
The gateset containing all of the estimated labels.
"""
if maxfev is None: maxfev = maxiter
opt_SPAM = opt_SP0 = False #no point in optimizing SPAM gate since it never enters objective function
gs = startGateset.copy()
gate_dim = len(gs.rhoVecs[0])
if verbosity > 2: print ""
if verbosity > 1:
print "--- eLGST (least squares) ---"
#convert list of GateStrings to list of raw tuples since that's all we'll need
if len(gateStringsToUseInEstimation) > 0 and isinstance(gateStringsToUseInEstimation[0],_objs.GateString):
gateStringsToUseInEstimation = [ gstr.tup for gstr in gateStringsToUseInEstimation ]
#Setup and solve a least-squares problem where each element of each
# (lgst_estimated_process - process_estimate_using_current_gateset) difference is a least-squares
# term and the optimization is over the elements of the "current_gateset". Note that:
# lgst_estimated_process = LGST estimate for a gate string in gateStringsToUseInEstimation
# process_estimate_using_current_gateset = process mx you get from multiplying together the gate matrices of the current gateset
#Step 1: get the lgst estimates for each of the "gate strings to use in estimation" list
gateLabelAliases = {}
for (i,gateStrTuple) in enumerate(gateStringsToUseInEstimation):
gateLabelAliases["estimator%d" % i] = gateStrTuple
lgstEstimates = do_lgst(dataset, specs, targetGateset, gateLabelAliases.keys(),
gateLabelAliases, spamDict, guessGatesetForGauge, svdTruncateTo,
verbosity=0) #override verbosity
estimates = _np.empty( (len(gateStringsToUseInEstimation), gate_dim, gate_dim), 'd')
for (i,gateStr) in enumerate(gateStringsToUseInEstimation):
estimates[i] = lgstEstimates[ "estimator%d" % i ]
evTree = gs.bulk_evaltree(gateStringsToUseInEstimation)
maxGateStringLength = max([len(x) for x in gateStringsToUseInEstimation])
#Step 2: create objective function for least squares optimization
if verbosity <= 2:
if regularizeFactor == 0:
def objective_func(vectorGS):
gs.from_vector(vectorGS,G0=opt_G0, SP0=opt_SP0, SPAM=opt_SPAM, gates=opt_gates)
prods = gs.bulk_product(evTree)
ret = (prods - estimates).flatten()
#assert( len( (_np.isnan(ret)).nonzero()[0] ) == 0 )
return ret
else:
def objective_func(vectorGS):
gs.from_vector(vectorGS,G0=opt_G0, SP0=opt_SP0, SPAM=opt_SPAM, gates=opt_gates)
prods = gs.bulk_product(evTree)
gsVecNorm = regularizeFactor * _np.array( [ max(0,absx-1.0) for absx in map(abs,vectorGS) ], 'd')
ret = _np.concatenate( ((prods - estimates).flatten(), gsVecNorm) )
#assert( len( (_np.isnan(ret)).nonzero()[0] ) == 0 )
return ret
else:
def objective_func(vectorGS):
gs.from_vector(vectorGS,G0=opt_G0, SP0=opt_SP0, SPAM=opt_SPAM, gates=opt_gates)
prods = gs.bulk_product(evTree)
ret = (prods - estimates).flatten()
#OLD (uncomment to check)
#errvec = []
#for (i,gateStr) in enumerate(gateStringsToUseInEstimation):
# term1 = lgstEstimates[ "estimator%d" % i ]
# term2 = gs.product(gateStr)
# if _np.linalg.norm(term2 - prods[i]) > 1e-6:
# print "term 2 = \n",term2
# print "prod = \n",prods[i]
# print "Check failed for product %d: %s : %g" % (i,str(gateStr[0:10]),_np.linalg.norm(term2 - prods[i]))
# diff = (term2 - term1).flatten()
# errvec += list(diff)
#ret_chk = _np.array(errvec)
#if _np.linalg.norm( ret - ret_chk ) > 1e-6:
# raise ValueError("Check failed with diff = %g" % _np.linalg.norm( ret - ret_chk ))
if regularizeFactor > 0:
gsVecNorm = regularizeFactor * _np.array( [ max(0,absx-1.0) for absx in map(abs,vectorGS) ], 'd')
ret = _np.concatenate( (ret, gsVecNorm) )
retSq = sum(ret*ret)
print "%g: objfn vec in (%g,%g), gs in (%g,%g), maxLen = %d" % \
(retSq, _np.min(ret), _np.max(ret), _np.min(vectorGS), _np.max(vectorGS), maxGateStringLength)
#assert( len( (_np.isnan(ret)).nonzero()[0] ) == 0 )
return ret
if verbosity <= 3:
if regularizeFactor == 0:
def jacobian(vectorGS):
gs.from_vector(vectorGS,G0=opt_G0, SP0=opt_SP0, SPAM=opt_SPAM, gates=opt_gates)
jac = gs.bulk_dproduct(evTree, gates=opt_gates, G0=opt_G0, flat=True) # shape == nGateStrings*nFlatGate, nDerivCols
if check_jacobian: _opt.check_jac(objective_func, vectorGS, jac, tol=1e-3, eps=1e-6, errType='abs')
return jac
else:
def jacobian(vectorGS):
gs.from_vector(vectorGS,G0=opt_G0, SP0=opt_SP0, SPAM=opt_SPAM, gates=opt_gates)
gsVecGrad = _np.diag( [ (regularizeFactor * _np.sign(x) if abs(x) > 1.0 else 0.0) for x in vectorGS ] )
jac = gs.bulk_dproduct(evTree, gates=opt_gates, G0=opt_G0, flat=True) # shape == nGateStrings*nFlatGate, nDerivCols
jac = _np.concatenate( (jac, gsVecGrad), axis=0 ) # shape == nGateStrings*nFlatGate+nDerivCols, nDerivCols
if check_jacobian: _opt.check_jac(objective_func, vectorGS, jac, tol=1e-3, eps=1e-6, errType='abs')
return jac
#OLD return _np.concatenate( [ gs.dproduct(gateStr, G0=opt_G0, gates=opt_gates, flat=True) \
# for gateStr in gateStringsToUseInEstimation ], axis=0 )
else:
def jacobian(vectorGS):
gs.from_vector(vectorGS,G0=opt_G0, SP0=opt_SP0, SPAM=opt_SPAM, gates=opt_gates)
jac = gs.bulk_dproduct(evTree, gates=opt_gates, G0=opt_G0, flat=True) # shape == nGateStrings*nFlatGate, nDerivCols
if regularizeFactor > 0:
gsVecGrad = _np.diag( [ (regularizeFactor * _np.sign(x) if abs(x) > 1.0 else 0.0) for x in vectorGS ] )
jac = _np.concatenate( (jac, gsVecGrad), axis=0 )
if check_jacobian:
errSum, errs, fd_jac = _opt.check_jac(objective_func, vectorGS, jac, tol=1e-3, eps=1e-6, errType='abs')
print "Jacobian has error %g and %d of %d indices with error > tol" % (errSum, len(errs), jac.shape[0]*jac.shape[1])
if len(errs) > 0:
i,j = errs[0][0:2]; maxabs = _np.max(_np.abs(jac))
print " ==> Worst index = %d,%d. Analytic jac = %g, Fwd Diff = %g" % (i,j, jac[i,j], fd_jac[i,j])
print " ==> max err = ", errs[0][2]
print " ==> max err/max = ", max([ x[2]/maxabs for x in errs ])
return jac
#OLD return _np.concatenate( [ gs.dproduct(gateStr, G0=opt_G0, gates=opt_gates, flat=True) \
# for gateStr in gateStringsToUseInEstimation ], axis=0 )
#def checked_jacobian(vectorGS):
# def obj_i(x, i): return objective_func(x)[i]
# def jac_i(x, i): return (jacobian(x))[i]
# y = objective_func(vectorGS)
# jac = jacobian(vectorGS); nJ = _np.linalg.norm(jac)
# for i in range(len(y)):
# err = _spo.check_grad(obj_i, jac_i, vectorGS, i)
# if err/nJ > 1e-6: print "Jacobian(%d) Error = %g (jac norm = %g)" % (i,err,nJ)
# return jac
#Step 3: solve least squares minimization problem
x0 = gs.to_vector(G0=opt_G0, SP0=opt_SP0, SPAM=opt_SPAM, gates=opt_gates)
opt_x, opt_jac, info, msg, flag = \
_spo.leastsq( objective_func, x0, xtol=tol, ftol=tol, gtol=tol,
maxfev=maxfev*(len(x0)+1), full_output=True, Dfun=jacobian)
full_minErrVec = objective_func(opt_x)
minErrVec = full_minErrVec if regularizeFactor == 0 else full_minErrVec[0:-len(x0)] #don't include regularization terms
#DEBUG: check without using our jacobian
#opt_x_chk, opt_jac_chk, info_chk, msg_chk, flag_chk = \
# _spo.leastsq( objective_func, x0, xtol=tol, ftol=tol, gtol=tol,
# maxfev=maxfev*(len(x0)+1), full_output=True, epsfcn=1e-30)
#minErrVec_chk = objective_func(opt_x_chk)
gs.from_vector(opt_x,G0=opt_G0, SP0=opt_SP0, SPAM=opt_SPAM, gates=opt_gates)
gs.log("ExLGST", { 'method': "leastsq", 'tol': tol, 'maxiter': maxiter,
'opt_G0': opt_G0, 'opt_SP0': opt_SP0 } )
if verbosity > 1:
print " Sum of minimum least squares error (w/out reg terms) = %g" % sum([x**2 for x in minErrVec])
#try: print " log(likelihood) = ", _tools.logl(gs, dataset)
#except: pass
if targetGateset is not None and len(targetGateset.rhoVecs[0]) == len(gs.rhoVecs[0]):
print " frobenius distance to target = ", gs.frobeniusdist(targetGateset)
#DEBUG
#print " Sum of minimum least squares error check = %g" % sum([x**2 for x in minErrVec_chk])
#print "DEBUG : opt_x diff = ", _np.linalg.norm( opt_x - opt_x_chk )
#print "DEBUG : opt_jac diff = ", _np.linalg.norm( opt_jac - opt_jac_chk )
#print "DEBUG : flags (1,2,3,4=OK) = %d, check = %d" % (flag, flag_chk)
return minErrVec, gs
def do_iterative_exlgst(dataset, startGateset, specs, gateStringSetsToUseInEstimation,
targetGateset=None, spamDict=None, guessGatesetForGauge=None,
svdTruncateTo=0, maxiter=100000, maxfev=None, tol=1e-6,
opt_gates=True, opt_G0=True, regularizeFactor=0,
returnErrorVec=False, returnAll=False,
gateStringSetLabels=None, verbosity=0, check_jacobian=False):
"""
Performs Iterated Extended Linear-inversion Gate Set Tomography on the dataset.
Parameters
----------
dataset : DataSet
The data used to generate Extended-LGST estimates
startGateset : GateSet
The GateSet used as a starting point for the least-squares
optimization.
specs : 2-tuple
A (rhoSpecs,ESpecs) tuple usually generated by calling build_spam_specs(...)
gateStringSetsToUseInEstimation : list of lists of (tuples or GateStrings)
The i-th element is a list of the gate strings to be used in the i-th iteration
of extended-LGST. Each element of these lists is a gate string, specifed as
either a GateString object or as a tuple of gate labels (but all must be specified
using the same type).
e.g. [ [ (), ('Gx',) ], [ (), ('Gx',), ('Gy',) ], [ (), ('Gx',), ('Gy',), ('Gx','Gy') ] ]
targetGateset : GateSet, optional
A gateset used to provide a guess for gauge in which LGST estimates should be returned,
and the SPAM labels used to connect the dataset values to rhoVec and EVec indices.
spamDict : dictionary, optional
Dictionary mapping (rhoVec_index,EVec_index) integer tuples to string spam labels.
Defaults to the spam dictionary of targetGateset
e.g. spamDict[(0,0)] == "plus"
guessGatesetForGauge : GateSet, optional
A gateset used to compute a gauge transformation that is applied to
the LGST estimates before they are returned.
Defaults to targetGateset.
svdTruncateTo : int, optional
The Hilbert space dimension to truncate the gate matrices to using
a SVD to keep only the largest svdToTruncateTo singular values of
the I_tildle LGST matrix.
Defaults to 0 (no truncation)
maxiter : int, optional
Maximum number of iterations in each of the least squares optimizations
maxfev : int, optional
Maximum number of function evaluations for each of the least squares optimizations
Defaults to maxiter
tol : float, optional
The tolerance for each of the least squares optimizations.
opt_gates : bool, optional
Whether the gate matrices should be optimized
opt_G0 : bool, optional
Whether the first row of gate matrices should be optimized. If False, then
when the startGateset has TP gates this will now be changed during the
optimization and the resulting gates are guaranteed to be TP.
regularizeFactor : float, optional
Multiplicative prefactor of L2-like regularization term that penalizes gateset entries
which have absolute value greater than 1. When set to 0, no regularization is applied.
returnErrorVec : bool, optional
If True, return (errorVec, gateset), or (errorVecs, gatesets) if
returnAll == True, instead of just the gateset or gatesets.
returnAll : bool, optional
If True return a list of gatesets (and errorVecs if returnErrorVec == True),
one per iteration, instead of the results from just the final iteration.
gateStringSetLabels : list of strings, optional
An identification label for each of the gate string sets (used for displaying
progress). Must be the same length as gateStringSetsToUseInEstimation.
verbosity : int, optional
How much detail to send to stdout.
check_jacobian : boolean, optional
If True, compare the analytic jacobian with a forward finite difference jacobean
and print warning messages if there is disagreement.
Returns
-------
gateset if returnAll == False and returnErrorVec == False
gatesets if returnAll == True and returnErrorVec == False
(errorVec, gateset) if returnAll == False and returnErrorVec == True
(errorVecs, gatesets) if returnAll == True and returnErrorVec == True
where errorVec is a numpy array of minimum error values v = f(x_min), where f(x)**2 is
the function being minimized, gateset is the GateSet containing the final estimated gates.
In cases when returnAll == True, gatesets and errorVecs are lists whose i-th elements are the
errorVec and gateset corresponding to the results of the i-th iteration.
"""
# Parameter to add later??
# whenCannotEstimate : string
# What to do when a gate string to be estimated by LGST cannot because there isn't enough data.
# Allowed values are:
# 'stop' - stop algorithm and report an error (Default)
# 'warn' - skip string, print a warning to stdout, and proceed
# 'ignore' - skip string silently and proceed
#convert lists of GateStrings to lists of raw tuples since that's all we'll need
if len(gateStringSetsToUseInEstimation ) > 0 and \
len(gateStringSetsToUseInEstimation[0]) > 0 and \
isinstance(gateStringSetsToUseInEstimation[0][0],_objs.GateString):
gateStringLists = [ [gstr.tup for gstr in gsList] for gsList in gateStringSetsToUseInEstimation ]
else:
gateStringLists = gateStringSetsToUseInEstimation
#Run extended eLGST iteratively on given sets of estimatable strings
elgstGatesets = [ ]; minErrs = [ ] #for returnAll == True case
elgstGateset = startGateset.copy(); nIters = len(gateStringLists)
for (i,stringsToEstimate) in enumerate(gateStringLists):
if verbosity > 1: print "" #newline if we have more info to print
if verbosity > 0:
print "--- Iterative eLGST: Beginning iter %d of %d %s: %d gate strings ---" \
% (i+1,nIters,("(%s) " % gateStringSetLabels[i]) if gateStringSetLabels else "", len(stringsToEstimate))
_sys.stdout.flush()
if stringsToEstimate is None or len(stringsToEstimate) == 0: continue
minErr, elgstGateset = do_exlgst( dataset, elgstGateset, stringsToEstimate, specs,
targetGateset, spamDict, guessGatesetForGauge,
svdTruncateTo, maxiter, maxfev, tol,
opt_gates, opt_G0, regularizeFactor, verbosity,
check_jacobian )
if returnAll:
elgstGatesets.append(elgstGateset)
minErrs.append(minErr)
if returnErrorVec:
return (minErrs, elgstGatesets) if returnAll else (minErr, elgstGateset)
else:
return elgstGatesets if returnAll else elgstGateset
###################################################################################
# Least-squares GST (LSGST)
##################################################################################
def do_mc2gst(dataset, startGateset, gateStringsToUse,
maxiter=100000, maxfev=None, tol=1e-6,
opt_gates=True, opt_G0=True, opt_SPAM=True, opt_SP0=True,
cptp_penalty_factor=0, minProbClipForWeighting=1e-4, probClipInterval=None,
useFreqWeightedChiSq=False, regularizeFactor=0, verbosity=0,
check=False, check_jacobian=False, gatestringWeights=None, gateLabelAliases=None,
memLimit=None):
"""
Performs Least-Squares Gate Set Tomography on the dataset.
Parameters
----------
dataset : DataSet
The dataset to obtain counts from.
startGateset : GateSet
The GateSet used as a starting point for the least-squares
optimization.
gateStringsToUse : list of (tuples or GateStrings)
Each tuple contains gate labels and specifies a gate string whose
probabilities are considered when trying to least-squares-fit the
probabilities given in the dataset.
e.g. [ (), ('Gx',), ('Gx','Gy') ]
maxiter : int, optional
Maximum number of iterations for the least squares optimization.
maxfev : int, optional
Maximum number of function evaluations for the least squares optimization.
Defaults to maxiter.
tol : float, optional
The tolerance for the least squares optimization.
opt_gates : bool, optional
Whether the gate matrices should be optimized.
opt_G0 : bool, optional
Whether the first row of gate matrices should be optimized. If False, then
when the startGateset has TP gates this will now be changed during the
optimization and the resulting gates are guaranteed to be TP.
opt_SPAM : bool, optional
Whether the rhoVecs and EVecs should be optimized
opt_SP0 : bool, optional
Whether the first element of the state preparation vectors
(i.e. the rhoVecs) should be optimized. If False, then rhoVecs
in startingGateset that are trace == 1 will remain trace == 1
after the optimization.
cptp_penalty_factor : float, optional
If greater than zero, the least squares optimization also contains CPTP penalty
terms which penalize non-CPTP-ness of the gateset being optimized. This factor
multiplies these CPTP penalty terms.
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 LSGST's
least squares search for an optimal gateset (if not None). Defaults to no clipping.
useFreqWeightedChiSq : bool, optional
If True, objective function uses only an approximate chi^2 weighting: N/(f*(1-f))
where f is the frequency obtained from the dataset, instead of the true chi^2: N/(p*(1-p))
where p is a predicted probability. Defaults to False, and only should use
True for backward compatibility.
regularizeFactor : float, optional
Multiplicative prefactor of L2-like regularization term that penalizes gateset entries
which have absolute value greater than 1. When set to 0, no regularization is applied.
verbosity : int, optional
How much detail to send to stdout.
check : boolean, optional
If True, perform extra checks within code to verify correctness. Used
for testing, and runs much slower when True.
check_jacobian : boolean, optional
If True, compare the analytic jacobian with a forward finite difference jacobean
and print warning messages if there is disagreement. Defaults to False.
gatestringWeights : numpy array, optional
An array of length len(gateStringsToUse). Each element scales the
least-squares term of the corresponding gate string in gateStringsToUse.
The default is no weight scaling at all.
gateLabelAliases : dictionary, optional
Dictionary whose keys are gate label "aliases" and whose values are tuples
corresponding to what that gate label should be expanded into before querying
the dataset. Defaults to the empty dictionary (no aliases defined)
e.g. gateLabelAliases['Gx^3'] = ('Gx','Gx','Gx')
memLimit : int, optional
A rough memory limit in bytes which restricts the amount of intermediate
values that are computed and stored.
Returns
-------
errorVec : numpy array
Minimum error values v = f(x_best), where f(x)**2 is the function being minimized
gateset : GateSet
GateSet containing the estimated gates.
"""
gs = startGateset.copy()
if maxfev is None: maxfev = maxiter
if verbosity > 2: print ""
if verbosity > 1:
print "--- Least Squares GST ---"
#convert list of GateStrings to list of raw tuples since that's all we'll need
if len(gateStringsToUse) > 0 and isinstance(gateStringsToUse[0],_objs.GateString):
gateStringsToUse = [ gstr.tup for gstr in gateStringsToUse ]
spamLabels = gs.get_spam_labels() #this list fixes the ordering of the spam labels
spam_lbl_rows = { sl:i for (i,sl) in enumerate(spamLabels) }
vec_gs_len = len(gs.to_vector(G0=opt_G0, SP0=opt_SP0, SPAM=opt_SPAM, gates=opt_gates))
KM = len(spamLabels)*len(gateStringsToUse) #shorthand for this combined dimension used below
if gateLabelAliases is not None: #then find & replace aliased gate labels with their expanded form
dsGateStringsToUse = []
for s in gateStringsToUse:
for label,expandedStr in gateLabelAliases.iteritems():
while label in tuple(s):
i = tuple(s).index(label)
s = tuple(s)[:i] + tuple(expandedStr) + tuple(s)[i+1:]
dsGateStringsToUse.append(s)
else:
dsGateStringsToUse = gateStringsToUse # no difference in the strings used by the alias
probs = _np.empty( (len(spamLabels),len(gateStringsToUse)) )
dprobs = _np.empty( (len(spamLabels),len(gateStringsToUse),vec_gs_len) )
N = _np.array( [ dataset[gateStr].total() for gateStr in dsGateStringsToUse ], 'd')
f = _np.empty( (len(spamLabels),len(gateStringsToUse)) )
fweights = _np.empty( (len(spamLabels),len(gateStringsToUse)) )
z = _np.zeros( (len(spamLabels),len(gateStringsToUse)) ) #always zeros - used for derivative below
#Memory estimates - maybe make GateSet methods to get intermediate memory estimates
ns = len(spamLabels); ng = len(gateStringsToUse); ne = vec_gs_len; gd = len(gs.rhoVecs[0])
persistentMem = 8* (ng*(ns + ns*ne + 1 + 3*ns)) # Memory needed by final results in bytes
intermedMem = 8* (ng*(1 + gd**2 * (1 + ne))) # Memory needed by intermediate results in bytes (now just ~ that of dproduct)
C = 1.0/1024.0**3 #; print "DEBUG: MEM",persistentMem," , ", intermedMem
maxEvalSubTreeSize = None
if memLimit is not None:
if memLimit < persistentMem:
raise MemoryError("Memory limit (%g GB) is < memory required to hold final results (%g GB)" % (memLimit*C, persistentMem*C))
if memLimit < intermedMem:
reductionFactor = float(intermedMem) / float(memLimit)
maxEvalSubTreeSize = int(ng / reductionFactor)
if verbosity > 2:
print "Peristent Memory estimate: %d spam labels, %d gate strings, %d gateset params" % (ns,ng,ne)
print " ==> %g GB (p) + %g GB (dp) + %g GB (other) = %g GB (total)" % \
(8*ns*ng*C, 8*ns*ng*ne*C,8*(ng+3*ns*ng)*C, persistentMem*C)
print "Intermediate Memory estimate: %d gate strings, %d gate dimension, %d gateset params" % (ng,gd,ne)
print " ==> %g GB (p) + %g GB (dp) + %g GB (other) = %g GB (total)" % \
(8*ng*gd*gd*C, 8*ng*gd*gd*ne*C,8*ng*C, intermedMem*C)
if memLimit is not None: print "Memory limit = %g GB" % (memLimit*C)
if maxEvalSubTreeSize is not None: print "Maximum eval sub-tree size = %d" % maxEvalSubTreeSize
#NOTE on chi^2 expressions:
#in general case: chi^2 = sum (p_i-f_i)^2/p_i (for i summed over outcomes)
#in 2-outcome case: chi^2 = (p+ - f+)^2/p+ + (p- - f-)^2/p-
# = (p - f)^2/p + (1-p - (1-f))^2/(1-p)
# = (p - f)^2 * (1/p + 1/(1-p))
# = (p - f)^2 * ( ((1-p) + p)/(p*(1-p)) )
# = 1/(p*(1-p)) * (p - f)^2
for (i,gateStr) in enumerate(dsGateStringsToUse):
for k,sl in enumerate(spamLabels):
n = float(dataset[gateStr][sl])
f[k,i] = n / N[i]; f2 = (n+1)/(N[i]+2)
fweights[k,i] = _np.sqrt( N[i] / (f2*(1-f2)) )
if gatestringWeights is not None:
fweights *= gatestringWeights[None,:] #b/c we necessarily used unweighted N[i]'s above
N *= gatestringWeights #multiply N's by weights
evTree = gs.bulk_evaltree(gateStringsToUse)
maxGateStringLength = max([len(x) for x in gateStringsToUse])
if maxEvalSubTreeSize is not None:
evTree.split(maxEvalSubTreeSize)
if verbosity > 2:
print "Memory limit has imposed a division of the evaluation tree:"
evTree.print_analysis()
if useFreqWeightedChiSq:
def get_weights(p):
return fweights
def get_dweights(p,wts):
return z
else:
def get_weights(p):
cp = _np.clip(p,minProbClipForWeighting,1-minProbClipForWeighting)
return _np.sqrt(N / cp) # nSpamLabels x nGateStrings array (K x M)
def get_dweights(p,wts): #derivative of weights w.r.t. p
cp = _np.clip(p,minProbClipForWeighting,1-minProbClipForWeighting)
dw = -0.5 * wts / cp # nSpamLabels x nGateStrings array (K x M)
dw[ _np.logical_or(p < minProbClipForWeighting, p>(1-minProbClipForWeighting)) ] = 0.0
return dw