-
Notifications
You must be signed in to change notification settings - Fork 63
Expand file tree
/
Copy pathstatespace.py
More file actions
1448 lines (1192 loc) · 47.3 KB
/
Copy pathstatespace.py
File metadata and controls
1448 lines (1192 loc) · 47.3 KB
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 OrderedDict-derived classes used to store specific pyGSTi objects
"""
# ***************************************************************************************************
# 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 numbers as _numbers
import sys as _sys
import numpy as _np
from pygsti.baseobjs.nicelyserializable import NicelySerializable as _NicelySerializable
class StateSpace(_NicelySerializable):
"""
Base class for defining a state space (Hilbert or Hilbert-Schmidt space).
This base class just sets the API for a "state space" in pyGSTi, accessed
as the direct sum of one or more tensor products of Hilbert spaces.
"""
@classmethod
def cast(cls, obj):
"""
Casts `obj` into a :class:`StateSpace` object if possible.
If `obj` is already of this type, it is simply returned without modification.
Parameters
----------
obj : StateSpace or int or list
Either an already-built state space object or an integer specifying the number of qubits,
or a list of labels as would be provided to the first argument of :meth:`ExplicitStateSpace.__init__`.
Returns
-------
StateSpace
"""
if isinstance(obj, StateSpace):
return obj
if isinstance(obj, int) or all([isinstance(x, int) or (isinstance(x, str) and x.startswith('Q')) for x in obj]):
return QubitSpace(obj)
return ExplicitStateSpace(obj)
def __init__(self):
super().__init__()
@property
def udim(self):
"""
Integer Hilbert (unitary operator) space dimension of this quantum state space.
Raises an error if this space is *not* a quantum state space.
"""
raise NotImplementedError("Derived classes should implement this!")
@property
def dim(self):
"""Integer Hilbert-Schmidt (super-operator) or classical dimension of this state space."""
raise NotImplementedError("Derived classes should implement this!")
@property
def num_qubits(self): # may raise ValueError if the state space doesn't consist entirely of qubits
"""
The number of qubits in this quantum state space.
Raises a ValueError if this state space doesn't consist entirely of qubits.
"""
raise NotImplementedError("Derived classes should implement this!")
@property
def num_qudits(self): # may raise ValueError if the state space doesn't consist entirely of qubits
"""
The number of qudits in this quantum state space.
Raises a ValueError if this state space doesn't consist entirely of qudits.
"""
raise NotImplementedError("Derived classes should implement this!")
@property
def num_tensor_product_blocks(self):
"""
The number of tensor-product blocks which are direct-summed to get the final state space.
Returns
-------
int
"""
raise NotImplementedError("Derived classes should implement this!")
@property
def sole_tensor_product_block_labels(self):
"""
The labels of the first and only tensor product block within this state space.
If there are multiple blocks, a ValueError is raised.
"""
if self.num_tensor_product_blocks > 1:
raise ValueError(("Attribute `sole_tensor_product_block_labels` was used but this state space has"
" %d blocks!") % self.num_tensor_product_blocks)
return self.tensor_product_block_labels(0)
@property
def tensor_product_blocks_labels(self):
"""
The labels for all the tensor-product blocks.
Returns
-------
tuple of tuples
"""
raise NotImplementedError("Derived classes should implement this!")
@property
def tensor_product_blocks_dimensions(self):
"""
The superoperator dimensions for all the tensor-product blocks.
Returns
-------
tuple of tuples
"""
raise NotImplementedError("Derived classes should implement this!")
@property
def tensor_product_blocks_udimensions(self):
"""
The unitary operator dimensions for all the tensor-product blocks.
Returns
-------
tuple of tuples
"""
raise NotImplementedError("Derived classes should implement this!")
@property
def tensor_product_blocks_types(self):
"""
The type (quantum vs classical) of all the tensor-product blocks.
Returns
-------
tuple of tuples
"""
raise NotImplementedError("Derived classes should implement this!")
def label_dimension(self, label):
"""
The superoperator dimension of the given label (from any tensor product block)
Parameters
----------
label : str or int
The label whose dimension should be retrieved.
Returns
-------
int
"""
raise NotImplementedError("Derived classes should implement this!")
def label_udimension(self, label):
"""
The unitary operator dimension of the given label (from any tensor product block)
Parameters
----------
label : str or int
The label whose dimension should be retrieved.
Returns
-------
int
"""
raise NotImplementedError("Derived classes should implement this!")
def label_tensor_product_block_index(self, label):
"""
The index of the tensor product block containing the given label.
Parameters
----------
label : str or int
The label whose index should be retrieved.
Returns
-------
int
"""
raise NotImplementedError("Derived classes should implement this!")
def label_type(self, label):
"""
The type (quantum or classical) of the given label (from any tensor product block).
Parameters
----------
label : str or int
The label whose type should be retrieved.
Returns
-------
str
"""
raise NotImplementedError("Derived classes should implement this!")
def tensor_product_block_labels(self, i_tpb):
"""
The labels for the `iTBP`-th tensor-product block.
Parameters
----------
i_tpb : int
Tensor-product block index.
Returns
-------
tuple
"""
return self.tensor_product_blocks_labels[i_tpb]
def tensor_product_block_dimensions(self, i_tpb):
"""
The superoperator dimensions for the factors in the `iTBP`-th tensor-product block.
Parameters
----------
i_tpb : int
Tensor-product block index.
Returns
-------
tuple
"""
return self.tensor_product_blocks_dimensions[i_tpb]
def tensor_product_block_udimensions(self, i_tpb):
"""
The unitary-operator dimensions for the factors in the `iTBP`-th tensor-product block.
Parameters
----------
i_tpb : int
Tensor-product block index.
Returns
-------
tuple
"""
return self.tensor_product_blocks_dimensions[i_tpb]
def copy(self):
"""
Return a copy of this StateSpace.
Returns
-------
StateSpace
"""
return _copy.deepcopy(self)
def is_compatible_with(self, other_state_space):
"""
Whether another state space is compatible with this one.
Two state spaces are considered "compatible" when their overall dimensions
agree (even if their tensor product block structure and labels do not).
(This checks whether the Hilbert spaces are isomorphic.)
Parameters
----------
other_state_space : StateSpace
The state space to check compatibility with.
Returns
-------
bool
"""
try:
if self.num_qubits == other_state_space.num_qubits:
return True
except Exception:
if self.udim == other_state_space.udim:
return True
return False
@property
def is_entirely_qubits(self):
"""
Whether this state space is just the tensor product of qubit subspaces.
Returns
-------
bool
"""
try:
self.num_qubits
return True
except Exception:
return False
def is_entire_space(self, labels):
"""
True if this state space is a single tensor product block with (exactly, in order) the given set of labels.
Parameters
----------
labels : iterable
the labels to test.
Returns
-------
bool
"""
return (self.num_tensor_product_blocks == 1
and self.tensor_product_block_labels(0) == tuple(labels))
def contains_labels(self, labels):
"""
True if this state space contains all of a given set of labels.
Parameters
----------
labels : iterable
the labels to test.
Returns
-------
bool
"""
return all((self.contains_label(lbl) for lbl in labels))
def contains_label(self, label):
"""
True if this state space contains a given label.
Parameters
----------
label : str or int
the label to test for.
Returns
-------
bool
"""
for i in range(self.num_tensor_product_blocks):
if label in self.tensor_product_block_labels(i): return True
return False
@property
def common_dimension(self):
"""
Returns the common super-op dimension of all the labels in this space.
If not all the labels in this space have the same dimension, then
`None` is returned to indicate this.
This property is useful when working with stencils, where operations
are created for a "stencil space" that is not exactly a subspace of
a StateSpace space but will be mapped to one in the future.
Returns
-------
int or None
"""
tpb_dims = self.tensor_product_blocks_dimensions
if len(tpb_dims) == 0: return 0
ref_dim = tpb_dims[0][0]
if all([dim == ref_dim for dims in tpb_dims for dim in dims]):
return ref_dim
else:
return None
@property
def common_udimension(self):
"""
Returns the common unitary-op dimension of all the labels in this space.
If not all the labels in this space have the same dimension, then
`None` is returned to indicate this.
This property is useful when working with stencils, where operations
are created for a "stencil space" that is not exactly a subspace of
a StateSpace space but will be mapped to one in the future.
Returns
-------
int or None
"""
tpb_udims = self.tensor_product_blocks_udimensions
if len(tpb_udims) == 0: return 0
ref_udim = tpb_udims[0][0]
if all([udim == ref_udim for udims in tpb_udims for udim in udims]):
return ref_udim
else:
return None
def create_subspace(self, labels):
"""
Create a sub-`StateSpace` object from a set of existing labels.
Parameters
----------
labels : iterable
The labels to include in the returned state space.
Returns
-------
StateSpace
"""
# Default, generic, implementation constructs an explicit state space
labels = sorted(set(labels))
sub_tpb_labels = []
sub_tpb_udims = []
sub_tpb_types = []
for lbls, udims, typs in zip(self.tensor_product_blocks_labels, self.tensor_product_blocks_udimensions,
self.tensor_product_blocks_types):
sub_lbls = []; sub_udims = []; sub_types = []
for lbl, udim, typ in zip(lbls, udims, typs):
if lbl in labels:
sub_lbls.append(lbl)
sub_udims.append(udim)
sub_types.append(typ)
labels.remove(lbl)
if len(sub_lbls) > 0:
sub_tpb_labels.append(sub_lbls)
sub_tpb_udims.append(sub_udims)
sub_tpb_types.append(sub_types)
assert(len(labels) == 0), "One or more elements of `labels` is not a valid label for this state space!"
return ExplicitStateSpace(sub_tpb_labels, sub_tpb_udims, sub_tpb_types)
def intersection(self, other_state_space):
"""
Create a state space whose labels are the intersection of the labels of this space and one other.
Dimensions associated with the labels are preserved, as is the ordering of tensor product blocks.
If the two spaces have the same label, but their dimensions or indices do not agree, an
error is raised.
Parameters
----------
other_state_space : StateSpace
The other state space.
Returns
-------
StateSpace
"""
ret_tpb_labels = []
ret_tpb_udims = []
ret_tpb_types = []
for iTPB, (lbls, udims, typs) in enumerate(zip(self.tensor_product_blocks_labels,
self.tensor_product_blocks_udimensions,
self.tensor_product_blocks_types)):
ret_lbls = []; ret_udims = []; ret_types = []
for lbl, udim, typ in zip(lbls, udims, typs):
if other_state_space.contains_label(lbl):
other_iTPB = other_state_space.label_tensor_product_block_index(lbl)
other_udim = other_state_space.label_udimension(lbl)
other_typ = other_state_space.label_type(lbl)
if other_iTPB != iTPB or other_udim != udim or other_typ != typ:
raise ValueError(("Cannot take state space intersection: repeated label '%s' has inconsistent index,"
" dim, or type!") % str(lbl))
ret_lbls.append(lbl)
ret_udims.append(udim)
ret_types.append(typ)
if len(ret_lbls) > 0:
ret_tpb_labels.append(ret_lbls)
ret_tpb_udims.append(ret_udims)
ret_tpb_types.append(ret_types)
return ExplicitStateSpace(ret_tpb_labels, ret_tpb_udims, ret_tpb_types)
def union(self, other_state_space):
"""
Create a state space whose labels are the union of the labels of this space and one other.
Dimensions associated with the labels are preserved, as is the tensor product block index.
If the two spaces have the same label, but their dimensions or indices do not agree, an
error is raised.
Parameters
----------
other_state_space : StateSpace
The other state space.
Returns
-------
StateSpace
"""
ret_tpb_labels = []
ret_tpb_udims = []
ret_tpb_types = []
# Step 1: add all of the labels of `self`, checking that overlaps are consistent as we go:
for iTPB, (lbls, udims, typs) in enumerate(zip(self.tensor_product_blocks_labels,
self.tensor_product_blocks_udimensions,
self.tensor_product_blocks_types)):
ret_lbls = []; ret_udims = []; ret_types = []
for lbl, udim, typ in zip(lbls, udims, typs):
if other_state_space.contains_label(lbl):
other_iTPB = other_state_space.label_tensor_product_block_index(lbl)
other_udim = other_state_space.label_udimension(lbl)
other_typ = other_state_space.label_type(lbl)
if other_iTPB != iTPB or other_udim != udim or other_typ != typ:
raise ValueError(("Cannot take state space union: repeated label '%s' has inconsistent index,"
" dim, or type!") % str(lbl))
ret_lbls.append(lbl)
ret_udims.append(udim)
ret_types.append(typ)
ret_tpb_labels.append(ret_lbls)
ret_tpb_udims.append(ret_udims)
ret_tpb_types.append(ret_types)
# Step 2: add any non-overlapping labels from other_state_space
for iTPB, (lbls, udims, typs) in enumerate(zip(other_state_space.tensor_product_blocks_labels,
other_state_space.tensor_product_blocks_udimensions,
other_state_space.tensor_product_blocks_types)):
for lbl, udim, typ in zip(lbls, udims, typs):
if not self.contains_label(lbl):
ret_tpb_labels[iTPB].append(lbl)
ret_tpb_udims[iTPB].append(udim)
ret_tpb_types[iTPB].append(typ)
return ExplicitStateSpace(ret_tpb_labels, ret_tpb_udims, ret_tpb_types)
def difference(self, other_state_space):
"""
Create a state space whose labels are the difference of the labels of this space and one other.
I.e. a state space containing the labels of this space which don't appear in the other.
Dimensions associated with the labels are preserved, as is the tensor product block index.
If the two spaces have the same label, but their dimensions or indices do not agree, an
error is raised.
Parameters
----------
other_state_space : StateSpace
The other state space.
Returns
-------
StateSpace
"""
ret_tpb_labels = []
ret_tpb_udims = []
ret_tpb_types = []
for iTPB, (lbls, udims, typs) in enumerate(zip(self.tensor_product_blocks_labels,
self.tensor_product_blocks_udimensions,
self.tensor_product_blocks_types)):
ret_lbls = []; ret_udims = []; ret_types = []
for lbl, udim, typ in zip(lbls, udims, typs):
#If the label does appear in the other state space, verify that the
#properties of the label are consistently defined accross the two state spaces
#otherwise raise an error.
if other_state_space.contains_label(lbl):
other_iTPB = other_state_space.label_tensor_product_block_index(lbl)
other_udim = other_state_space.label_udimension(lbl)
other_typ = other_state_space.label_type(lbl)
if other_iTPB != iTPB or other_udim != udim or other_typ != typ:
raise ValueError(("Cannot take state space difference: repeated label '%s' has inconsistent index,"
" dim, or type!") % str(lbl))
continue
#Otherwise add this to the state space.
else:
ret_lbls.append(lbl)
ret_udims.append(udim)
ret_types.append(typ)
if len(ret_lbls) > 0:
ret_tpb_labels.append(ret_lbls)
ret_tpb_udims.append(ret_udims)
ret_tpb_types.append(ret_types)
return ExplicitStateSpace(ret_tpb_labels, ret_tpb_udims, ret_tpb_types)
def create_stencil_subspace(self, labels):
"""
Create a template sub-`StateSpace` object from a set of potentially stencil-type labels.
That is, the elements of `labels` don't need to actually exist
within this state space -- they may be stencil labels that will
resolve to a label in this state space later on.
Parameters
----------
labels : iterable
The labels to include in the returned state space.
Returns
-------
StateSpace
"""
common_udim = self.common_udimension
if common_udim is None:
raise ValueError("Can only create stencil sub-StateSpace for a state space with a common label dimension!")
num_labels = len(labels)
return ExplicitStateSpace(tuple(range(num_labels)), (common_udim,) * num_labels)
# Note: this creates quantum-type sectors because integer labels are used (OK?)
def __repr__(self):
return self.__class__.__name__ + "[" + str(self) + "]"
def __hash__(self):
return hash((self.tensor_product_blocks_labels,
self.tensor_product_blocks_dimensions,
self.tensor_product_blocks_types))
def __eq__(self, other_statespace):
if isinstance(other_statespace, StateSpace):
return (self.tensor_product_blocks_labels == other_statespace.tensor_product_blocks_labels
and self.tensor_product_blocks_dimensions == other_statespace.tensor_product_blocks_dimensions
and self.tensor_product_blocks_types == other_statespace.tensor_product_blocks_types)
else:
return False # this state space is not equal to anything that isn't another state space
@property
def state_space_labels(self):
"""
Return a tuple corresponding to the concatenation of the
constituent state space labels within each tensor product
block of this `StateSpace` object.
Returns
-------
flattened_state_space_label_list : tuple
A tuple containing a flattened list of all of the state
space labels appearing within the tensor product blocks
of this `StateSpace` objects label list.
"""
flattened_state_space_label_list = []
for blk in self.tensor_product_blocks_labels:
for lbl in blk:
flattened_state_space_label_list.append(lbl)
return tuple(flattened_state_space_label_list)
class QuditSpace(StateSpace):
"""
A state space consisting of N qudits.
"""
def __init__(self, nqudits_or_labels, udim_or_udims):
super().__init__()
if isinstance(nqudits_or_labels, int):
self._qudit_labels = tuple(range(nqudits_or_labels))
else:
self._qudit_labels = tuple(nqudits_or_labels)
if isinstance(udim_or_udims, int):
self._qudit_udims = tuple([udim_or_udims] * len(self._qudit_labels))
else:
self._qudit_udims = tuple(udim_or_udims)
assert(len(self._qudit_udims) == len(self._qudit_labels)), \
"`udim_or_udims` must either be an interger or have length equal to the number of qudits!"
#This state space is effectively static, so we can precompute the hash for it for performance
self._hash = hash((self.tensor_product_blocks_labels,
self.tensor_product_blocks_dimensions,
self.tensor_product_blocks_types))
def __hash__(self):
return self._hash
#pickle management functions
def __getstate__(self):
state_dict = self.__dict__
return state_dict
def __setstate__(self, state_dict):
for k, v in state_dict.items():
self.__dict__[k] = v
#reinitialize the hash
self._hash = hash((self.tensor_product_blocks_labels,
self.tensor_product_blocks_dimensions,
self.tensor_product_blocks_types))
def _to_nice_serialization(self):
state = super()._to_nice_serialization()
state.update({'qudit_labels': self._qudit_labels,
'qudit_udims': self._qudit_udims})
return state
@classmethod
def _from_nice_serialization(cls, state):
return cls(state['qudit_labels'], state['qudit_udims'])
@property
def qudit_labels(self):
"""The labels of the qudits in this state space."""
return self._qudit_labels
@property
def qudit_udims(self):
"""Integer Hilbert (unitary operator) space dimensions of the qudits in ths quantum state space."""
return self._qudit_udims
@property
def udim(self):
"""
Integer Hilbert (unitary operator) space dimension of this quantum state space.
"""
return _np.prod(self._qudit_udims)
@property
def dim(self):
"""Integer Hilbert-Schmidt (super-operator) or classical dimension of this state space."""
return self.udim**2
@property
def num_qudits(self): # may raise ValueError if the state space doesn't consist entirely of qudits
"""
The number of qubits in this quantum state space.
"""
return len(self._qudit_labels)
@property
def num_tensor_product_blocks(self):
"""
Get the number of tensor-product blocks which are direct-summed to get the final state space.
Returns
-------
int
"""
return 1
@property
def tensor_product_blocks_labels(self):
"""
Get the labels for all the tensor-product blocks.
Returns
-------
tuple of tuples
"""
return (self._qudit_labels,)
@property
def tensor_product_blocks_dimensions(self):
"""
Get the superoperator dimensions for all the tensor-product blocks.
Returns
-------
tuple of tuples
"""
return (tuple([udim**2 for udim in self._qudit_udims]),)
@property
def tensor_product_blocks_udimensions(self):
"""
Get the unitary operator dimensions for all the tensor-product blocks.
Returns
-------
tuple of tuples
"""
return (self._qudit_udims,)
@property
def tensor_product_blocks_types(self):
"""
Get the type (quantum vs classical) of all the tensor-product blocks.
Returns
-------
tuple of tuples
"""
return (('Q',) * len(self._qudit_labels))
def label_dimension(self, label):
"""
The superoperator dimension of the given label (from any tensor product block)
Parameters
----------
label : str or int
The label whose dimension should be retrieved.
Returns
-------
int
"""
if label in self._qudit_labels:
i = self._qudit_labels.index(label)
return self._qudit_udims[i]**2
else:
raise KeyError("Invalid qudit label: %s" % label)
def label_udimension(self, label):
"""
The unitary operator dimension of the given label (from any tensor product block)
Parameters
----------
label : str or int
The label whose dimension should be retrieved.
Returns
-------
int
"""
if label in self._qudit_labels:
i = self._qudit_labels.index(label)
return self._qudit_udims[i]
else:
raise KeyError("Invalid qudit label: %s" % label)
def label_tensor_product_block_index(self, label):
"""
The index of the tensor product block containing the given label.
Parameters
----------
label : str or int
The label whose index should be retrieved.
Returns
-------
int
"""
if label in self._qudit_labels:
return 0
else:
raise KeyError("Invalid qudit label: %s" % label)
def label_type(self, label):
"""
The type (quantum or classical) of the given label (from any tensor product block).
Parameters
----------
label : str or int
The label whose type should be retrieved.
Returns
-------
str
"""
if label in self._qudit_labels:
return 'Q'
else:
raise KeyError("Invalid qudit label: %s" % label)
def __str__(self):
return 'QuditSpace(' + str(self._qudit_labels) + ")"
class QubitSpace(QuditSpace):
"""
A state space consisting of N qubits.
"""
def __init__(self, nqubits_or_labels):
super().__init__(nqubits_or_labels, 2)
def _to_nice_serialization(self):
state = super()._to_nice_serialization()
state.update({'qubit_labels': self.qubit_labels})
return state
@classmethod
def _from_nice_serialization(cls, state):
return cls(state['qubit_labels'])
@property
def udim(self):
"""
Integer Hilbert (unitary operator) space dimension of this quantum state space.
"""
return 2**self.num_qubits
@property
def dim(self):
"""Integer Hilbert-Schmidt (super-operator) or classical dimension of this state space."""
return 4**self.num_qubits
@property
def qubit_labels(self):
"""The labels of the qubits"""
return self._qudit_labels
@property
def num_qubits(self): # may raise ValueError if the state space doesn't consist entirely of qubits
"""
The number of qubits in this quantum state space.
"""
return len(self.qubit_labels)
@property
def num_tensor_product_blocks(self):
"""
Get the number of tensor-product blocks which are direct-summed to get the final state space.
Returns
-------
int
"""
return 1
@property
def tensor_product_blocks_labels(self):
"""
Get the labels for all the tensor-product blocks.
Returns
-------
tuple of tuples
"""
return (self.qubit_labels,)
@property
def tensor_product_blocks_dimensions(self):
"""
Get the superoperator dimensions for all the tensor-product blocks.
Returns
-------
tuple of tuples
"""
return ((4,) * self.num_qubits,)
@property
def tensor_product_blocks_udimensions(self):
"""
Get the unitary operator dimensions for all the tensor-product blocks.
Returns
-------
tuple of tuples
"""
return ((2,) * self.num_qubits,)
@property
def tensor_product_blocks_types(self):
"""
Get the type (quantum vs classical) of all the tensor-product blocks.
Returns
-------
tuple of tuples
"""
return (('Q',) * self.num_qubits,)
def label_dimension(self, label):
"""
The superoperator dimension of the given label (from any tensor product block)
Parameters
----------
label : str or int
The label whose dimension should be retrieved.
Returns
-------
int
"""
if label in self.qubit_labels:
return 4
else:
raise KeyError("Invalid qubit label: %s" % label)
def label_udimension(self, label):
"""
The unitary operator dimension of the given label (from any tensor product block)
Parameters
----------
label : str or int
The label whose dimension should be retrieved.
Returns
-------
int
"""
if label in self.qubit_labels:
return 2
else:
raise KeyError("Invalid qubit label: %s" % label)
def label_tensor_product_block_index(self, label):
"""
The index of the tensor product block containing the given label.
Parameters