/
testSpamVecs.py
330 lines (255 loc) · 11.6 KB
/
testSpamVecs.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
import unittest
import pygsti
import numpy as np
import pickle
from numpy.random import random,seed
from pygsti.objects import SPAMVec, DenseSPAMVec
import pygsti.construction as pc
from ..testutils import BaseTestCase, compare_files, temp_files
class SPAMVecTestCase(BaseTestCase):
def setUp(self):
super(SPAMVecTestCase, self).setUp()
self.spamvec = DenseSPAMVec(np.array([1,0]))
def test_slice(self):
self.spamvec[:]
def test_bad_vec(self):
bad_vecs = [
'akdjsfaksdf',
[[], [1, 2]],
[[[]], [[1, 2]]]
]
for bad_vec in bad_vecs:
with self.assertRaises(ValueError):
SPAMVec.convert_to_vector(bad_vec)
def test_base_spamvec(self):
raw = pygsti.objects.SPAMVec(4)
with self.assertRaises(NotImplementedError):
raw.toarray()
with self.assertRaises(NotImplementedError):
raw.transform(None,None)
with self.assertRaises(NotImplementedError):
raw.depolarize(None)
with self.assertRaises(ValueError):
pygsti.objects.SPAMVec.convert_to_vector(0.0) # something with no len()
def test_methods(self):
v = np.ones((4,1),'d')
v_tp = np.zeros((4,1),'d'); v_tp[0] = 1.0/np.sqrt(2); v_tp[3] = 1.0/np.sqrt(2) - 0.05
v_id = np.zeros((4,1),'d'); v_id[0] = 1.0/np.sqrt(2)
povm = pygsti.obj.UnconstrainedPOVM( [('0',pygsti.obj.FullyParameterizedSPAMVec(v))] )
tppovm = pygsti.obj.TPPOVM( [('0',pygsti.obj.FullyParameterizedSPAMVec(v)),
('1',pygsti.obj.FullyParameterizedSPAMVec(v_id-v))] )
compSV = tppovm['1'] #complement POVM
self.assertTrue(isinstance(compSV,pygsti.obj.ComplementSPAMVec))
vecs = [ pygsti.obj.FullyParameterizedSPAMVec(v),
pygsti.obj.TPParameterizedSPAMVec(v_tp),
pygsti.obj.CPTPParameterizedSPAMVec(v_tp, "pp"),
pygsti.obj.StaticSPAMVec(v),
compSV,
pygsti.obj.TensorProdSPAMVec("prep", [pygsti.obj.FullyParameterizedSPAMVec(v),
pygsti.obj.FullyParameterizedSPAMVec(v)]),
pygsti.obj.TensorProdSPAMVec("effect", [povm], ['0'])
]
with self.assertRaises(ValueError):
pygsti.obj.TensorProdSPAMVec("foobar",
[pygsti.obj.FullyParameterizedSPAMVec(v),
pygsti.obj.FullyParameterizedSPAMVec(v)])
for sv in vecs:
print("Testing %s spam vec -------------- " % type(sv))
try:
Np = sv.num_params()
except NotImplementedError:
Np = 0 # OK, b/c complement spam vec isn't a true spamvec...
sv.size
sv_str = str(sv)
try:
deriv = sv.deriv_wrt_params()
except NotImplementedError:
pass #OK - some not implemented yet... (like TensorProdSPAMVec)
if Np > 0:
try:
deriv = sv.deriv_wrt_params([0])
except NotImplementedError:
pass #OK - some not implemented yet...
if sv.has_nonzero_hessian():
try:
sv.hessian_wrt_params()
sv.hessian_wrt_params([0])
sv.hessian_wrt_params([0],[0])
except NotImplementedError:
pass #OK for NOW -- later this should always be implemented when there's a nonzero hessian!!
sv.frobeniusdist2(sv,"prep")
sv.frobeniusdist2(sv,"effect")
with self.assertRaises(ValueError):
sv.frobeniusdist2(sv,"foobar")
sv2 = sv.copy()
try:
vec = sv.to_vector()
sv2.from_vector(vec)
except ValueError:
assert(isinstance(sv, pygsti.obj.TensorProdSPAMVec)) # OK for TensorProd case
except NotImplementedError:
pass # Complement spam vec doesn't support to_vector
T = pygsti.objects.FullGaugeGroupElement(
np.array( [ [0,1],
[1,0] ], 'd') )
T2 = pygsti.objects.UnitaryGaugeGroupElement(
np.array( [ [1,0],
[0,1] ], 'd') )
try:
sv.transform(T,"prep")
sv.transform(T,"effect")
except ValueError: pass #OK, as this is unallowed for some gate types
except NotImplementedError: pass #also OK, as this signifies derived class doesn't even implement it
try:
sv.transform(T2, "prep")
sv.transform(T2, "effect")
except ValueError: pass #OK, as this is unallowed for some gate types
except NotImplementedError: pass #also OK, as this signifies derived class doesn't even implement it
try:
with self.assertRaises(ValueError):
sv.transform(T,"foobar") #invalid type
except NotImplementedError: pass #also OK
try:
sv.depolarize(0.05)
except ValueError: pass #OK, as this is unallowed for some gate types
except NotImplementedError: pass #also OK, as this signifies derived class doesn't even implement it
try:
sv.set_value( np.zeros( (sv.dim,1), 'd') )
except ValueError:
pass #OK - some don't allow setting value
def test_convert(self):
v_tp = np.zeros((4,1),'d'); v_tp[0] = 1.0/np.sqrt(2); v_tp[3] = 1.0/np.sqrt(2) - 0.05
s = pygsti.obj.FullyParameterizedSPAMVec(v_tp)
for toType in ("full","TP","CPTP","static"):
s2 = pygsti.objects.spamvec.convert(s, toType, "pp")
pygsti.objects.spamvec.convert(s2, toType, "pp") #no conversion necessary
ssv = pygsti.obj.StaticSPAMVec(v_tp)
pygsti.objects.spamvec.optimize_spamvec(ssv, s) #test opt of static spamvec (nothing to do)
def test_cptp_spamvec(self):
vec = pygsti.obj.CPTPParameterizedSPAMVec([1/np.sqrt(2),0,0,1/np.sqrt(2) - 0.1], "pp")
print(vec)
print(vec.base.shape)
v = vec.to_vector()
vec.from_vector(v)
print(v)
print(vec)
vec_std = pygsti.change_basis(vec,"pp","std")
print(vec_std)
def analyze(spamvec):
stdmx = pygsti.vec_to_stdmx(spamvec, "pp")
evals = np.linalg.eigvals(stdmx)
#print(evals)
assert( np.all(evals > -1e-10) )
assert( np.linalg.norm(np.imag(evals)) < 1e-8)
return np.real(evals)
print( analyze(vec) )
pygsti.objects.spamvec.check_deriv_wrt_params(vec)
seed(1234)
#Nice cases - when parameters are small
nRandom = 1000
for randvec in random((nRandom,4)):
r = 2*(randvec-0.5)
vec.from_vector(r)
evs = analyze(vec)
pygsti.objects.spamvec.check_deriv_wrt_params(vec)
#print(r, "->", evs)
print("OK1")
#Mean cases - when parameters are large
nRandom = 1000
for randvec in random((nRandom,4)):
r = 10*(randvec-0.5)
vec.from_vector(r)
evs = analyze(vec)
pygsti.objects.spamvec.check_deriv_wrt_params(vec)
#print(r, "->", evs)
print("OK2")
vec.depolarize(0.01)
vec.depolarize((0.1,0.09,0.08))
#TODO
def test_complement_spamvec(self):
gateset = pygsti.construction.build_gateset(
[2], [('Q0',)],['Gi','Gx','Gy'],
[ "I(Q0)","X(pi/8,Q0)", "Y(pi/8,Q0)"])
E0 = gateset.povms['Mdefault']['0']
E1 = gateset.povms['Mdefault']['1']
Ec = pygsti.obj.ComplementSPAMVec(
pygsti.construction.build_identity_vec([2],"pp"),
[E0])
print(Ec.gpindices)
#Test TPPOVM which uses a complement evec
gateset.povms['Mtest'] = pygsti.obj.TPPOVM( [('+',E0),('-',E1)] )
E0 = gateset.povms['Mtest']['+']
Ec = gateset.povms['Mtest']['-']
v = gateset.to_vector()
gateset.from_vector(v)
#print(Ec.num_params()) #not implemented for complement vecs - only for POVM
identity = np.array([[np.sqrt(2)], [0], [0], [0]],'d')
print("TEST1")
print(E0)
print(Ec)
print(E0 + Ec)
self.assertArraysAlmostEqual(E0+Ec, identity)
#TODO: add back if/when we can set parts of a POVM directly...
#print("TEST2")
#gateset.effects['E0'] = [1/np.sqrt(2), 0, 0.4, 0.6]
#print(gateset.effects['E0'])
#print(gateset.effects['E1'])
#print(gateset.effects['E0'] + gateset.effects['E1'])
#self.assertArraysAlmostEqual(gateset.effects['E0'] + gateset.effects['E1'], identity)
#
#print("TEST3")
#gateset.effects['E0'][0,0] = 1.0 #uses dirty processing
#gateset._update_paramvec(gateset.effects['E0'])
#print(gateset.effects['E0'])
#print(gateset.effects['E1'])
#print(gateset.effects['E0'] + gateset.effects['E1'])
#self.assertArraysAlmostEqual(gateset.effects['E0'] + gateset.effects['E1'], identity)
def test_povms(self):
gateset = pygsti.construction.build_gateset(
[2], [('Q0',)],['Gi'], ["I(Q0)"])
gateset2Q = pygsti.construction.build_gateset(
[4], [('Q0','Q1')],['Gi'], ["I(Q0)"])
povm = gateset.povms['Mdefault'].copy()
E0 = povm['0']
E1 = povm['1']
gateset.povms['Munconstrained'] = povm # so gpindices get setup
with self.assertRaises(ValueError):
pygsti.obj.povm.convert(povm, "foobar", gateset.basis)
with self.assertRaises(ValueError):
pygsti.obj.UnconstrainedPOVM( "NotAListOrDict" )
povm['0'] = E0 # assignment
tp_povm = pygsti.obj.povm.convert(povm, "TP", gateset.basis)
tp_povm['0'] = E0 # ok
with self.assertRaises(KeyError):
tp_povm['1'] = E0 # can't assign complement vector
gateset.povms['Mtp'] = tp_povm # so gpindices get setup
factorPOVMs = [povm, povm.copy()]
tensor_povm = pygsti.obj.TensorProdPOVM( factorPOVMs )
gateset2Q.povms['Mtensor'] = tensor_povm # so gpindices get setup
for i,p in enumerate([povm, tp_povm, tensor_povm]):
print("Testing POVM of type ", type(p))
Nels = p.num_elements()
cpy = p.copy()
s = str(p)
s = pickle.dumps(p)
x = pickle.loads(s)
T = pygsti.objects.FullGaugeGroupElement(
np.array( [ [0,1],
[1,0] ], 'd') )
v = p.to_vector()
p.from_vector(v)
v = gateset.to_vector() if i < 2 else gateset2Q.to_vector()
effects = p.compile_effects(prefix="ABC")
for Evec in effects.values():
print("inds = ",Evec.gpindices, len(v))
Evec.from_vector(v[Evec.gpindices]) # gpindices should be setup relative to GateSet's param vec
try:
p.transform(T)
except ValueError:
pass #OK - tensorprod doesn't allow transform for instance
try:
p.depolarize(0.01)
except ValueError:
pass #OK - tensorprod doesn't allow transform for instance
if __name__ == '__main__':
unittest.main(verbosity=2)