-
Notifications
You must be signed in to change notification settings - Fork 54
/
Copy pathbasis.py
1776 lines (1492 loc) · 70.8 KB
/
basis.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 Basis object and supporting functions
"""
#***************************************************************************************************
# Copyright 2015, 2019, 2025 National Technology & Engineering Solutions of Sandia, LLC (NTESS).
# Under the terms of Contract DE-NA0003525 with NTESS, the U.S. Government retains certain rights
# in this software.
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
# in compliance with the License. You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0 or in the LICENSE file in the root pyGSTi directory.
#***************************************************************************************************
import copy as _copy
import itertools as _itertools
import warnings as _warnings
from functools import lru_cache
from typing import Union, Tuple, List
import numpy as _np
import scipy.sparse as _sps
import scipy.sparse.linalg as _spsl
from numpy.linalg import inv as _inv
from pygsti.baseobjs.basisconstructors import _basis_constructor_dict
from pygsti.baseobjs.statespace import StateSpace as _StateSpace
from pygsti.baseobjs.nicelyserializable import NicelySerializable as _NicelySerializable
#Helper functions
def _sparse_equal(a, b, atol=1e-8):
""" NOTE: same as matrixtools.sparse_equal - but can't import that here """
if _np.array_equal(a.shape, b.shape) == 0:
return False
r1, c1 = a.nonzero()
r2, c2 = b.nonzero()
lidx1 = _np.ravel_multi_index((r1, c1), a.shape)
lidx2 = _np.ravel_multi_index((r2, c2), b.shape)
sidx1 = lidx1.argsort()
sidx2 = lidx2.argsort()
index_match = _np.array_equal(lidx1[sidx1], lidx2[sidx2])
if index_match == 0:
return False
else:
v1 = a.data
v2 = b.data
V1 = v1[sidx1]
V2 = v2[sidx2]
return _np.allclose(V1, V2, atol=atol)
class Basis(_NicelySerializable):
"""
An ordered set of labeled matrices/vectors.
The base class for basis objects. A basis in pyGSTi is an abstract notion
of a set of labeled elements, or "vectors". Each basis has a certain size,
and has .elements, .labels, and .ellookup members, the latter being a
dictionary mapping of labels to elements.
An important point to note that isn't immediately
intuitive is that while Basis object holds *elements* (in its
`.elements` property) these are not the same as its *vectors*
(given by the object's `vector_elements` property). Often times,
in what we term a "simple" basis, the you just flatten an element
to get the corresponding vector-element. This works for bases
where the elements are either vectors (where flattening does
nothing) and matrices. By storing `elements` as distinct from
`vector_elements`, the Basis can capture additional structure
of the elements (such as viewing them as matrices) that can
be helpful for their display and interpretation. The elements
are also sometimes referred to as the "natural elements" because
they represent how to display the element in a natrual way. A
non-simple basis occurs when vector_elements need to be stored as
elements in a larger "embedded" way so that these elements can be
displayed and interpeted naturally.
A second important note is that there is assumed to be some underlying
"standard" basis underneath all the bases in pyGSTi. The elements in
a Basis are *always* written in this standard basis. In the case of the
"std"-named basis in pyGSTi, these elements are just the trivial vector
or matrix units, so one can rightly view the "std" pyGSTi basis as the
"standard" basis for a that particular dimension.
The arguments below describe the basic properties of all basis
objects in pyGSTi. It is important to remember that the
`vector_elements` of a basis are different from its `elements`
(see the :class:`Basis` docstring), and that `dim` refers
to the vector elements whereas elshape refers to the elements.
For example, consider a 2-element Basis containing the I and X Pauli
matrices. The `size` of this basis is `2`, as there are two elements
(and two vector elements). Since vector elements are the length-4
flattened Pauli matrices, the dimension (`dim`) is `4`. Since the
elements are 2x2 Pauli matrices, the `elshape` is `(2,2)`.
As another example consider a basis which spans all the diagonal
2x2 matrices. The elements of this basis are the two matrix units
with a 1 in the (0,0) or (1,1) location. The vector elements,
however, are the length-2 [1,0] and [0,1] vectors obtained by extracting
just the diagonal entries from each basis element. Thus, for this
basis, `size=2`, `dim=2`, and `elshape=(2,2)` - so the dimension is
not just the product of `elshape` entries (equivalently, `elsize`).
Parameters
----------
name : string
The name of the basis. This can be anything, but is
usually short and abbreviated. There are several
types of bases built into pyGSTi that can be constructed by
this name.
longname : string
A more descriptive name for the basis.
real : bool
Elements and vector elements are always allowed to have complex
entries. This argument indicates whether the coefficients in the
expression of an arbitrary vector in this basis must be real. For
example, if `real=True`, then when pyGSTi transforms a vector in
some other basis to a vector in *this* basis, it will demand that
the values of that vector (i.e. the coefficients which multiply
this basis's elements to obtain a vector in the "standard" basis)
are real.
sparse : bool
Whether the elements of `.elements` for this Basis are stored (when
they are stored at all) as sparse matrices or vectors.
Attributes
----------
dim : int
The dimension of the vector space this basis fully or partially
spans. Equivalently, the length of the `vector_elements` of the
basis.
size : int
The number of elements (or vector-elements) in the basis.
elshape : int
The shape of each element. Typically either a length-1 or length-2
tuple, corresponding to vector or matrix elements, respectively.
Note that *vector elements* always have shape `(dim,)` (or `(dim,1)`
in the sparse case).
elndim : int
The number of element dimensions, i.e. `len(self.elshape)`
elsize : int
The total element size, i.e. `product(self.elshape)`
vector_elements : list
The "vectors" of this basis, always 1D (sparse or dense) arrays.
"""
# Implementation note: casting functions are classmethods, but current implementations
# could be static methods.
@classmethod
def cast_from_name_and_statespace(cls, name: str, state_space: _StateSpace, sparse=None):
tpbBases = []
block_labels = state_space.tensor_product_blocks_labels
if len(block_labels) == 1 and len(block_labels[0]) == 1:
# Special case when we can actually pipe state_space to the BuiltinBasis constructor
lbl = block_labels[0][0]
nm = name if (state_space.label_type(lbl) == 'Q') else 'cl'
tpbBases.append(BuiltinBasis(nm, state_space, sparse))
else:
#TODO: add methods to StateSpace that can extract a sub-*StateSpace* object for a given label.
for tpbLabels in block_labels:
if len(tpbLabels) == 1:
nm = name if (state_space.label_type(tpbLabels[0]) == 'Q') else 'cl'
tpbBases.append(BuiltinBasis(nm, state_space.label_dimension(tpbLabels[0]), sparse))
else:
tpbBases.append(TensorProdBasis([
BuiltinBasis(name if (state_space.label_type(l) == 'Q') else 'cl',
state_space.label_dimension(l), sparse) for l in tpbLabels]))
if len(tpbBases) == 1:
return tpbBases[0]
else:
return DirectSumBasis(tpbBases)
@classmethod
def cast_from_name_and_dims(cls, name: str, dim: Union[int,list,tuple], sparse=None):
if isinstance(dim, (list, tuple)): # list/tuple of block dimensions
tpbBases = []
for tpbDim in dim:
if isinstance(tpbDim, (list, tuple)): # list/tuple of tensor-product dimensions
tpbBases.append(
TensorProdBasis([BuiltinBasis(name, factorDim, sparse) for factorDim in tpbDim]))
else:
tpbBases.append(BuiltinBasis(name, tpbDim, sparse))
if len(tpbBases) == 1:
return tpbBases[0]
else:
return DirectSumBasis(tpbBases)
else:
return BuiltinBasis(name, dim, sparse)
@classmethod
def cast_from_basis(cls, basis, dim=None, sparse=None):
#then just check to make sure consistent with `dim` & `sparse`
if dim is not None:
if isinstance(dim, _StateSpace):
state_space = dim
if hasattr(basis, 'state_space'): # TODO - should *all* basis objects have a state_space?
assert(state_space.is_compatible_with(basis.state_space)), \
"Basis object has incompatible state space: %s != %s" % (str(state_space),
str(basis.state_space))
else: # assume dim is an integer
assert(dim == basis.dim or dim == basis.elsize), \
"Basis object has unexpected dimension: %d != %d or %d" % (dim, basis.dim, basis.elsize)
if sparse is not None:
basis = basis.with_sparsity(sparse)
return basis
@classmethod
def cast_from_arrays(cls, arrays, dim=None, sparse=None):
b = ExplicitBasis(arrays, sparse=sparse)
if dim is not None:
assert(dim == b.dim), "Created explicit basis has unexpected dimension: %d vs %d" % (dim, b.dim)
if sparse is not None:
assert(sparse == b.sparse), "Basis object has unexpected sparsity: %s" % (b.sparse)
return b
@classmethod
def cast(cls, arg, dim=None, sparse=None):
#print("DB: CAST = ",arg,dim)
if isinstance(arg, Basis):
return cls.cast_from_basis(arg, dim, sparse)
if isinstance(arg, str):
if isinstance(dim, _StateSpace):
return cls.cast_from_name_and_statespace(arg, dim, sparse)
return cls.cast_from_name_and_dims(arg, dim, sparse)
if (arg is None) or (hasattr(arg,'__len__') and len(arg) == 0):
return ExplicitBasis([], [], "*Empty*", "Empty (0-element) basis", False, sparse)
# ^ The original implementation would return this value under two conditions.
# Either arg was None, or isinstance(arg,(tuple,list,ndarray)) and len(arg) == 0.
# We're just slightly relaxing the type requirement by using this check instead.
# At this point, original behavior would check that arg is a tuple, list, or ndarray.
# Instead, we'll just require that arg[0] is well-defined. This is enough to discern
# between the two cases we can still support.
if isinstance(arg[0], _np.ndarray):
return cls.cast_from_arrays(arg, dim, sparse)
if len(arg[0]) == 2:
compBases = [BuiltinBasis(subname, subdim, sparse) for (subname, subdim) in arg]
return DirectSumBasis(compBases)
raise ValueError("Can't cast %s to be a basis!" % str(type(arg)))
def __init__(self, name, longname, real, sparse):
super().__init__()
self.name = name
self.longname = longname
self.real = real # whether coefficients must be real (*not* whether elements are real - they're always complex)
self.sparse = sparse # whether elements are stored as sparse vectors/matrices
@property
def dim(self):
"""
The dimension of the vector space this basis fully or partially
spans. Equivalently, the length of the `vector_elements` of the
basis.
"""
# dimension of vector space this basis fully or partially spans
raise NotImplementedError("Derived classes must implement this!")
@property
def size(self):
"""
The number of elements (or vector-elements) in the basis.
"""
# number of elements (== dim if a *full* basis)
raise NotImplementedError("Derived classes must implement this!")
@property
def elshape(self):
"""
The shape of each element. Typically either a length-1 or length-2
tuple, corresponding to vector or matrix elements, respectively.
Note that *vector elements* always have shape `(dim,)` (or `(dim,1)`
in the sparse case).
"""
# shape of "natural" elements - size may be > self.dim (to display naturally)
raise NotImplementedError("Derived classes must implement this!")
@property
def elndim(self):
"""
The number of element dimensions, i.e. `len(self.elshape)`
Returns
-------
int
"""
if self.elshape is None: return 0
return len(self.elshape)
@property
def elsize(self):
"""
The total element size, i.e. `product(self.elshape)`
Returns
-------
int
"""
if self.elshape is None: return 0
return int(_np.prod(self.elshape))
@property
def first_element_is_identity(self):
"""
True if the first element of this basis is *proportional* to the identity matrix, False otherwise.
"""
if self.elndim != 2 or self.elshape[0] != self.elshape[1]: return False
d = self.elshape[0]
return _np.allclose(self.elements[0], _np.identity(d) * (_np.linalg.norm(self.elements[0]) / _np.sqrt(d)))
def is_simple(self):
"""
Whether the flattened-element vector space is the *same* space as the space this basis's vectors belong to.
Returns
-------
bool
"""
return self.elsize == self.dim
def is_complete(self):
"""
Whether this is a complete basis, i.e. this basis's vectors span the entire space that they live in.
Returns
-------
bool
"""
return self.dim == self.size
def is_partial(self):
"""
The negative of :meth:`is_complete`, effectively "is_incomplete".
Returns
-------
bool
"""
return not self.is_complete()
@property
def vector_elements(self):
"""
The "vectors" of this basis, always 1D (sparse or dense) arrays.
Returns
-------
list
A list of 1D arrays.
"""
if self.sparse:
return [_sps.lil_matrix(el).reshape((self.elsize, 1)) for el in self.elements]
else:
# Use flatten (rather than ravel) to ensure a copy is made.
return [el.flatten() for el in self.elements]
def copy(self):
"""
Make a copy of this Basis object.
Returns
-------
Basis
"""
return _copy.deepcopy(self)
def with_sparsity(self, desired_sparsity):
"""
Returns either this basis or a copy of it with the desired sparsity.
If this basis has the desired sparsity it is simply returned. If
not, this basis is copied to one that does.
Parameters
----------
desired_sparsity : bool
The sparsity (`True` for sparse elements, `False` for dense elements)
that is desired.
Returns
-------
Basis
"""
if self.sparse == desired_sparsity:
return self
else:
return self._copy_with_toggled_sparsity()
def _copy_with_toggled_sparsity(self):
raise NotImplementedError("Derived classes should implement this!")
def __str__(self):
return '{} (dim={}), {} elements of shape {} :\n{}'.format(
self.longname, self.dim, self.size, self.elshape, ', '.join(self.labels))
def __getitem__(self, index):
if isinstance(index, str) and self.ellookup is not None:
return self.ellookup[index]
return self.elements[index]
def __len__(self):
return self.size
def __eq__(self, other):
return self.is_equivalent(other, sparseness_must_match=True)
def is_equivalent(self, other, sparseness_must_match=True):
"""
Tests whether this basis is equal to another basis, optionally ignoring sparseness.
Parameters
-----------
other : Basis or str
The basis to compare with.
sparseness_must_match : bool, optional
If `False` then comparison ignores differing sparseness, and this function
returns `True` when the two bases are equal except for their `.sparse` values.
Returns
-------
bool
"""
otherIsBasis = isinstance(other, Basis)
if otherIsBasis and sparseness_must_match and (self.sparse != other.sparse):
return False # sparseness mismatch => not equal when sparseness_must_match == True
if self.sparse:
if self.dim > 256:
_warnings.warn("Attempted comparison between bases with large sparse matrices! Assuming not equal.")
return False # to expensive to compare sparse matrices
if otherIsBasis:
return all([_sparse_equal(A, B) for A, B in zip(self.elements, other.elements)])
else:
return all([_sparse_equal(A, B) for A, B in zip(self.elements, other)])
else:
if otherIsBasis:
return _np.array_equal(self.elements, other.elements)
else:
return _np.array_equal(self.elements, other)
@lru_cache(maxsize=4)
def create_transform_matrix(self, to_basis):
"""
Get the matrix that transforms a vector from this basis to `to_basis`.
Parameters
----------
to_basis : Basis or string
The basis to transform to or a built-in basis name. In the latter
case, a basis to transform to is built with the same structure as
this basis but with all components constructed from the given name.
Returns
-------
numpy.ndarray (even if basis is sparse)
"""
#Note: construct to_basis as sparse this basis is sparse and
# if to_basis is not already a Basis object
if not isinstance(to_basis, Basis):
to_basis = self.create_equivalent(to_basis)
#Note same logic as matrixtools.safe_dot(...)
if to_basis.sparse:
return to_basis.from_std_transform_matrix.dot(self.to_std_transform_matrix)
elif self.sparse:
#return _sps.csr_matrix(to_basis.from_std_transform_matrix).dot(self.to_std_transform_matrix)
return _np.dot(to_basis.from_std_transform_matrix, self.to_std_transform_matrix.toarray())
else:
return _np.dot(to_basis.from_std_transform_matrix, self.to_std_transform_matrix)
@lru_cache(maxsize=4)
def reverse_transform_matrix(self, from_basis):
"""
Get the matrix that transforms a vector from `from_basis` to this basis.
The reverse of :meth:`create_transform_matrix`.
Parameters
----------
from_basis : Basis or string
The basis to transform from or a built-in basis name. In the latter
case, a basis to transform from is built with the same structure as
this basis but with all components constructed from the given name.
Returns
-------
numpy.ndarray (even if basis is sparse)
"""
if not isinstance(from_basis, Basis):
from_basis = self.create_equivalent(from_basis)
#Note same logic as matrixtools.safe_dot(...)
if self.sparse:
return self.from_std_transform_matrix.dot(from_basis.to_std_transform_matrix)
elif from_basis.sparse:
#return _sps.csr_matrix(to_basis.from_std_transform_matrix).dot(self.to_std_transform_matrix)
return _np.dot(self.from_std_transform_matrix, from_basis.to_std_transform_matrix.toarray())
else:
return _np.dot(self.from_std_transform_matrix, from_basis.to_std_transform_matrix)
@lru_cache(maxsize=128)
def is_normalized(self):
"""
Check if a basis is normalized, meaning that Tr(Bi Bi) = 1.0.
Available only to bases whose elements are *matrices* for now.
Returns
-------
bool
"""
if self.elndim == 2:
for i, mx in enumerate(self.elements):
t = _np.linalg.norm(mx) # == sqrt(tr(mx mx))
if not _np.isclose(t, 1.0): return False
return True
elif self.elndim == 1:
raise NotImplementedError("TODO: add code so this works for *vector*-valued bases too!")
else:
raise ValueError("I don't know what normalized means for elndim == %d!" % self.elndim)
@property
@lru_cache(maxsize=128)
def to_std_transform_matrix(self):
"""
Retrieve the matrix that transforms a vector from this basis to the standard basis of this basis's dimension.
Returns
-------
numpy array or scipy.sparse.lil_matrix
An array of shape `(dim, size)` where `dim` is the dimension
of this basis (the length of its vectors) and `size` is the
size of this basis (its number of vectors).
"""
if self.sparse:
toStd = _sps.lil_matrix((self.dim, self.size), dtype='complex')
else:
toStd = _np.zeros((self.dim, self.size), 'complex')
for i, vel in enumerate(self.vector_elements):
toStd[:, i] = vel
return toStd
@property
@lru_cache(maxsize=128)
def from_std_transform_matrix(self):
"""
Retrieve the matrix that transforms vectors from the standard basis to this basis.
Returns
-------
numpy array or scipy sparse matrix
An array of shape `(size, dim)` where `dim` is the dimension
of this basis (the length of its vectors) and `size` is the
size of this basis (its number of vectors).
"""
if self.sparse:
if self.is_complete():
return _spsl.inv(self.to_std_transform_matrix.tocsc()).tocsr()
else:
assert(self.size < self.dim), "Basis seems to be overcomplete: size > dimension!"
# we'd need to construct a different pseudo-inverse if the above assert fails
A = self.to_std_transform_matrix # shape (dim,size) - should have indep *cols*
Adag = A.getH() # shape (size, dim)
invAdagA = _spsl.inv(Adag.tocsr().dot(A.tocsc())).tocsr()
return invAdagA.dot(Adag.tocsc())
else:
if self.is_complete():
return _inv(self.to_std_transform_matrix)
else:
assert(self.size < self.dim), "Basis seems to be overcomplete: size > dimension!"
# we'd need to construct a different pseudo-inverse if the above assert fails
A = self.to_std_transform_matrix # shape (dim,size) - should have indep *cols*
Adag = A.transpose().conjugate() # shape (size, dim)
return _np.dot(_inv(_np.dot(Adag, A)), Adag)
@property
@lru_cache(maxsize=128)
def to_elementstd_transform_matrix(self):
"""
Get transformation matrix from this basis to the "element space".
Get the matrix that transforms vectors in this basis (with length equal
to the `dim` of this basis) to vectors in the "element space" - that
is, vectors in the same standard basis that the *elements* of this basis
are expressed in.
Returns
-------
numpy array
An array of shape `(element_dim, size)` where `element_dim` is the
dimension, i.e. size, of the elements of this basis (e.g. 16 if the
elements are 4x4 matrices) and `size` is the size of this basis (its
number of vectors).
"""
# This default implementation assumes that the (flattened) element space
# *is* a standard representation of the vector space this basis or partial-basis
# acts upon (this is *not* true for direct-sum bases, where the flattened
# elements represent vectors in a larger "embedding" space (w/larger dim than actual space).
assert(self.is_simple()), "Incorrectly using a simple-assuming implementation of to_elementstd_transform_matrix"
return self.to_std_transform_matrix
@property
@lru_cache(maxsize=128)
def from_elementstd_transform_matrix(self): # OLD: get_expand_mx(self):
"""
Get transformation matrix from "element space" to this basis.
Get the matrix that transforms vectors in the "element space" - that
is, vectors in the same standard basis that the *elements* of this basis
are expressed in - to vectors in this basis (with length equal to the
`dim` of this basis).
Returns
-------
numpy array
An array of shape `(size, element_dim)` where `element_dim` is the
dimension, i.e. size, of the elements of this basis (e.g. 16 if the
elements are 4x4 matrices) and `size` is the size of this basis (its
number of vectors).
"""
if self.sparse:
raise NotImplementedError("from_elementstd_transform_matrix not implemented for sparse mode") # (need pinv)
return _np.linalg.pinv(self.to_elementstd_transform_matrix)
def create_equivalent(self, builtin_basis_name):
"""
Create an equivalent basis with components of type `builtin_basis_name`.
Create a :class:`Basis` that is equivalent in structure & dimension to this
basis but whose simple components (perhaps just this basis itself) is
of the builtin basis type given by `builtin_basis_name`.
Parameters
----------
builtin_basis_name : str
The name of a builtin basis, e.g. `"pp"`, `"gm"`, or `"std"`. Used to
construct the simple components of the returned basis.
Returns
-------
Basis
"""
#This default implementation assumes that this basis is simple.
assert(self.is_simple()), "Incorrectly using a simple-assuming implementation of create_equivalent()"
return BuiltinBasis(builtin_basis_name, self.dim, sparse=self.sparse)
#TODO: figure out if we actually need the return value from this function to
# not have any components... Maybe jamiolkowski.py needs this? If it's
# unnecessary, we can update these doc strings and perhaps TensorProdBasis's
# implementation:
def create_simple_equivalent(self, builtin_basis_name=None):
"""
Create a basis of type `builtin_basis_name` whose elements are compatible with this basis.
Create a simple basis *and* one without components (e.g. a
:class:`TensorProdBasis`, is a simple basis w/components) of the
builtin type specified whose dimension is compatible with the
*elements* of this basis. This function might also be named
"element_equivalent", as it returns the `builtin_basis_name`-analogue
of the standard basis that this basis's elements are expressed in.
Parameters
----------
builtin_basis_name : str, optional
The name of the built-in basis to use. If `None`, then a
copy of this basis is returned (if it's simple) or this
basis's name is used to try to construct a simple and
component-free version of the same builtin-basis type.
Returns
-------
Basis
"""
#This default implementation assumes that this basis is simple.
assert(self.is_simple()), "Incorrectly using a simple-assuming implementation of create_simple_equivalent()"
if builtin_basis_name is None: return self.copy()
else: return self.create_equivalent(builtin_basis_name)
def is_compatible_with_state_space(self, state_space):
"""
Checks whether this basis is compatible with a given state space.
Parameters
----------
state_space : StateSpace
the state space to check.
Returns
-------
bool
"""
#FUTURE - need a way to deal with many qubits where total dim will overflow an int64
#if self.state_space.dim is None: # `None` indicates that dim is effectively infinite?
return bool(self.dim == state_space.dim)
class LazyBasis(Basis):
"""
A :class:`Basis` whose labels and elements that are constructed only when at least one of them is needed.
This class is also used as a base class for higher-level, more specific basis classes.
Parameters
----------
name : string
The name of the basis. This can be anything, but is
usually short and abbreviated. There are several
types of bases built into pyGSTi that can be constructed by
this name.
longname : string
A more descriptive name for the basis.
real : bool
Elements and vector elements are always allowed to have complex
entries. This argument indicates whether the coefficients in the
expression of an arbitrary vector in this basis must be real. For
example, if `real=True`, then when pyGSTi transforms a vector in
some other basis to a vector in *this* basis, it will demand that
the values of that vector (i.e. the coefficients which multiply
this basis's elements to obtain a vector in the "standard" basis)
are real.
sparse : bool
Whether the elements of `.elements` for this Basis are stored (when
they are stored at all) as sparse matrices or vectors.
Attributes
----------
ellookup : dict
A dictionary mapping basis element labels to the elements themselves, for fast element lookup.
elements : numpy.ndarray
The basis elements (sometimes different from the *vectors*)
labels : list
The basis labels
"""
def __init__(self, name, longname, real, sparse):
"""
Creates a new LazyBasis. Parameters are the same as those to
:meth:`Basis.__init__`.
"""
self._elements = None # "natural-shape" elements - can be vecs or matrices
self._labels = None # element labels
self._ellookup = None # fast element lookup
super(LazyBasis, self).__init__(name, longname, real, sparse)
def _lazy_build_elements(self):
raise NotImplementedError("Derived classes must implement this function!")
def _lazy_build_labels(self):
raise NotImplementedError("Derived classes must implement this function!")
@property
def ellookup(self):
"""
A dictionary mapping basis element labels to the elements themselves
Returns
-------
dict
"""
if self._ellookup is None:
if self._elements is None:
self._lazy_build_elements()
if self._labels is None:
self._lazy_build_labels()
self._ellookup = {lbl: el for lbl, el in zip(self._labels, self._elements)}
return self._ellookup
@property
def elements(self):
"""
The basis elements (sometimes different from the *vectors*)
Returns
-------
numpy.ndarray
"""
if self._elements is None:
self._lazy_build_elements()
return self._elements
@property
def labels(self):
"""
The basis labels
Returns
-------
list
"""
if self._labels is None:
self._lazy_build_labels()
return self._labels
def __str__(self):
if self._labels is None and self.dim > 64:
return '{} (dim={}), {} elements of shape {} (not computed yet)'.format(
self.longname, self.dim, self.size, self.elshape)
else:
return super(LazyBasis, self).__str__()
class ExplicitBasis(Basis):
"""
A `Basis` whose elements are specified directly.
All explicit bases are simple: their vector space is taken to be that
of the the flattened elements unless separate `vector_elements` are given.
Parameters
----------
elements : numpy.ndarray
The basis elements (sometimes different from the *vectors*)
labels : list
The basis labels
name : str, optional
The name of this basis. If `None`, then a name will be
automatically generated.
longname : str, optional
A more descriptive name for this basis. If `None`, then the
short `name` will be used.
real : bool, optional
Whether the coefficients in the expression of an arbitrary vector
as a linear combination of this basis's elements must be real.
sparse : bool, optional
Whether the elements of this Basis are stored as sparse matrices or
vectors. If `None`, then this is automatically determined by the
type of the initial object: `elements[0]` (`sparse=False` is used
when `len(elements) == 0`).
vector_elements : numpy.ndarray, optional
A list or array of the 1D *vectors* corresponding to each element.
If `None`, then the flattened elements are used as vectors. The size
of these vectors sets the dimension of the basis.
Attributes
----------
Count : int
The number of custom bases, used for serialized naming
"""
Count = 0 # The number of custom bases, used for serialized naming
def __init__(self, elements, labels=None, name=None, longname=None, real=False, sparse=None, vector_elements=None):
'''
Create a new ExplicitBasis.
Parameters
----------
elements : iterable
A list of the elements of this basis.
labels : iterable, optional
A list of the labels corresponding to the elements of `elements`.
If given, `len(labels)` must equal `len(elements)`.
name : str, optional
The name of this basis. If `None`, then a name will be
automatically generated.
longname : str, optional
A more descriptive name for this basis. If `None`, then the
short `name` will be used.
real : bool, optional
Whether the coefficients in the expression of an arbitrary vector
as a linear combination of this basis's elements must be real.
sparse : bool, optional
Whether the elements of this Basis are stored as sparse matrices or
vectors. If `None`, then this is automatically determined by the
type of the initial object: `elements[0]` (`sparse=False` is used
when `len(elements) == 0`).
vector_elements : numpy.ndarray, optional
A list or array of the 1D *vectors* corresponding to each element.
If `None`, then the flattened elements are used as vectors. The size
of these vectors sets the dimension of the basis.
'''
if name is None:
name = 'ExplicitBasis_{}'.format(ExplicitBasis.Count)
if longname is None: longname = "Auto-named " + name
ExplicitBasis.Count += 1
elif longname is None: longname = name
if labels is None: labels = ["E%d" % k for k in range(len(elements))]
if (len(labels) != len(elements)):
raise ValueError("Expected a list of %d labels but got: %s" % (len(elements), str(labels)))
self.labels = tuple(labels) # so hashable - see __hash__
self.elements = []
size = len(elements)
if size == 0:
elshape = (); dim = 0; sparse = False
else:
if sparse is None:
sparse = _sps.issparse(elements[0]) if len(elements) > 0 else False
elshape = None
for el in elements:
if sparse:
if not _sps.issparse(el) or not _sps.isspmatrix_csr(el): # needs to be CSR type for __hash__
el = _sps.csr_matrix(el) # try to convert to a sparse matrix
else:
if not isinstance(el, _np.ndarray):
el = _np.array(el) # try to convert to a numpy array
if elshape is None: elshape = el.shape
else: assert(elshape == el.shape), "Inconsistent element shapes!"
self.elements.append(el)
dim = int(_np.prod(elshape))
self.ellookup = {lbl: el for lbl, el in zip(self.labels, self.elements)} # fast by-label element lookup
if vector_elements is not None:
assert(len(vector_elements) == size), "Must have the same number of `elements` and `vector_elements`"
if sparse:
self._vector_elements = [(el if _sps.issparse(el) else _sps.lil_matrix(el)) for el in vector_elements]
else:
self._vector_elements = _np.array(vector_elements) # rows are *vectors*
dim = self._vector_elements.shape[1]
else:
self._vector_elements = None
self._dim = dim
self._size = size
self._elshape = elshape
super(ExplicitBasis, self).__init__(name, longname, real, sparse)
def _to_nice_serialization(self):
state = super()._to_nice_serialization()
state.update({'name': self.name,
'longname': self.longname,
'real': self.real,
'sparse': self.sparse,
'labels': self.labels,
'elements': [self._encodemx(el) for el in self.elements],
'vector_elements': ([self._encodemx(vel) for vel in self._vector_elements]
if (self._vector_elements is not None) else None)
})
return state
@classmethod
def _from_nice_serialization(cls, state):
vels = [cls._decodemx(vel) for vel in state['vector_elements']] \
if (state.get('vector_elements', None) is not None) else None
return cls([cls._decodemx(el) for el in state['elements']],
state['labels'], state['name'], state['longname'], state['real'],
state['sparse'], vels)
@property
def dim(self):
"""
The dimension of the vector space this basis fully or partially
spans. Equivalently, the length of the `vector_elements` of the
basis.
"""
# dimension of vector space this basis fully or partially spans
return self._dim
@property
def size(self):
"""
The number of elements (or vector-elements) in the basis.
"""
# number of elements (== dim if a *full* basis)
return self._size
@property
def elshape(self):
"""