/
core.py
2599 lines (2125 loc) · 123 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
""" Core GST algorithms """
from __future__ import division, print_function, absolute_import, unicode_literals
#*****************************************************************
# 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
#*****************************************************************
import numpy as _np
import scipy.optimize as _spo
import scipy.stats as _stats
import warnings as _warnings
import time as _time
from .. import optimize as _opt
from .. import tools as _tools
from .. import objects as _objs
from .. import baseobjs as _baseobjs
from .. import construction as _pc
from ..baseobjs import objectivefns as _objfns
from ..baseobjs import DummyProfiler as _DummyProfiler
_dummy_profiler = _DummyProfiler()
CUSTOMLM = True
FLOATSIZE = 8 # TODO: better way?
#from .track_allocations import AllocationTracker
#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_model_info(...)
###################################################################################
# Linear Inversion GST (LGST)
###################################################################################
def do_lgst(dataset, prepStrs, effectStrs, targetModel, opLabels=None, opLabelAliases={},
guessModelForGauge=None, svdTruncateTo=None, verbosity=0):
"""
Performs Linear-inversion Gate Set Tomography on the dataset.
Parameters
----------
dataset : DataSet
The data used to generate the LGST estimates
prepStrs,effectStrs : list of Circuits
Fiducial Circuit lists used to construct a informationally complete
preparation and measurement.
targetModel : Model
A model used to specify which operation labels should be estimated, a
guess for which gauge these estimates should be returned in, and
used to simplify operation sequences.
opLabels : list, optional
A list of which operation labels (or aliases) should be estimated.
Overrides the operation labels in targetModel.
e.g. ['Gi','Gx','Gy','Gx2']
opLabelAliases : dictionary, optional
Dictionary whose keys are operation label "aliases" and whose values are tuples
corresponding to what that operation label should be expanded into before querying
the dataset.
Defaults to the empty dictionary (no aliases defined)
e.g. opLabelAliases['Gx^3'] = ('Gx','Gx','Gx')
guessModelForGauge : Model, optional
A model 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 model given,
then the operation matrices would match, i.e. the gauge would be the same as
the model supplied.
Defaults to targetModel.
svdTruncateTo : int, optional
The Hilbert space dimension to truncate the operation matrices to using
a SVD to keep only the largest svdToTruncateTo singular values of
the I_tildle LGST matrix. Zero means no truncation.
Defaults to dimension of `targetModel`.
verbosity : int, optional
How much detail to send to stdout.
Returns
-------
Model
A model containing all of the estimated labels (or aliases)
"""
#Notes:
# We compute, # noqa
# I_tilde = AB (trunc,trunc), where trunc <= K = min(nRhoSpecs,nESpecs) # noqa
# X_tilde = AXB (trunc,trunc) # noqa
# and A, B for *target* model. (but target model may need dimension increase to get to trunc... and then A,B are rank deficient) # noqa
# We would like to get X or it's gauge equivalent. # noqa
# We do: 1) (I^-1)*AXB ~= B^-1 X B := Xhat -- we solve Ii*A*B = identity for Ii # noqa
# 2) B * Xhat * B^-1 ==> X (but what if B is non-invertible -- say rectangular) Want B*(something) ~ identity ?? # noqa
# for lower rank target models, want a gauge tranformation that brings Xhat => X of "increased dim" model # noqa
# want "B^-1" such that B(gsDim,nRhoSpecs) "B^-1"(nRhoSpecs,gsDim) ~ Identity(gsDim) # noqa
# Ub,sb,Vb = svd(B) so B = Ub*diag(sb)*Vb where Ub = (gsDim,M), s = (M,M), Vb = (M,prepSpecs) # noqa
# if B^-1 := VbT*sb^-1*Ub^-1 then B*B^-1 = I(gsDim) # noqa
# similarly, can get want "A^-1" such that "A^-1"(gsDim,nESpecs) A(nESpecs,gsDim) ~ Identity(gsDim) # noqa
# 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. # noqa
# (but we can't do this, since we only have AB, not A and B separately) # noqa
# A is (trunc, gsDim) # noqa
# B is (gsDim, trunc) # noqa
# 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)
printer = _objs.VerbosityPrinter.build_printer(verbosity)
if targetModel is None:
raise ValueError("Must specify a target model for LGST!")
#printer.log('', 2)
printer.log("--- LGST ---", 1)
#Process input parameters
if opLabels is not None:
opLabelsToEstimate = opLabels
else:
opLabelsToEstimate = list(targetModel.operations.keys()) + \
list(targetModel.instruments.keys())
rhoLabelsToEstimate = list(targetModel.preps.keys())
povmLabelsToEstimate = list(targetModel.povms.keys())
if guessModelForGauge is None:
guessModelForGauge = targetModel
# the dimensions of the LGST matrices, called (nESpecs, nRhoSpecs),
# are determined by the number of outcomes obtained by compiling the
# all prepStr * effectStr sequences:
nRhoSpecs, nESpecs, povmLbls, povmLens = _lgst_matrix_dims(
targetModel, prepStrs, effectStrs)
K = min(nRhoSpecs, nESpecs)
#Create truncation projector -- just trims columns (Pj) or rows (Pjt) of a matrix.
# note K = min(nRhoSpecs,nESpecs), and dot(Pjt,Pj) == identity(trunc)
if svdTruncateTo is None: svdTruncateTo = targetModel.dim
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(prepStrs, effectStrs, targetModel, dataset, opLabelAliases) # shape = (nESpecs, nRhoSpecs)
U, s, V = _np.linalg.svd(ABMat, full_matrices=False)
printer.log("Singular values of I_tilde (truncating to first %d of %d) = " % (trunc, len(s)), 2)
for sval in s: printer.log(sval, 2)
printer.log('', 2)
Ud, Vd = _np.transpose(_np.conjugate(U)), _np.transpose(_np.conjugate(V)) # Udagger, Vdagger
# truncate ABMat => ABMat' (note diag(s) = Ud*ABMat*Vd), shape = (trunc, trunc)
ABMat_p = _np.dot(Pjt, _np.dot(_np.diag(s), Pj))
# 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 prepStrs and/or effectStrs, "
"or decrease svdTruncateTo" % (rankAB, ABMat_p.shape[0]))
invABMat_p = _np.dot(Pjt, _np.dot(_np.diag(1.0 / s), Pj)) # (trunc,trunc)
# check inverse is correct (TODO: comment out later)
assert(_np.linalg.norm(_np.linalg.inv(ABMat_p) - invABMat_p) < 1e-8)
assert(len((_np.isnan(invABMat_p)).nonzero()[0]) == 0)
if svdTruncateTo is None or svdTruncateTo == targetModel.dim: # use target sslbls and basis
lgstModel = _objs.ExplicitOpModel(targetModel.state_space_labels, targetModel.basis)
else: # construct a default basis for the requested dimension
# - just act on diagonal density mx
dumb_basis = _objs.DirectSumBasis([_objs.BuiltinBasis('gm', 1)] * svdTruncateTo)
lgstModel = _objs.ExplicitOpModel([('L%d' % i,) for i in range(svdTruncateTo)], dumb_basis)
for opLabel in opLabelsToEstimate:
Xs = _constructXMatrix(prepStrs, effectStrs, targetModel, (opLabel,),
dataset, opLabelAliases) # shape (nVariants, nESpecs, nRhoSpecs)
X_ps = []
for X in Xs:
# shape (K,K) this should be close to rank "svdTruncateTo" (which is <= K) -- TODO: check this
X2 = _np.dot(Ud, _np.dot(X, Vd))
#if svdTruncateTo > 0:
# printer.log("LGST DEBUG: %s before trunc to first %d row and cols = \n" % (opLabel,svdTruncateTo), 3)
# if printer.verbosity >= 3:
# _tools.print_mx(X2)
X_p = _np.dot(Pjt, _np.dot(X2, Pj)) # truncate X => X', shape (trunc, trunc)
X_ps.append(X_p)
if opLabel in targetModel.instruments:
#Note: we assume leading dim of X matches instrument element ordering
lgstModel.instruments[opLabel] = _objs.Instrument(
[(lbl, _np.dot(invABMat_p, X_ps[i]))
for i, lbl in enumerate(targetModel.instruments[opLabel])])
else:
#Just a normal gae
assert(len(X_ps) == 1); X_p = X_ps[0] # shape (nESpecs, nRhoSpecs)
lgstModel.operations[opLabel] = _objs.FullDenseOp(_np.dot(invABMat_p, X_p)) # shape (trunc,trunc)
#print "DEBUG: X(%s) = \n" % opLabel,X
#print "DEBUG: Evals(X) = \n",_np.linalg.eigvals(X)
#print "DEBUG: %s = \n" % opLabel,lgstModel[ opLabel ]
#Form POVMs
for povmLabel in povmLabelsToEstimate:
povm_effects = []
for effectLabel in targetModel.povms[povmLabel]:
EVec = _np.zeros((1, nRhoSpecs))
for i, rhostr in enumerate(prepStrs):
circuit = rhostr + _objs.Circuit((povmLabel,))
if circuit not in dataset and len(targetModel.povms) == 1:
# try without povmLabel since it will be the default
circuit = rhostr
dsRow = dataset[circuit]
# outcome labels should just be effect labels (no instruments!)
EVec[0, i] = dsRow.fraction((effectLabel,))
EVec_p = _np.dot(_np.dot(EVec, Vd), Pj) # truncate Evec => Evec', shape (1,trunc)
povm_effects.append((effectLabel, _np.transpose(EVec_p)))
lgstModel.povms[povmLabel] = _objs.UnconstrainedPOVM(povm_effects)
# unconstrained POVM for now - wait until after guess gauge for TP-constraining)
# Form rhoVecs
for prepLabel in rhoLabelsToEstimate:
rhoVec = _np.zeros((nESpecs, 1)); eoff = 0
for i, (estr, povmLbl, povmLen) in enumerate(zip(effectStrs, povmLbls, povmLens)):
circuit = _objs.Circuit((prepLabel,)) + estr # ; spamLabel = spamDict[ (prepLabel, espec.lbl) ]
if circuit not in dataset and len(targetModel.preps) == 1:
# try without prepLabel since it will be the default
circuit = estr
dsRow = dataset[circuit]
rhoVec[eoff:eoff + povmLen, 0] = [dsRow.fraction((ol,)) for ol in targetModel.povms[povmLbl]]
eoff += povmLen
rhoVec_p = _np.dot(Pjt, _np.dot(Ud, rhoVec)) # truncate rhoVec => rhoVec', shape (trunc, 1)
rhoVec_p = _np.dot(invABMat_p, rhoVec_p)
lgstModel.preps[prepLabel] = rhoVec_p
# Perform "guess" gauge transformation by computing the "B" matrix
# assuming rhos, Es, and gates are those of a guesstimate of the model
if guessModelForGauge is not None:
guessTrunc = guessModelForGauge.get_dimension() # the truncation to apply to it's B matrix
# the dimension of the model for gauge guessing cannot exceed the dimension of the model being estimated
assert(guessTrunc <= trunc)
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(effectStrs, guessModelForGauge) # shape = (nESpecs, gsDim)
# AMat_p = _np.dot( guessPjt, _np.dot(Ud, AMat)) #truncate Evec => Evec', shape (guessTrunc,gsDim) (square!)
BMat = _constructB(prepStrs, guessModelForGauge) # shape = (gsDim, nRhoSpecs)
BMat_p = _np.dot(_np.dot(BMat, Vd), guessPj) # truncate Evec => Evec', shape (gsDim,guessTrunc) (square!)
guess_ABMat = _np.dot(AMat, BMat)
_, guess_s, _ = _np.linalg.svd(guess_ABMat, full_matrices=False)
printer.log("Singular values of target I_tilde (truncating to first %d of %d) = "
% (guessTrunc, len(guess_s)), 2)
for sval in guess_s: printer.log(sval, 2)
printer.log('', 2)
if guessTrunc < trunc:
# if the dimension of the gauge-guess model is smaller than the matrices being estimated, pad B with
# identity
printer.log("LGST: Padding target B with sqrt of low singular values of I_tilde: \n", 2)
printer.log(s[guessTrunc:trunc], 2)
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
ggEl = _objs.FullGaugeGroupElement(_np.linalg.inv(BMat_p_padded))
lgstModel.transform(ggEl)
else:
ggEl = _objs.FullGaugeGroupElement(_np.linalg.inv(BMat_p))
lgstModel.transform(ggEl)
# Force lgstModel to have gates, preps, & effects parameterized in the same way as those in
# guessModelForGauge, but we only know how to do this when the dimensions of the target and
# created model match. If they don't, it doesn't make sense to increase the target model
# dimension, as this will generally not preserve its parameterization.
if guessTrunc == trunc:
for opLabel in opLabelsToEstimate:
if opLabel in guessModelForGauge.operations:
new_op = guessModelForGauge.operations[opLabel].copy()
_objs.operation.optimize_operation(new_op, lgstModel.operations[opLabel])
lgstModel.operations[opLabel] = new_op
for prepLabel in rhoLabelsToEstimate:
if prepLabel in guessModelForGauge.preps:
new_vec = guessModelForGauge.preps[prepLabel].copy()
_objs.spamvec.optimize_spamvec(new_vec, lgstModel.preps[prepLabel])
lgstModel.preps[prepLabel] = new_vec
for povmLabel in povmLabelsToEstimate:
if povmLabel in guessModelForGauge.povms:
povm = guessModelForGauge.povms[povmLabel]
new_effects = []
if isinstance(povm, _objs.TPPOVM): # preserve *identity* of guess
for effectLabel, EVec in povm.items():
if effectLabel == povm.complement_label: continue
new_vec = EVec.copy()
_objs.spamvec.optimize_spamvec(new_vec, lgstModel.povms[povmLabel][effectLabel])
new_effects.append((effectLabel, new_vec))
# Construct identity vector for complement effect vector
# Pad with zeros if needed (ROBIN - is this correct?)
identity = povm[povm.complement_label].identity
Idim = identity.shape[0]
assert(Idim <= trunc)
if Idim < trunc:
padded_identityVec = _np.concatenate((identity, _np.zeros((trunc - Idim, 1), 'd')))
else:
padded_identityVec = identity
comp_effect = padded_identityVec - sum([v for k, v in new_effects])
new_effects.append((povm.complement_label, comp_effect)) # add complement
lgstModel.povms[povmLabel] = _objs.TPPOVM(new_effects)
else: # just create an unconstrained POVM
for effectLabel, EVec in povm.items():
new_vec = EVec.copy()
_objs.spamvec.optimize_spamvec(new_vec, lgstModel.povms[povmLabel][effectLabel])
new_effects.append((effectLabel, new_vec))
lgstModel.povms[povmLabel] = _objs.UnconstrainedPOVM(new_effects)
#Also convey default gauge group & calc class from guessModelForGauge
lgstModel.default_gauge_group = \
guessModelForGauge.default_gauge_group
lgstModel._calcClass = guessModelForGauge._calcClass
#inv_BMat_p = _np.dot(invABMat_p, AMat_p) # should be equal to inv(BMat_p) when trunc == gsDim ?? check??
# # lgstModel had dim trunc, so after transform is has dim gsDim
#lgstModel.transform( S=_np.dot(invABMat_p, AMat_p), Si=BMat_p )
printer.log("Resulting model:\n", 3)
printer.log(lgstModel, 3)
# for line in str(lgstModel).split('\n'):
# printer.log(line, 3)
return lgstModel
def _lgst_matrix_dims(mdl, prepStrs, effectStrs):
assert(mdl is not None), "LGST matrix construction requires a non-None Model!"
nRhoSpecs = len(prepStrs) # no instruments allowed in prepStrs
povmLbls = [mdl.split_circuit(s, ('povm',))[2] # povm_label
for s in effectStrs]
povmLens = ([len(mdl.povms[l]) for l in povmLbls])
nESpecs = sum(povmLens)
return nRhoSpecs, nESpecs, povmLbls, povmLens
def _constructAB(prepStrs, effectStrs, model, dataset, opLabelAliases=None):
nRhoSpecs, nESpecs, povmLbls, povmLens = _lgst_matrix_dims(
model, prepStrs, effectStrs)
AB = _np.empty((nESpecs, nRhoSpecs))
eoff = 0
for i, (estr, povmLen) in enumerate(zip(effectStrs, povmLens)):
for j, rhostr in enumerate(prepStrs):
opLabelString = rhostr + estr # LEXICOGRAPHICAL VS MATRIX ORDER
dsStr = _tools.find_replace_tuple(opLabelString, opLabelAliases)
raw_dict, outcomes = model.simplify_circuit(opLabelString)
assert(len(raw_dict) == 1), "No instruments are allowed in LGST fiducials!"
unique_key = list(raw_dict.keys())[0]
assert(len(raw_dict[unique_key]) == povmLen)
dsRow = dataset[dsStr]
AB[eoff:eoff + povmLen, j] = [dsRow.fraction(ol) for ol in outcomes]
eoff += povmLen
return AB
def _constructXMatrix(prepStrs, effectStrs, model, opLabelTuple, dataset, opLabelAliases=None):
nRhoSpecs, nESpecs, povmLbls, povmLens = _lgst_matrix_dims(
model, prepStrs, effectStrs)
nVariants = 1
for g in opLabelTuple:
if g in model.instruments:
nVariants *= len(model.instruments[g])
X = _np.empty((nVariants, nESpecs, nRhoSpecs)) # multiple "X" matrix variants b/c of instruments
eoff = 0 # effect-dimension offset
for i, (estr, povmLen) in enumerate(zip(effectStrs, povmLens)):
for j, rhostr in enumerate(prepStrs):
opLabelString = rhostr + _objs.Circuit(opLabelTuple) + estr # LEXICOGRAPHICAL VS MATRIX ORDER
dsStr = _tools.find_replace_tuple(tuple(opLabelString), opLabelAliases)
raw_dict, outcomes = model.simplify_circuit(opLabelString)
dsRow = dataset[dsStr]
assert(len(raw_dict) == nVariants)
ooff = 0 # outcome offset
for k, (raw_str, spamtups) in enumerate(raw_dict.items()):
assert(len(spamtups) == povmLen)
X[k, eoff:eoff + povmLen, j] = [
dsRow.fraction(ol) for ol in outcomes[ooff:ooff + len(spamtups)]]
ooff += len(spamtups)
eoff += povmLen
return X
def _constructA(effectStrs, mdl):
_, n, povmLbls, povmLens = _lgst_matrix_dims(
mdl, [], effectStrs)
dim = mdl.get_dimension()
A = _np.empty((n, dim))
# st = _np.empty(dim, 'd')
basis_st = _np.zeros((dim, 1), 'd'); eoff = 0
for k, (estr, povmLbl, povmLen) in enumerate(zip(effectStrs, povmLbls, povmLens)):
#Build fiducial < E_k | := < EVec[ effectSpec[0] ] | Circuit(effectSpec[1:])
#st = dot(Ek.T, Estr) = ( dot(Estr.T,Ek) ).T
#A[k,:] = st[0,:] # E_k == kth row of A
for i in range(dim): # propagate each basis initial state
basis_st[i] = 1.0
mdl.preps['rho_LGST_tmp'] = basis_st
probs = mdl.probs(_objs.Circuit(('rho_LGST_tmp',)) + estr)
A[eoff:eoff + povmLen, i] = [probs[(ol,)] for ol in mdl.povms[povmLbl]] # CHECK will this work?
del mdl.preps['rho_LGST_tmp']
basis_st[i] = 0.0
eoff += povmLen
return A
def _constructB(prepStrs, mdl):
n = len(prepStrs)
dim = mdl.get_dimension()
B = _np.empty((dim, n))
# st = _np.empty(dim, 'd')
#Create POVM of vector units
basis_Es = []
for i in range(dim): # propagate each basis initial state
basis_E = _np.zeros((dim, 1), 'd')
basis_E[i] = 1.0
basis_Es.append(basis_E)
mdl.povms['M_LGST_tmp_povm'] = _objs.UnconstrainedPOVM(
[("E%d" % i, E) for i, E in enumerate(basis_Es)])
for k, rhostr in enumerate(prepStrs):
#Build fiducial | rho_k > := Circuit(prepSpec[0:-1]) | rhoVec[ prepSpec[-1] ] >
# B[:,k] = st[:,0] # rho_k == kth column of B
probs = mdl.probs(rhostr + _objs.Circuit(('M_LGST_tmp_povm',)))
B[:, k] = [probs[("E%d" % i,)] for i in range(dim)] # CHECK will this work?
del mdl.povms['M_LGST_tmp_povm']
return B
def _constructTargetAB(prepStrs, effectStrs, targetModel):
nRhoSpecs, nESpecs, povmLbls, povmLens = _lgst_matrix_dims(
targetModel, prepStrs, effectStrs)
AB = _np.empty((nESpecs, nRhoSpecs))
eoff = 0
for i, (estr, povmLbl, povmLen) in enumerate(zip(effectStrs, povmLbls, povmLens)):
for j, rhostr in enumerate(prepStrs):
opLabelString = rhostr + estr # LEXICOGRAPHICAL VS MATRIX ORDER
probs = targetModel.probs(opLabelString)
AB[eoff:eoff + povmLen, j] = \
[probs[(ol,)] for ol in targetModel.povms[povmLbl]]
# outcomes (keys of probs) should just be povm effect labels
# since no instruments are allowed in fiducial strings.
eoff += povmLen
return AB
def gram_rank_and_evals(dataset, prepStrs, effectStrs, targetModel):
"""
Returns the rank and singular values of the Gram matrix for a dataset.
Parameters
----------
dataset : DataSet
The data used to populate the Gram matrix
prepStrs, effectStrs : list
Lists of preparation and measurement fiducial sequences.
targetModel : Model
A model used to make sense of operation sequence elements, and to compute the
theoretical gram matrix eigenvalues (returned as `svalues_target`).
Returns
-------
rank : int
the rank of the Gram matrix
svalues : numpy array
the singular values of the Gram matrix
svalues_target : numpy array
the corresponding singular values of the Gram matrix
generated by targetModel.
"""
if targetModel is None: raise ValueError("Must supply `targetModel`")
ABMat = _constructAB(prepStrs, effectStrs, targetModel, dataset)
_, s, _ = _np.linalg.svd(ABMat)
ABMat_tgt = _constructTargetAB(prepStrs, effectStrs, targetModel)
_, s_tgt, _ = _np.linalg.svd(ABMat_tgt)
return _np.linalg.matrix_rank(ABMat), s, s_tgt # _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, startModel, circuitsToUseInEstimation, prepStrs,
effectStrs, targetModel, guessModelForGauge=None,
svdTruncateTo=None, maxiter=100000, maxfev=None, tol=1e-6,
regularizeFactor=0, verbosity=0, comm=None, check_jacobian=False):
"""
Performs Extended Linear-inversion Gate Set Tomography on the dataset.
Parameters
----------
dataset : DataSet
The data used to generate Extended-LGST estimates
startModel : Model
The Model used as a starting point for the least-squares
optimization.
circuitsToUseInEstimation : list of (tuples or Circuits)
Each element of this list specifies a operation sequence that is
estimated using LGST and used in the overall least-squares
fit that determines the final "extended LGST" model.
e.g. [ (), ('Gx',), ('Gx','Gy') ]
prepStrs,effectStrs : list of Circuits
Fiducial Circuit lists used to construct a informationally complete
preparation and measurement.
targetModel : Model
A model used to provide a guess for gauge in which LGST estimates
should be returned, and the ability to make sense of ("complile")
operation sequences.
guessModelForGauge : Model, optional
A model used to compute a gauge transformation that is applied to
the LGST estimates before they are returned.
Defaults to targetModel.
svdTruncateTo : int, optional
The Hilbert space dimension to truncate the operation matrices to using
a SVD to keep only the largest svdToTruncateTo singular values of
the I_tildle LGST matrix. 0 causes no truncation, and default is
`targetModel.dim`.
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.
regularizeFactor : float, optional
Multiplicative prefactor of L2-like regularization term that penalizes model 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.
comm : mpi4py.MPI.Comm, optional
When not None, an MPI communicator for distributing the computation
across multiple processors.
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.
Model
The model containing all of the estimated labels.
"""
printer = _objs.VerbosityPrinter.build_printer(verbosity, comm)
if maxfev is None: maxfev = maxiter
mdl = startModel.copy()
op_dim = mdl.get_dimension()
#In order to make sure the vectorized model size matches the
# "dproduct" size, we *don't* want to parameterize any of the
# SPAM vectors in the model -- these parameters are not
# optimized in exLGST so don't paramterize them. Note that this
# assumes a "local" Model where parameters are attributed to
# individual SPAM vecs and gates.
for prepLabel, rhoVec in mdl.preps.items():
mdl.preps[prepLabel] = _objs.StaticSPAMVec(rhoVec)
for povmLabel, povm in mdl.povms.items():
mdl.povms[povmLabel] = _objs.UnconstrainedPOVM(
[(lbl, _objs.StaticSPAMVec(E))
for lbl, E in povm.items()])
printer.log("--- eLGST (least squares) ---", 1)
#convert list of Circuits to list of raw tuples since that's all we'll need
if len(circuitsToUseInEstimation) > 0 and isinstance(circuitsToUseInEstimation[0], _objs.Circuit):
circuitsToUseInEstimation = [opstr.tup for opstr in circuitsToUseInEstimation]
#Setup and solve a least-squares problem where each element of each
# (lgst_estimated_process - process_estimate_using_current_model) difference is a least-squares
# term and the optimization is over the elements of the "current_model". Note that:
# lgst_estimated_process = LGST estimate for a operation sequence in circuitsToUseInEstimation
# process_estimate_using_current_model = process mx you get from multiplying together the operation matrices of
# the current model
#Step 1: get the lgst estimates for each of the "operation sequences to use in estimation" list
evTree, _, _ = mdl.bulk_evaltree(circuitsToUseInEstimation)
circuitsToUseInEstimation = evTree.generate_circuit_list(permute=False)
# length of this list == that of raw "simplify" dict == dim of bulk_product, etc.
opLabelAliases = {}
for i, opStrTuple in enumerate(circuitsToUseInEstimation):
opLabelAliases["Gestimator%d" % i] = opStrTuple
lgstEstimates = do_lgst(dataset, prepStrs, effectStrs, targetModel, list(opLabelAliases.keys()),
opLabelAliases, guessModelForGauge, svdTruncateTo,
verbosity=0) # override verbosity
estimates = _np.empty((len(circuitsToUseInEstimation), op_dim, op_dim), 'd')
for i in range(len(circuitsToUseInEstimation)):
estimates[i] = lgstEstimates.operations["Gestimator%d" % i]
maxCircuitLength = max([len(x) for x in circuitsToUseInEstimation])
#Step 2: create objective function for least squares optimization
if printer.verbosity < 3:
if regularizeFactor == 0:
def _objective_func(vectorGS):
mdl.from_vector(vectorGS)
prods = mdl.bulk_product(evTree, comm=comm)
ret = (prods - estimates).flatten()
#assert( len( (_np.isnan(ret)).nonzero()[0] ) == 0 )
return ret
else:
def _objective_func(vectorGS):
mdl.from_vector(vectorGS)
prods = mdl.bulk_product(evTree, comm=comm)
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):
mdl.from_vector(vectorGS)
prods = mdl.bulk_product(evTree, comm=comm)
ret = (prods - estimates).flatten()
#OLD (uncomment to check)
#errvec = []
#for (i,opStr) in enumerate(circuitsToUseInEstimation):
# term1 = lgstEstimates[ "Gestimator%d" % i ]
# term2 = mdl.product(opStr)
# 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(opStr[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)
printer.log(
("%g: objfn vec in (%g,%g), mdl in (%g,%g), maxLen = %d" %
(retSq, _np.min(ret), _np.max(ret), _np.min(vectorGS), _np.max(vectorGS), maxCircuitLength)),
3)
#assert( len( (_np.isnan(ret)).nonzero()[0] ) == 0 )
return ret
if printer.verbosity < 3:
if regularizeFactor == 0:
def _jacobian(vectorGS):
mdl.from_vector(vectorGS)
jac = mdl.bulk_dproduct(evTree, flat=True, comm=comm)
# shape == nCircuits*nFlatOp, 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):
mdl.from_vector(vectorGS)
gsVecGrad = _np.diag([(regularizeFactor * _np.sign(x) if abs(x) > 1.0 else 0.0) for x in vectorGS])
jac = mdl.bulk_dproduct(evTree, flat=True, comm=comm)
# shape == nCircuits*nFlatOp, nDerivCols
jac = _np.concatenate((jac, gsVecGrad), axis=0) # shape == nCircuits*nFlatOp+nDerivCols, 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):
mdl.from_vector(vectorGS)
jac = mdl.bulk_dproduct(evTree, flat=True, comm=comm)
# shape == nCircuits*nFlatOp, 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')
printer.log("Jacobian has error %g and %d of %d indices with error > tol" %
(errSum, len(errs), jac.shape[0]), 3)
if len(errs) > 0:
i, j = errs[0][0:2]; maxabs = _np.max(_np.abs(jac)) # pragma: no cover
printer.log(" ==> Worst index = %d,%d. Analytic jac = %g, Fwd Diff = %g" # pragma: no cover
% (i, j, jac[i, j], fd_jac[i, j]), 3) # pragma: no cover
printer.log(" ==> max err = ", errs[0][2], 3) # pragma: no cover
printer.log(" ==> max err/max = ", max([x[2] / maxabs for x in errs]), 3) # pragma: no cover
return jac
#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 = mdl.to_vector()
opt_x, _, _, _, _ = \
_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)
# don't include regularization terms
minErrVec = full_minErrVec if regularizeFactor == 0 else full_minErrVec[0:-len(x0)]
#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)
mdl.from_vector(opt_x)
#mdl.log("ExLGST", { 'method': "leastsq", 'tol': tol, 'maxiter': maxiter } )
printer.log(("Sum of minimum least squares error (w/out reg terms) = %g" % sum([x**2 for x in minErrVec])), 2)
#try: print " log(likelihood) = ", _tools.logl(mdl, dataset)
#except: pass
if targetModel.get_dimension() == mdl.get_dimension():
printer.log("frobenius distance to target = %s" % mdl.frobeniusdist(targetModel), 2)
#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)
#TODO: perhaps permute minErrVec using evTree to restore original circuit ordering
# but currently minErrVec isn't in such an intuitive format anyway (list of flattened gates)
# so maybe just drop minErrVec from return value entirely?
return minErrVec, mdl
def do_iterative_exlgst(
dataset, startModel, prepStrs, effectStrs, circuitSetsToUseInEstimation,
targetModel, guessModelForGauge=None, svdTruncateTo=None, maxiter=100000,
maxfev=None, tol=1e-6, regularizeFactor=0, returnErrorVec=False,
returnAll=False, circuitSetLabels=None, verbosity=0, comm=None,
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
startModel : Model
The Model used as a starting point for the least-squares
optimization.
prepStrs,effectStrs : list of Circuits
Fiducial Circuit lists used to construct a informationally complete
preparation and measurement.
circuitSetsToUseInEstimation : list of lists of (tuples or Circuits)
The i-th element is a list of the operation sequences to be used in the i-th iteration
of extended-LGST. Each element of these lists is a operation sequence, specifed as
either a Circuit object or as a tuple of operation labels (but all must be specified
using the same type).
e.g. [ [ (), ('Gx',) ], [ (), ('Gx',), ('Gy',) ], [ (), ('Gx',), ('Gy',), ('Gx','Gy') ] ]
targetModel : Model
A model used to provide a guess for gauge in which LGST estimates
should be returned, and the ability to make sense of ("complile")
operation sequences.
guessModelForGauge : Model, optional
A model used to compute a gauge transformation that is applied to
the LGST estimates before they are returned.
Defaults to targetModel.
svdTruncateTo : int, optional
The Hilbert space dimension to truncate the operation matrices to using
a SVD to keep only the largest svdToTruncateTo singular values of
the I_tildle LGST matrix. 0 causes no truncation, and default is
`targetModel.dim`.
maxiter : int, optional
Maximum number of iterations in each of the chi^2 optimizations
maxfev : int, optional
Maximum number of function evaluations for each of the chi^2 optimizations
Defaults to maxiter
tol : float, optional
The tolerance for each of the chi^2 optimizations.
regularizeFactor : float, optional
Multiplicative prefactor of L2-like regularization term that penalizes model entries
which have absolute value greater than 1. When set to 0, no regularization is applied.
returnErrorVec : bool, optional
If True, return (errorVec, model), or (errorVecs, models) if
returnAll == True, instead of just the model or models.
returnAll : bool, optional
If True return a list of models (and errorVecs if returnErrorVec == True),
one per iteration, instead of the results from just the final iteration.
circuitSetLabels : list of strings, optional
An identification label for each of the operation sequence sets (used for displaying
progress). Must be the same length as circuitSetsToUseInEstimation.
verbosity : int, optional
How much detail to send to stdout.
comm : mpi4py.MPI.Comm, optional
When not None, an MPI communicator for distributing the computation
across multiple processors.
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
-------
model if returnAll == False and returnErrorVec == False
models if returnAll == True and returnErrorVec == False
(errorVec, model) if returnAll == False and returnErrorVec == True
(errorVecs, models) 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, model is the Model containing the final estimated gates.
In cases when returnAll == True, models and errorVecs are lists whose i-th elements are the
errorVec and model corresponding to the results of the i-th iteration.
"""
printer = _objs.VerbosityPrinter.build_printer(verbosity, comm)
# Parameter to add later??
# whenCannotEstimate : string
# What to do when a operation sequence 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 Circuits to lists of raw tuples since that's all we'll need
if len(circuitSetsToUseInEstimation) > 0 and \
len(circuitSetsToUseInEstimation[0]) > 0 and \
isinstance(circuitSetsToUseInEstimation[0][0], _objs.Circuit):
circuitLists = [[opstr.tup for opstr in gsList] for gsList in circuitSetsToUseInEstimation]
else:
circuitLists = circuitSetsToUseInEstimation
#Run extended eLGST iteratively on given sets of estimatable strings
elgstModels = []; minErrs = [] # for returnAll == True case
elgstModel = startModel.copy(); nIters = len(circuitLists)
with printer.progress_logging(1):
for (i, stringsToEstimate) in enumerate(circuitLists):
if stringsToEstimate is None or len(stringsToEstimate) == 0: continue
#printer.log('', 2) #newline if we have more info to print
extraMessages = ["(%s)" % circuitSetLabels[i]] if circuitSetLabels else []
printer.show_progress(i, nIters, prefix='--- Iterative eLGST: ',
suffix='; %s operation sequences ---' % len(stringsToEstimate),
verboseMessages=extraMessages)
minErr, elgstModel = do_exlgst(
dataset, elgstModel, stringsToEstimate, prepStrs, effectStrs,
targetModel, guessModelForGauge, svdTruncateTo, maxiter, maxfev,
tol, regularizeFactor, printer - 2, comm, check_jacobian)
if returnAll:
elgstModels.append(elgstModel)
minErrs.append(minErr)
if returnErrorVec:
return (minErrs, elgstModels) if returnAll else (minErr, elgstModel)
else:
return elgstModels if returnAll else elgstModel
###################################################################################
# Minimum-Chi2 GST (MC2GST)
##################################################################################
def do_mc2gst(dataset, startModel, circuitsToUse,
maxiter=100000, maxfev=None, fditer=0, tol=1e-6,
cptp_penalty_factor=0, spam_penalty_factor=0,
minProbClipForWeighting=1e-4,
probClipInterval=(-1e6, 1e6), useFreqWeightedChiSq=False,
regularizeFactor=0, verbosity=0, check=False,
check_jacobian=False, circuitWeights=None,
opLabelAliases=None, memLimit=None, comm=None,
distributeMethod="deriv", profiler=None,
evaltree_cache=None, time_dependent=False):
"""
Performs Least-Squares Gate Set Tomography on the dataset.
Parameters
----------
dataset : DataSet
The dataset to obtain counts from.
startModel : Model
The Model used as a starting point for the least-squares
optimization.
circuitsToUse : list of (tuples or Circuits)
Each tuple contains operation labels and specifies a operation sequence 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 chi^2 optimization.
maxfev : int, optional
Maximum number of function evaluations for the chi^2 optimization.
Defaults to maxiter.
fditer : int, optional
The number of iterations to perform with a finite-difference-Jacobian,
as opposed to the more precise "analytic" Jacobian. Useful if the
optimization's starting point is special/singular.
tol : float or dict, optional
The tolerance for the chi^2 optimization. If a dict, allowed keys are
`'relx'`, `'relf'`, `'f'`, `'jac'`, and `'maxdx'`. If a float, then
`{'relx': 1e-8, 'relf': tol, 'f': 1.0, 'jac': tol, 'maxdx': 1.0 }` is used.
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 gates being optimized. This factor
multiplies these CPTP penalty terms.
spam_penalty_factor : float, optional
If greater than zero, the least squares optimization also contains SPAM penalty
terms which penalize non-positive-ness of the state preps being optimized. This
factor multiplies these SPAM penalty terms.
minProbClipForWeighting : float, optional
Sets the minimum and maximum probability p allowed in the chi^2 weights: N/(p*(1-p))