/
spamvec.py
607 lines (482 loc) · 17.4 KB
/
spamvec.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
#*****************************************************************
# 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
#*****************************************************************
"""
Defines classes with represent SPAM operations, along with supporting
functionality.
"""
import numpy as _np
from ..tools import matrixtools as _mt
from protectedarray import ProtectedArray as _ProtectedArray
def convert(spamvec, toType):
"""
Convert SPAM vector to a new type of parameterization, potentially
creating a new SPAMVec object. Raises ValueError for invalid conversions.
Parameters
----------
spamvec : SPAMVec
SPAM vector to convert
toType : {"full","TP","static"}
The type of parameterizaton to convert to.
Returns
-------
SPAMVec
The converted SPAM vector, usually a distinct
object from the object passed as input.
"""
if toType == "full":
if isinstance(spamvec, FullyParameterizedSPAMVec):
return spamvec #no conversion necessary
else:
return FullyParameterizedSPAMVec( spamvec )
elif toType == "TP":
if isinstance(spamvec, TPParameterizedSPAMVec):
return spamvec #no conversion necessary
else:
return TPParameterizedSPAMVec( spamvec )
# above will raise ValueError if conversion cannot be done
elif toType == "static":
if isinstance(spamvec, StaticSPAMVec):
return spamvec #no conversion necessary
else:
return StaticSPAMVec( spamvec )
else:
raise ValueError("Invalid toType argument: %s" % toType)
class SPAMVec(object):
"""
Excapulates a parameterization of a state preparation OR POVM effect
vector. This class is the common base class for all specific
parameterizations of a SPAM vector.
"""
def __init__(self, vec):
""" Initialize a new SPAM Vector """
self.base = vec
self.dim = len(vec)
def get_dimension(self):
""" Return the dimension of the gate matrix. """
return self.dim
#Handled by derived classes
#def __str__(self):
# s = "Spam vector with length %d\n" % len(self.base)
# s += _mt.mx_to_string(self.base, width=4, prec=2)
# return s
#Pickle plumbing
def __setstate__(self, state):
self.__dict__.update(state)
#Access to underlying array
def __getitem__( self, key ):
return self.base.__getitem__(key)
def __getslice__(self, i,j):
return self.__getitem__(slice(i,j)) #Called for A[:]
def __setitem__(self, key, val):
return self.base.__setitem__(key,val)
def __getattr__(self, attr):
#use __dict__ so no chance for recursive __getattr__
ret = getattr(self.__dict__['base'],attr)
if(self.base.shape != (self.dim,1)):
raise ValueError("Cannot change dimension of Vector")
return ret
#Mimic array
def __pos__(self): return self.base
def __neg__(self): return -self.base
def __abs__(self): return abs(self.base)
def __add__(self,x): return self.base + x
def __radd__(self,x): return x + self.base
def __sub__(self,x): return self.base - x
def __rsub__(self,x): return x - self.base
def __mul__(self,x): return self.base * x
def __rmul__(self,x): return x * self.base
def __div__(self,x): return self.base / x
def __rdiv__(self,x): return x / self.base
def __floordiv__(self,x): return self.base // x
def __pow__(self,x): return self.base ** x
def __eq__(self,x): return self.base == x
def __len__(self): return len(self.base)
def __int__(self): return int(self.base)
def __long__(self): return long(self.base)
def __float__(self): return float(self.base)
def __complex__(self): return complex(self.base)
@staticmethod
def convert_to_vector(V):
"""
Static method that converts a vector-like object to a 2D numpy
dim x 1 column array.
Parameters
----------
V : array_like
Returns
-------
numpy array
"""
if isinstance(V, SPAMVec):
vector = _np.asarray(V).copy()
else:
try:
dim = len(V)
except:
raise ValueError("%s doesn't look like an array/list" % V)
try:
d2s = [ len(row) for row in V ]
except TypeError: # thrown if len(row) fails because no 2nd dim
d2s = None
if d2s is not None:
if any([len(row) != 1 for row in V]):
raise ValueError("%s is 2-dimensional but 2nd dim != 1" % V)
typ = 'd' if _np.all(_np.isreal(V)) else 'complex'
vector = _np.array(V, typ) #vec is already a 2-D column vector
else:
typ = 'd' if _np.all(_np.isreal(V)) else 'complex'
vector = _np.array(V, typ)[:,None] # make into a 2-D column vec
return vector
class StaticSPAMVec(SPAMVec):
"""
Encapsulates a SPAM vector that is completely fixed, or "static", meaning
that is contains no parameters.
"""
def __init__(self, vec):
"""
Initialize a StaticSPAMVec object.
Parameters
----------
vec : array_like or SPAMVec
a 1D numpy array representing the SPAM operation. The
shape of this array sets the dimension of the SPAM op.
"""
SPAMVec.__init__(self, SPAMVec.convert_to_vector(vec))
def set_vector(self, vec):
"""
Attempts to modify SPAMVec parameters so that the specified raw
SPAM vector becomes vec. Will raise ValueError if this operation
is not possible.
Parameters
----------
vec : array_like or SPAMVec
A numpy array representing a SPAM vector, or a SPAMVec object.
Returns
-------
None
"""
vec = SPAMVec.convert_to_vector(vec)
if(vec.size != self.dim):
raise ValueError("Argument must be length %d" % self.dim)
self.base[:,:] = vec
def num_params(self):
"""
Get the number of independent parameters which specify this SPAM vector.
Zero in the case of StaticSPAMVec.
Returns
-------
int
the number of independent parameters.
"""
return 0 #no parameters
def to_vector(self):
"""
Get the SPAM vector parameters as an array of values. An empty
array in the case of StaticSPAMVec.
Returns
-------
numpy array
The parameters as a 1D array with length num_params().
"""
return _np.array([], 'd') #no parameters
def from_vector(self, v):
"""
Initialize the SPAM vector using a 1D array of parameters.
Parameters
----------
v : numpy array
The 1D vector of gate parameters. Length
must == num_params()
Returns
-------
None
"""
assert(len(v) == 0) #should be no parameters, and nothing to do
def deriv_wrt_params(self):
"""
Construct a matrix whose columns are the derivatives of the SPAM vector
with respect to a single param. Thus, each column is of length
get_dimension and there is one column per SPAM vector parameter.
An empty 2D array in the StaticSPAMVec case (num_params == 0).
Returns
-------
numpy array
Array of derivatives, shape == (dimension, num_params)
"""
return _np.zeros((self.dim,0),'d')
def copy(self):
"""
Copy this SPAM vector.
Returns
-------
StaticSPAMVec
A copy of this SPAM operation.
"""
return StaticSPAMVec(self.base)
def __str__(self):
s = "Static spam vector with length %d\n" % \
len(self.base)
s += _mt.mx_to_string(self.base, width=4, prec=2)
return s
def __reduce__(self):
return (StaticSPAMVec, (_np.empty((self.dim,1),'d'),), self.__dict__)
class FullyParameterizedSPAMVec(SPAMVec):
"""
Encapsulates a SPAM vector that is fully parameterized, that is,
each element of the SPAM vector is an independent parameter.
"""
def __init__(self, vec):
"""
Initialize a FullyParameterizedSPAMOp object.
Parameters
----------
vec : array_like or SPAMVec
a 1D numpy array representing the SPAM operation. The
shape of this array sets the dimension of the SPAM op.
"""
SPAMVec.__init__(self, SPAMVec.convert_to_vector(vec))
def set_vector(self, vec):
"""
Attempts to modify SPAMVec parameters so that the specified raw
SPAM vector becomes vec. Will raise ValueError if this operation
is not possible.
Parameters
----------
vec : array_like or SPAMVec
A numpy array representing a SPAM vector, or a SPAMVec object.
Returns
-------
None
"""
vec = SPAMVec.convert_to_vector(vec)
if(vec.size != self.dim):
raise ValueError("Argument must be length %d" % self.dim)
self.base[:,:] = vec
def num_params(self):
"""
Get the number of independent parameters which specify this SPAM vector.
Returns
-------
int
the number of independent parameters.
"""
return self.dim
def to_vector(self):
"""
Get the SPAM vector parameters as an array of values.
Returns
-------
numpy array
The parameters as a 1D array with length num_params().
"""
return self.base.flatten() #.real in case of complex matrices
def from_vector(self, v):
"""
Initialize the SPAM vector using a 1D array of parameters.
Parameters
----------
v : numpy array
The 1D vector of gate parameters. Length
must == num_params()
Returns
-------
None
"""
self.base[:,0] = v
def deriv_wrt_params(self):
"""
Construct a matrix whose columns are the derivatives of the SPAM vector
with respect to a single param. Thus, each column is of length
get_dimension and there is one column per SPAM vector parameter.
Returns
-------
numpy array
Array of derivatives, shape == (dimension, num_params)
"""
return _np.identity( self.dim, 'd' )
def copy(self):
"""
Copy this SPAM vector.
Returns
-------
FullyParameterizedSPAMVec
A copy of this SPAM operation.
"""
return FullyParameterizedSPAMVec(self.base)
def __str__(self):
s = "Fully Parameterized spam vector with length %d\n" % len(self.base)
s += _mt.mx_to_string(self.base, width=4, prec=2)
return s
def __reduce__(self):
return (FullyParameterizedSPAMVec, (_np.empty((self.dim,1),'d'),), self.__dict__)
#Helpful for deriv_wrt_params??
# for (i,rhoVec) in enumerate(self.preps):
# deriv[foff+m:foff+m+rhoSize[i],off:off+rhoSize[i]] = _np.identity( rhoSize[i], 'd' )
# off += rhoSize[i]; foff += full_vsize
#
# for (i,EVec) in enumerate(self.effects):
# deriv[foff:foff+eSize[i],off:off+eSize[i]] = _np.identity( eSize[i], 'd' )
# off += eSize[i]; foff += full_vsize
class TPParameterizedSPAMVec(SPAMVec):
"""
Encapsulates a SPAM vector that is fully parameterized except for the first
element, which is frozen to be 1/(d**0.25). This is so that, when the SPAM
vector is interpreted in the Pauli or Gell-Mann basis, the represented
density matrix has trace == 1. This restriction is frequently used in
conjuction with trace-preserving (TP) gates.
"""
#Note: here we assume that the first basis element is (1/sqrt(x) * I),
# where I the d-dimensional identity (where len(vector) == d**2). So
# if Tr(basisEl*basisEl) == Tr(1/x*I) == d/x must == 1, then we must
# have x == d. Thus, we multiply this first basis element by
# alpha = 1/sqrt(d) to obtain a trace-1 matrix, i.e., finding alpha
# s.t. Tr(alpha*[1/sqrt(d)*I]) == 1 => alpha*d/sqrt(d) == 1 =>
# alpha = 1/sqrt(d) = 1/(len(vec)**0.25).
def __init__(self, vec):
"""
Initialize a TPParameterizedSPAMOp object.
Parameters
----------
vec : array_like or SPAMVec
a 1D numpy array representing the SPAM operation. The
shape of this array sets the dimension of the SPAM op.
"""
vector = SPAMVec.convert_to_vector(vec)
firstEl = len(vector)**-0.25
if not _np.isclose(vector[0,0], firstEl):
raise ValueError("Cannot create TPParameterizedSPAMVec: " +
"first element must equal %g!" % firstEl)
SPAMVec.__init__(self, _ProtectedArray(vector,
indicesToProtect=(0,0)))
def set_vector(self, vec):
"""
Attempts to modify SPAMVec parameters so that the specified raw
SPAM vector becomes vec. Will raise ValueError if this operation
is not possible.
Parameters
----------
vec : array_like or SPAMVec
A numpy array representing a SPAM vector, or a SPAMVec object.
Returns
-------
None
"""
vec = SPAMVec.convert_to_vector(vec)
firstEl = (self.dim)**-0.25
if(vec.size != self.dim):
raise ValueError("Argument must be length %d" % self.dim)
if not _np.isclose(vec[0,0], firstEl):
raise ValueError("Cannot create TPParameterizedSPAMVec: " +
"first element must equal %g!" % firstEl)
self.base[1:,:] = vec[1:,:]
def num_params(self):
"""
Get the number of independent parameters which specify this SPAM vector.
Returns
-------
int
the number of independent parameters.
"""
return self.dim-1
def to_vector(self):
"""
Get the SPAM vector parameters as an array of values.
Returns
-------
numpy array
The parameters as a 1D array with length num_params().
"""
return self.base.flatten()[1:] #.real in case of complex matrices?
def from_vector(self, v):
"""
Initialize the SPAM vector using a 1D array of parameters.
Parameters
----------
v : numpy array
The 1D vector of gate parameters. Length
must == num_params()
Returns
-------
None
"""
assert(_np.isclose(self.base[0,0], (self.dim)**-0.25))
self.base[1:,0] = v
def deriv_wrt_params(self):
"""
Construct a matrix whose columns are the derivatives of the SPAM vector
with respect to a single param. Thus, each column is of length
get_dimension and there is one column per SPAM vector parameter.
Returns
-------
numpy array
Array of derivatives, shape == (dimension, num_params)
"""
derivMx = _np.identity( self.dim, 'd' )
derivMx = derivMx[:,1:] #remove first col ( <=> first-el parameters )
return derivMx
def copy(self):
"""
Copy this SPAM vector.
Returns
-------
TPParameterizedSPAMVec
A copy of this SPAM operation.
"""
return TPParameterizedSPAMVec(self.base)
def __str__(self):
s = "TP-Parameterized spam vector with length %d\n" % self.dim
s += _mt.mx_to_string(self.base, width=4, prec=2)
return s
def __reduce__(self):
return (TPParameterizedSPAMVec, (self.base.copy(),), self.__dict__)
#SCRATCH: TO REMOVE
# def __len__(self):
# return len(self.base)
#
# def __add__(self,x):
# if isinstance(x, SPAMVec):
# return self.base + x.base
# else:
# return self.base + x
#
# def __radd__(self,x):
# if isinstance(x, SPAMVec):
# return x.base + self.base
# else:
# return x + self.base
#
# def __sub__(self,x):
# if isinstance(x, SPAMVec):
# return self.base - x.base
# else:
# return self.base - x
#
# def __rsub__(self,x):
# if isinstance(x, SPAMVec):
# return x.base - self.base
# else:
# return x - self.base
#
# def __mul__(self,x):
# if isinstance(x, SPAMVec):
# return self.base * x.base
# else:
# return self.base * x
#
# def __rmul__(self,x):
# if isinstance(x, SPAMVec):
# return x.base * self.base
# else:
# return x * self.base
#
# def __pow__(self,x): #same as __mul__()
# return self.base ** x
#
# def __eq__(self,x):
# if isinstance(x, SPAMVec):
# return self.base == x.base
# else:
# return self.base == x