/
gateset.py
3232 lines (2673 loc) · 132 KB
/
gateset.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
""" Defines the GateSet class and supporting functionality."""
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 as _scipy
import itertools as _itertools
import collections as _collections
import warnings as _warnings
import time as _time
import bisect as _bisect
from ..tools import matrixtools as _mt
from ..tools import gatetools as _gt
from ..tools import slicetools as _slct
from ..tools import likelihoodfns as _lf
from ..tools import jamiolkowski as _jt
from ..tools import compattools as _compat
from ..tools import basistools as _bt
from ..tools import listtools as _lt
from . import gatesetmember as _gm
from . import gatestring as _gs
from . import gate as _gate
from . import spamvec as _sv
from . import povm as _povm
from . import instrument as _instrument
from . import labeldicts as _ld
from . import gaugegroup as _gg
from .gatematrixcalc import GateMatrixCalc as _GateMatrixCalc
#from .gatemapcalc import GateMapCalc as _GateMapCalc
from ..baseobjs import VerbosityPrinter as _VerbosityPrinter
from ..baseobjs import Basis as _Basis
class GateSet(object):
"""
Encapsulates a set of gate, state preparation, and POVM effect operations.
A GateSet stores a set of labeled Gate objects and provides dictionary-like
access to their matrices. State preparation and POVM effect operations are
represented as column vectors.
"""
#Whether access to gates & spam vecs via GateSet indexing is allowed
_strict = False
#Whether to perform extra parameter-vector integrity checks
_pcheck = False
def __init__(self, default_param="full",
prep_prefix="rho", effect_prefix="E", gate_prefix="G",
povm_prefix="M", instrument_prefix="I"):
"""
Initialize a gate set.
Parameters
----------
default_param : {"full", "TP", "static"}, optional
Specifies the default gate and SPAM vector parameterization type.
"full" : by default gates and vectors are fully parameterized.
"TP" : by default the first row of gates and the first element of
vectors is not parameterized and fixed so gate set is trace-
preserving.
"static" : by default gates and vectors are not parameterized.
prep_prefix, effect_prefix, gate_prefix,
povm_prefix, instrument_prefix : string, optional
Key prefixes designating state preparations, POVM effects,
gates, POVM, and instruments respectively. These prefixes allow
the GateSet to determine what type of object a key corresponds to.
"""
assert(default_param in ('full','TP','static'))
#default_e_param = "full" if default_param == "TP" else default_param
#Gate dimension of this GateSet (None => unset, to be determined)
self._dim = None
#Name and dimension (or list of dims) of the *basis*
# that the gates and SPAM vectors are expressed in. This
# is for interpretational purposes only, and is reset often
# (for instance, when reading GateSet params from a vector)
self.reset_basis()
#SPAM vectors
self.preps = _ld.OrderedMemberDict(self, default_param, prep_prefix, "spamvec")
self.povms = _ld.OrderedMemberDict(self, default_param, povm_prefix, "povm")
self.effects_prefix = effect_prefix
#self.effects = _ld.OrderedMemberDict(self, default_e_param, effect_prefix, "spamvec")
#SPAM labels: key = label, value = (prepLabel, effectLabel)
#self.spamdefs = _ld.OrderedSPAMLabelDict('remainder')
#Gates
self.gates = _ld.OrderedMemberDict(self, default_param, gate_prefix, "gate")
self.instruments = _ld.OrderedMemberDict(self, default_param, instrument_prefix, "instrument")
self._default_gauge_group = None
self._calcClass = _GateMatrixCalc
#self._calcClass = _GateMapCalc
self._paramvec = _np.zeros(0, 'd')
self._rebuild_paramvec()
super(GateSet, self).__init__()
@property
def default_gauge_group(self):
"""
Gets the default gauge group for performing gauge
transformations on this GateSet.
"""
return self._default_gauge_group
@default_gauge_group.setter
def default_gauge_group(self, value):
self._default_gauge_group = value
@property
def dim(self):
"""
The dimension of the gateset, which equals d when the gate
matrices have shape d x d and spam vectors have shape d x 1.
Returns
-------
int
gateset dimension
"""
return self._dim
def get_dimension(self):
"""
Get the dimension of the gateset, which equals d when the gate
matrices have shape d x d and spam vectors have shape d x 1.
Equivalent to gateset.dim.
Returns
-------
int
gateset dimension
"""
return self._dim
@property
def prep(self):
"""
The unique state preparation in this gateset, if one exists. If not,
a ValueError is raised.
"""
if len(self.preps) != 1:
raise ValueError("'.prep' can only be used on gate sets" +
" with a *single* state prep. This GateSet has" +
" %d state preps!" % len(self.preps))
return list(self.preps.values())[0]
@property
def effects(self):
"""
The unique POVM in this gateset, if one exists. If not,
a ValueError is raised.
"""
if len(self.povms) != 1:
raise ValueError("'.effects' can only be used on gate sets" +
" with a *single* POVM. This GateSet has" +
" %d POVMS!" % len(self.povms))
return list(self.povms.values())[0]
def get_basis_name(self):
""" DEPRECATED: use `<this object>.basis.name` instead. """
_warnings.warn('gs.get_basis_name() is deprecated. ' + \
'Use gs.basis.name instead.')
return self.basis.name
def get_basis_dimension(self):
""" DEPRECATED: use `<this object>.basis.dim.dmDim` instead. """
_warnings.warn('gs.get_basis_dimension() is deprecated. ' + \
'Use gs.basis.dim.dmDim (same functionality) or gs.basis.dim.blockDims (full blockDims) instead')
return self.basis.dim.dmDim
def set_basis(self, name, dimension):
""" DEPRECATED: use `<this object>.basis = Basis(...) instead. """
_warnings.warn('gs.set_basis() is deprecated. ' + \
'Use gs.basis = Basis({}, {}) ' + \
'(or another method of basis construction, ' + \
'like gs.basis = Basis([(\'std\', 2), (\'gm\', 2)])) ' + \
'instead.'.format(name, dimension))
self.basis = _Basis(name, dimension)
def reset_basis(self):
"""
"Forgets" the basis name and dimension by setting
these quantities to "unkown" and None, respectively.
"""
self.basis = _Basis('unknown', None)
def get_prep_labels(self):
"""
DEPRECATED. Get the labels of state preparation vectors.
Returns
-------
list of strings
"""
assert(False),"Deprecated!"
#return list(self.preps.keys())
def get_effect_labels(self):
"""
DEPRECATED. Get all the effect vector labels.
Returns
-------
list of strings
"""
assert(False),"Deprecated!"
#return list(self.effects.keys())
def get_preps(self):
"""
DEPRECATED.
Get an list of all the state prepartion vectors. These
vectors are copies of internally stored data and thus
can be modified without altering the gateset.
Returns
-------
list of numpy arrays
list of state preparation vectors of shape (dim, 1).
"""
assert(False),"Deprecated!"
#return [ self.preps[l].copy() for l in self.get_prep_labels() ]
def get_effects(self):
"""
DEPRECATED.
Get an list of all the POVM effect vectors. This list will include
the "compliment" effect vector at the end of the list if one has been
specified. Also, the returned vectors are copies of internally stored
data and thus can be modified without altering the gateset.
Returns
-------
list of numpy arrays
list of POVM effect vectors of shape (dim, 1).
"""
assert(False),"Deprecated!"
#return [ self.effects[l].copy() for l in self.get_effect_labels() ]
def num_preps(self):
"""
DEPRECATED. Get the number of state preparation vectors
Returns
-------
int
"""
assert(False),"Deprecated!"
#return len(self.preps)
def num_effects(self):
"""
DEPRECATED. Get the number of effect vectors.
Returns
-------
int
"""
assert(False),"Deprecated!"
#return len(self.effects)
def get_reverse_spam_defs(self):
"""
Get a reverse-lookup dictionary for spam labels.
Returns
-------
OrderedDict
a dictionary with keys == (prepLabel,effectLabel) tuples and
values == SPAM labels.
"""
assert(False),"Deprecated!"
#d = _collections.OrderedDict()
#for label in self.spamdefs:
# d[ self.spamdefs[label] ] = label
#return d
def get_spam_labels(self):
"""
Get a list of all the spam labels.
Returns
-------
list of strings
"""
assert(False),"Deprecated!"
#return list(self.spamdefs.keys())
def get_spamgate(self, spamLabel):
"""
Construct the SPAM gate associated with
a given spam label.
Parameters
----------
spamLabel : str
the spam label to construct a "spam gate" for.
Returns
-------
numpy array
"""
assert(False),"Deprecated!"
#return self._calc()._make_spamgate(spamLabel)
def __setitem__(self, label, value):
"""
Set a Gate or SPAM vector associated with a given label.
Parameters
----------
label : string
the gate or SPAM vector label.
value : numpy array or Gate or SPAMVec
a gate matrix, SPAM vector, or object, which must have the
appropriate dimension for the GateSet and appropriate type
given the prefix of the label.
"""
if GateSet._strict:
raise KeyError("Strict-mode: invalid key %s" % label)
if label.startswith(self.preps._prefix):
self.preps[label] = value
elif label.startswith(self.povms._prefix):
self.povms[label] = value
#elif label.startswith(self.effects._prefix):
# self.effects[label] = value
elif label.startswith(self.gates._prefix):
self.gates[label] = value
elif label.startswith(self.instruments._prefix):
self.instruments[label] = value
else:
raise KeyError("Key %s has an invalid prefix" % label)
def __getitem__(self, label):
"""
Get a Gate or SPAM vector associated with a given label.
Parameters
----------
label : string
the gate or SPAM vector label.
"""
if GateSet._strict:
raise KeyError("Strict-mode: invalid key %s" % label)
if label.startswith(self.preps._prefix):
return self.preps[label]
elif label.startswith(self.povms._prefix):
return self.povms[label]
#elif label.startswith(self.effects._prefix):
# return self.effects[label]
elif label.startswith(self.gates._prefix):
return self.gates[label]
elif label.startswith(self.instruments._prefix):
return self.instruments[label]
else:
raise KeyError("Key %s has an invalid prefix" % label)
def set_all_parameterizations(self, parameterization_type):
"""
Convert all gates and SPAM vectors to a specific parameterization
type.
Parameters
----------
parameterization_type : {"full", "TP", "CPTP", "H+S", "S", "static"}
The gate and SPAM vector parameterization type:
"""
typ = parameterization_type
assert(parameterization_type in ('full','TP','CPTP','H+S','S','static'))
rtyp = "TP" if typ in ("CPTP","H+S","S") else typ
#rtyp = "CPTP" if typ in ("H+S","S") else typ #TESTING, but CPTP spamvec still unreliable
povmtyp = rtyp
ityp = "TP" if typ in ("TP","CPTP","H+S","S") else typ
basis = self.basis
for lbl,gate in self.gates.items():
self.gates[lbl] = _gate.convert(gate, typ, basis)
for lbl,inst in self.instruments.items():
self.instruments[lbl] = _instrument.convert(inst, ityp, basis)
for lbl,vec in self.preps.items():
self.preps[lbl] = _sv.convert(vec, rtyp, basis)
for lbl,povm in self.povms.items():
self.povms[lbl] = _povm.convert(povm, povmtyp, basis)
if typ == 'full':
self.default_gauge_group = _gg.FullGaugeGroup(self.dim)
elif typ == 'TP':
self.default_gauge_group = _gg.TPGaugeGroup(self.dim)
elif typ == 'CPTP':
self.default_gauge_group = _gg.UnitaryGaugeGroup(self.dim, basis)
else: # typ in ('static','H+S','S')
self.default_gauge_group = _gg.TrivialGaugeGroup(self.dim)
#def __getstate__(self):
# #Returns self.__dict__ by default, which is fine
def __setstate__(self, stateDict):
if "effects" in stateDict:
#unpickling an OLD-version GateSet - like a re-__init__
#print("DB: UNPICKLING AN OLD GATESET"); print("Keys = ",stateDict.keys())
default_param = "full"
self.preps = _ld.OrderedMemberDict(self, default_param, "rho", "spamvec")
self.povms = _ld.OrderedMemberDict(self, default_param, "M", "povm")
self.effects_prefix = 'E'
self.gates = _ld.OrderedMemberDict(self, default_param, "G", "gate")
self.instruments = _ld.OrderedMemberDict(self, default_param, "I", "instrument")
self._paramvec = _np.zeros(0, 'd')
self._rebuild_paramvec()
self._dim = stateDict['_dim']
self._calcClass = stateDict.get('_calcClass',_GateMatrixCalc)
self._default_gauge_group = stateDict['_default_gauge_group']
self.basis = stateDict.get('basis', _Basis('unknown', None))
if self.basis.name == "unknown" and '_basisNameAndDim' in stateDict:
self.basis = _Basis(stateDict['_basisNameAndDim'][0],
stateDict['_basisNameAndDim'][1])
assert(len(stateDict['preps']) <= 1), "Cannot convert GateSets with multiple preps!"
for lbl,gate in stateDict['gates'].items(): self.gates[lbl] = gate
for lbl,vec in stateDict['preps'].items(): self.preps[lbl] = vec
effect_vecs = []; remL = stateDict['_remainderlabel']
comp_lbl = None
for sl,(prepLbl,ELbl) in stateDict['spamdefs'].items():
assert((prepLbl,ELbl) != (remL,remL)), "Cannot convert sum-to-one spamlabel!"
if ELbl == remL: comp_lbl = str(sl)
else: effect_vecs.append( (str(sl), stateDict['effects'][ELbl]) )
if comp_lbl is not None:
comp_vec = stateDict['_povm_identity'] - sum([v for sl,v in effect_vecs])
effect_vecs.append( (comp_lbl, comp_vec) )
self.povms['Mdefault'] = _povm.TPPOVM(effect_vecs)
else:
self.povms['Mdefault'] = _povm.UnconstrainedPOVM(effect_vecs)
else:
self.__dict__.update(stateDict)
#Additionally, must re-connect this gateset as the parent
# of relevant OrderedDict-derived classes, which *don't*
# preserve this information upon pickling so as to avoid
# circular pickling...
self.preps.parent = self
self.povms.parent = self
#self.effects.parent = self
self.gates.parent = self
self.instruments.parent = self
for o in self.preps.values(): o._parent = self
for o in self.povms.values(): o._parent = self
#for o in self.effects.values(): o._parent = self
for o in self.gates.values(): o._parent = self
for o in self.instruments.values(): o._parent = self
def num_params(self):
"""
Return the number of free parameters when vectorizing
this gateset.
Returns
-------
int
the number of gateset parameters.
"""
return len(self._paramvec)
def num_elements(self):
"""
Return the number of total gate matrix and spam vector
elements in this gateset. This is in general different
from the number of *parameters* in the gateset, which
are the number of free variables used to generate all of
the matrix and vector *elements*.
Returns
-------
int
the number of gateset elements.
"""
rhoSize = [ rho.size for rho in self.preps.values() ]
povmSize = [ povm.num_elements() for povm in self.povms.values() ]
gateSize = [ gate.size for gate in self.gates.values() ]
instSize = [ i.num_elements() for i in self.instruments.values() ]
return sum(rhoSize) + sum(povmSize) + sum(gateSize) + sum(instSize)
def num_nongauge_params(self):
"""
Return the number of non-gauge parameters when vectorizing
this gateset according to the optional parameters.
Returns
-------
int
the number of non-gauge gateset parameters.
"""
return self.num_params() - self.num_gauge_params()
def num_gauge_params(self):
"""
Return the number of gauge parameters when vectorizing
this gateset according to the optional parameters.
Returns
-------
int
the number of gauge gateset parameters.
"""
dPG = self._calc()._buildup_dPG()
gaugeDirs = _mt.nullspace_qr(dPG) #cols are gauge directions
return _np.linalg.matrix_rank(gaugeDirs[0:self.num_params(),:])
def _check_paramvec(self, debug=False):
if debug: print("---- GateSet._check_paramvec ----")
TOL=1e-8
for lbl,obj in self.iter_objs():
if debug: print(lbl,":",obj.num_params(),obj.gpindices)
w = obj.to_vector()
msg = "None" if (obj.parent is None) else id(obj.parent)
assert(obj.parent is self), "%s's parent is not set correctly (%s)!" % (lbl,msg)
if obj.gpindices is not None and len(w) > 0:
if _np.linalg.norm(self._paramvec[obj.gpindices]-w) > TOL:
raise ValueError("%s is out of sync with paramvec!!!" % lbl)
def _clean_paramvec(self):
""" Updates _paramvec corresponding to any "dirty" elements, which may
have been modified without out knowing, leaving _paramvec out of
sync with the element's internal data. It *may* be necessary
to resolve conflicts where multiple dirty elements want different
values for a single parameter. This method is used as a safety net
that tries to insure _paramvec & GateSet elements are consistent
before their use."""
dirty = False; TOL=1e-8
for _,obj in self.iter_objs():
if obj.dirty:
w = obj.to_vector()
if _np.linalg.norm(self._paramvec[obj.gpindices]-w) > TOL:
self._paramvec[obj.gpindices] = w; dirty = True
if dirty:
#re-update everything to ensure consistency
#print("DEBUG: non-trivailly CLEANED paramvec due to dirty elements")
self.from_vector(self._paramvec,False)
if GateSet._pcheck: self._check_paramvec()
def _update_paramvec(self, modified_obj=None):
"""Updates self._paramvec after a member of this GateSet is modified"""
self._rebuild_paramvec() # prepares _paramvec & gpindices
#update parameters changed by modified_obj
self._paramvec[modified_obj.gpindices] = modified_obj.to_vector()
#re-initialze any members that also depend on the updated parameters
modified_indices = set(modified_obj.gpindices_as_array())
for _,obj in self.iter_objs():
if obj is modified_obj: continue
if modified_indices.intersection(obj.gpindices_as_array()):
obj.from_vector(self._paramvec[obj.gpindices])
def _rebuild_paramvec(self):
""" Resizes self._paramvec and updates gpindices & parent members as needed,
and will initialize new elements of _paramvec, but does NOT change
existing elements of _paramvec (use _update_paramvec for this)"""
v = self._paramvec; Np = self.num_params()
off = 0; shift = 0
#ellist = ", ".join(list(self.preps.keys()) +list(self.povms.keys()) +list(self.gates.keys()))
#print("DEBUG: rebuilding... %s" % ellist)
#Step 1: remove any unused indices from paramvec and shift accordingly
used_gpindices = set()
for _,obj in self.iter_objs():
if obj.gpindices is not None:
assert(obj.parent is self), "Member's parent is not set correctly!"
used_gpindices.update( obj.gpindices_as_array() )
else:
assert(obj.parent is self or obj.parent is None)
#Note: ok for objects to have parent == None if their gpindices is also None
indices_to_remove = sorted(set(range(Np)) - used_gpindices)
if len(indices_to_remove) > 0:
#print("DEBUG: Removing %d params:" % len(indices_to_remove), indices_to_remove)
v = _np.delete(v, indices_to_remove)
get_shift = lambda j: _bisect.bisect_left(indices_to_remove, j)
memo = set() #keep track of which object's gpindices have been set
for lbl,obj in self.iter_objs():
if obj.gpindices is not None:
if id(obj) in memo: continue #already processed
if isinstance(obj.gpindices, slice):
new_inds = _slct.shift(obj.gpindices,
-get_shift(obj.gpindices.start))
else:
new_inds = []
for i in obj.gpindices:
new_inds.append(i - get_shift(i))
new_inds = _np.array(new_inds,'i')
obj.set_gpindices( new_inds, self, memo)
# Step 2: add parameters that don't exist yet
memo = set() #keep track of which object's gpindices have been set
for _,obj in self.iter_objs():
if shift > 0 and obj.gpindices is not None:
if isinstance(obj.gpindices, slice):
obj.set_gpindices(_slct.shift(obj.gpindices, shift), self, memo)
else:
obj.set_gpindices(obj.gpindices+shift, self, memo) #works for integer arrays
if obj.gpindices is None or obj.parent is not self:
#Assume all parameters of obj are new independent parameters
num_new_params = obj.allocate_gpindices( off, self )
objvec = obj.to_vector() #may include more than "new" indices
new_local_inds = _gm._decompose_gpindices(obj.gpindices, slice(off,off+num_new_params))
assert(len(objvec[new_local_inds]) == num_new_params)
v = _np.insert(v, off, objvec[new_local_inds])
#print("objvec len = ",len(objvec), "num_new_params=",num_new_params," gpinds=",obj.gpindices," loc=",new_local_inds)
#obj.set_gpindices( slice(off, off+obj.num_params()), self )
#shift += obj.num_params()
#off += obj.num_params()
shift += num_new_params
off += num_new_params
#print("DEBUG: %s: alloc'd & inserted %d new params. indices = " % (lbl,obj.num_params()), obj.gpindices, " off=",off)
else:
inds = obj.gpindices_as_array()
M = max(inds) if len(inds)>0 else -1; L = len(v)
#print("DEBUG: %s: existing indices = " % (lbl), obj.gpindices, " M=",M," L=",L)
if M >= L:
#Some indices specified by obj are absent, and must be created.
w = obj.to_vector()
v = _np.concatenate((v, _np.empty(M+1-L,'d')),axis=0) # [v.resize(M+1) doesn't work]
shift += M+1-L
for ii,i in enumerate(inds):
if i >= L: v[i] = w[ii]
#print("DEBUG: --> added %d new params" % (M+1-L))
off = M+1
self._paramvec = v
#print("DEBUG: Done rebuild: %d params" % len(v))
def to_vector(self):
"""
Returns the gateset vectorized according to the optional parameters.
Returns
-------
numpy array
The vectorized gateset parameters.
"""
self._clean_paramvec()
return self._paramvec
def from_vector(self, v, reset_basis=True):
"""
The inverse of to_vector. Loads values of gates and rho and E vecs from
from the vector `v`. Note that `v` does not specify the number of
gates, etc., and their labels: this information must be contained in
this `GateSet` prior to calling `from_vector`. In practice, this just
means you should call the `from_vector` method using the same `GateSet`
that was used to generate the vector `v` in the first place.
"""
assert( len(v) == self.num_params() )
self._paramvec = v.copy()
for _,obj in self.iter_objs():
obj.from_vector( v[obj.gpindices] )
obj.dirty = False #object is known to be consistent with _paramvec
if reset_basis:
self.reset_basis()
# assume the vector we're loading isn't producing gates & vectors in
# a known basis.
if GateSet._pcheck: self._check_paramvec()
def deriv_wrt_params(self):
"""
Construct a matrix whose columns are the vectorized derivatives of all
the gateset's raw matrix and vector *elements* (placed in a vector)
with respect to each single gateset parameter.
Thus, each column has length equal to the number of elements in the
gateset, and there are num_params() columns. In the case of a "fully
parameterized gateset" (i.e. all gate matrices and SPAM vectors are
fully parameterized) then the resulting matrix will be the (square)
identity matrix.
Returns
-------
numpy array
2D array of derivatives.
"""
return self._calc().deriv_wrt_params()
def get_nongauge_projector(self, itemWeights=None, nonGaugeMixMx=None):
"""
Construct a projector onto the non-gauge parameter space, useful for
isolating the gauge degrees of freedom from the non-gauge degrees of
freedom.
Parameters
----------
itemWeights : dict, optional
Dictionary of weighting factors for individual gates and spam operators.
Keys can be gate, state preparation, POVM effect, spam labels, or the
special strings "gates" or "spam" whic represent the entire set of gate
or SPAM operators, respectively. Values are floating point numbers.
These weights define the metric used to compute the non-gauge space,
*orthogonal* the gauge space, that is projected onto.
nonGaugeMixMx : numpy array, optional
An array of shape (nNonGaugeParams,nGaugeParams) specifying how to
mix the non-gauge degrees of freedom into the gauge degrees of
freedom that are projected out by the returned object. This argument
essentially sets the off-diagonal block of the metric used for
orthogonality in the "gauge + non-gauge" space. It is for advanced
usage and typically left as None (the default).
.
Returns
-------
numpy array
The projection operator as a N x N matrix, where N is the number
of parameters (obtained via num_params()). This projector acts on
parameter-space, and has rank equal to the number of non-gauge
degrees of freedom.
"""
return self._calc().get_nongauge_projector(itemWeights, nonGaugeMixMx)
def transform(self, S):
"""
Update each of the gate matrices G in this gateset with inv(S) * G * S,
each rhoVec with inv(S) * rhoVec, and each EVec with EVec * S
Parameters
----------
S : GaugeGroupElement
A gauge group element which specifies the "S" matrix
(and it's inverse) used in the above similarity transform.
"""
for rhoVec in self.preps.values():
rhoVec.transform(S,'prep')
for povm in self.povms.values():
povm.transform(S)
for gateObj in self.gates.values():
gateObj.transform(S)
for instrument in self.instruments.values():
instrument.transform(S)
self._clean_paramvec() #transform may leave dirty members
def _calc(self):
if not hasattr(self,"_calcClass"): #for backward compatibility
self._calcClass = _GateMatrixCalc
compiled_effects = _collections.OrderedDict()
for povm_lbl,povm in self.povms.items():
for k,e in povm.compile_effects(povm_lbl).items():
compiled_effects[k] = e
compiled_gates = _collections.OrderedDict()
for k,g in self.gates.items(): compiled_gates[k] = g
for inst_lbl,inst in self.instruments.items():
for k,g in inst.compile_gates(inst_lbl).items():
compiled_gates[k] = g
return self._calcClass(self._dim, compiled_gates, self.preps,
compiled_effects, self._paramvec)
def split_gatestring(self, gatestring, erroron=('prep','povm')):
"""
Splits a gate string into prepLabel + gatesOnlyString + povmLabel
components. If `gatestring` does not contain a prep label or a
povm label a default label is returned if one exists.
Parameters
----------
gatestring : GateString
A gate string, possibly beginning with a state preparation
label and ending with a povm label.
erroron : tuple of {'prep','povm'}
A ValueError is raised if a preparation or povm label cannot be
resolved when 'prep' or 'povm' is included in 'erroron'. Otherwise
`None` is returned in place of unresolvable labels. An exception
is when this gateset has no preps or povms, in which case `None`
is always returned and errors are never raised, since in this
case one usually doesn't expect to use the GateSet to compute
probabilities (e.g. in germ selection).
Returns
-------
prepLabel : str or None
gatesOnlyString : GateString
povmLabel : str or None
"""
if len(gatestring) > 0 and gatestring[0] in self.preps:
prep_lbl = gatestring[0]
gatestring = gatestring[1:]
elif len(self.preps) == 1:
prep_lbl = list(self.preps.keys())[0]
else:
if 'prep' in erroron and len(self.preps) > 0:
raise ValueError("Cannot resolve state prep in %s" % gatestring)
else: prep_lbl = None
if len(gatestring) > 0 and gatestring[-1] in self.povms:
povm_lbl = gatestring[-1]
gatestring = gatestring[:-1]
elif len(self.povms) == 1:
povm_lbl = list(self.povms.keys())[0]
else:
if 'povm' in erroron and len(self.povms) > 0:
raise ValueError("Cannot resolve POVM in %s" % gatestring)
else: povm_lbl = None
return prep_lbl, gatestring, povm_lbl
def compile_gatestrings(self, gatestrings):
"""
Compiles a list of :class:`GateString`s.
Gate strings must be "compiled" before probabilities can be computed for
them. Each string corresponds to some number of "outcomes", indexed by an
"outcome label" that is a tuple of POVM-effect or instrument-element
labels like "0". Compiling creates maps between gate strings and their
outcomes and the structures used in probability computation (see return
values below).
Parameters
----------
gatestrings : list of GateStrings
The list to compile.
Returns
-------
raw_spamTuples_dict : collections.OrderedDict
A dictionary whose keys are raw gate sequences (containing just
"compiled" gates, i.e. not instruments), and whose values are
lists of (preplbl, effectlbl) tuples. The effectlbl names a
"compiled" effect vector; preplbl is just a prep label. Each tuple
corresponds to a single "final element" of the computation, e.g. a
probability. The ordering is important - and is why this needs to be
an ordered dictionary - when the lists of tuples are concatenated (by
key) the resulting tuple orderings corresponds to the final-element
axis of an output array that is being filled (computed).
elIndices : collections.OrderedDict
A dictionary whose keys are integer indices into `gatestrings` and
whose values are slices and/or integer-arrays into the space/axis of
final elements. Thus, to get the final elements corresponding to
`gatestrings[i]`, use `filledArray[ elIndices[i] ]`.
outcomes : collections.OrderedDict
A dictionary whose keys are integer indices into `gatestrings` and
whose values are lists of outcome labels (an outcome label is a tuple
of POVM-effect and/or instrument-element labels). Thus, to obtain
what outcomes the i-th gate strings's final elements
(`filledArray[ elIndices[i] ]`) correspond to, use `outcomes[i]`.
nTotElements : int
The total number of "final elements" - this is how big of an array
is need to hold all of the probabilities `gatestrings` generates.
"""
# gateset.compile -> odict[raw_gstr] = spamTuples, elementIndices, nElements
# dataset.compile -> outcomeLabels[i] = list_of_ds_outcomes, elementIndices, nElements
# compile all gsplaq strs -> elementIndices[(i,j)],
#Indexed by raw gate string
raw_spamTuples_dict = _collections.OrderedDict() # final
raw_gateOutcomes_dict = _collections.OrderedDict()
raw_offsets = _collections.OrderedDict()
#Indexed by parent index (an integer)
elIndicesByParent = _collections.OrderedDict() # final
outcomesByParent = _collections.OrderedDict() # final
# Helper dict: (rhoLbl,POVM_ELbl) -> (Elbl,) mapping
spamTupleToOutcome = { None : ("NONE",) } #Dummy label for placeholding (see resolveSPAM below)
for prep_lbl in self.preps:
for povm_lbl in self.povms:
for elbl in self.povms[povm_lbl]:
spamTupleToOutcome[ (prep_lbl, povm_lbl + "_" + elbl) ] = (elbl,)
def resolveSPAM(gatestring):
""" Determines spam tuples that correspond to gatestring
and strips any spam-related pieces off """
prep_lbl, gatestring, povm_lbl = \
self.split_gatestring(gatestring)
if prep_lbl is None or povm_lbl is None:
spamtups = [ None ] #put a single "dummy" spam-tuple placeholder
# so that there's a single "element" for each compiled string,
# which means that the usual "lookup" or "elIndices" will map
# original gatestring-list indices to compiled-string, i.e.,
# evalTree index, which is useful when computing products
# (often the case when a GateSet has no preps or povms,
# e.g. in germ selection)
else:
spamtups = [ (prep_lbl, povm_lbl + "_" + elbl)
for elbl in self.povms[povm_lbl]]
return gatestring, spamtups
def process(action,s,spamtuples,iParent=None,gate_outcomes=(),start=0):
"""
Implements recursive processing of a string. Separately
implements two different behaviors:
"add" : add entries to raw_spamTuples_dict and raw_gateOutcomes_dict
"index" : adds entries to elIndicesByParent and outcomesByParent
assuming that raw_spamTuples_dict and raw_gateOutcomes_dict
are already build (and won't be modified anymore).
"""
for i,gate_label in enumerate(s[start:],start=start):
if gate_label in self.instruments:
#we've found an instrument - recurse!
for inst_el_lbl in self.instruments[gate_label]:
compiled_el_lbl = gate_label + "_" + inst_el_lbl
process(action, s[0:i] + _gs.GateString((compiled_el_lbl,)) + s[i+1:],
spamtuples, iParent, gate_outcomes + (inst_el_lbl,), i+1)
break
else: #no instruments -- add "raw" gate string s
if s in raw_spamTuples_dict:
assert(gate_outcomes == raw_gateOutcomes_dict[s])
if action == "add":
raw_spamTuples_dict[s] = _lt.remove_duplicates(raw_spamTuples_dict[s] + spamtuples)
# Note: there should only be duplicates if there are duplicates in
# original `gatestring_list` - check this?
elif action == "index": # fill *ByParent dicts
assert(iParent is not None)
offset = raw_offsets[s]
all_spamtuples = raw_spamTuples_dict[s]
final_outcomes = [ spamTupleToOutcome[x] for x in spamtuples ]
my_spamTuple_indices = [ offset+all_spamtuples.index(x) for x in spamtuples ]
my_outcome_tuples = [ gate_outcomes + x for x in final_outcomes ]
for i,tup in zip(my_spamTuple_indices,my_outcome_tuples):
if i not in elIndicesByParent[iParent]: #don't duplicate existing indices
elIndicesByParent[iParent].append(i)
outcomesByParent[iParent].append(tup)
else: assert(tup in outcomesByParent) # pragma: no check
# double-check - could REMOVE for speed in future
else:
assert(action == "add") # s should have been added in "add" process!
raw_spamTuples_dict[s] = spamtuples
raw_gateOutcomes_dict[s] = gate_outcomes