/
label.py
1337 lines (1090 loc) · 47.7 KB
/
label.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 Label class """
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 numbers as _numbers
import sys as _sys
import itertools as _itertools
import os
import inspect
debug_record = {}
try: basestring # noqa: F821
except NameError: basestring = str
def isstr(x): # Duplicates isstr from compattools! (b/c can't import!)
""" Return whether `x` has a string type """
return isinstance(x, basestring)
class Label(object):
"""
A label consisting of a string along with a tuple of
integers or sector-names specifying which qubits, or
more generally, parts of the Hilbert space that is
acted upon by an object so-labeled.
"""
# this is just an abstract base class for isinstance checking.
# actual labels will either be LabelTup or LabelStr instances,
# depending on whether the tuple of sector names exists or not.
# (the reason for separate classes is for hashing speed)
def __new__(cls, name, stateSpaceLabels=None, time=None, args=None):
"""
Creates a new Model-item label, which is divided into a simple string
label and a tuple specifying the part of the Hilbert space upon which the
item acts (often just qubit indices).
Parameters
----------
name : str
The item name. E.g., 'CNOT' or 'H'.
stateSpaceLabels : list or tuple, optional
A list or tuple that identifies which sectors/parts of the Hilbert
space is acted upon. In many cases, this is a list of integers
specifying the qubits on which a gate acts, when the ordering in the
list defines the 'direction' of the gate. If something other than
a list or tuple is passed, a single-element tuple is created
containing the passed object.
time : float
The time at which this label occurs (can be relative or absolute)
args : iterable of hashable types, optional
A list of "arguments" for this label. Having arguments makes the
Label even more resemble a function call, and supplies parameters
for the object (often a gate or layer operation) being labeled that
are fixed at circuit-creation time (i.e. are not optimized over).
For example, the angle of a continuously-variable X-rotation gate
could be an argument of a gate label, and one might create a label:
`Label('Gx', (0,), args=(pi/3,))`
"""
#print("Label.__new__ with name=", name, "sslbls=", stateSpaceLabels, "t=", time, "args=", args)
if isinstance(name, Label) and stateSpaceLabels is None:
return name # Note: Labels are immutable, so no need to copy
if not isstr(name) and stateSpaceLabels is None \
and isinstance(name, (tuple, list)):
#We're being asked to initialize from a non-string with no
# stateSpaceLabels, explicitly given. `name` could either be:
# 0) an empty tuple: () -> LabelTupTup with *no* subLabels.
# 1) a (name, ssl0, ssl1, ...) tuple -> LabelTup
# 2) a (subLabel1_tup, subLabel2_tup, ...) tuple -> LabelTupTup if
# length > 1 otherwise just initialize from subLabel1_tup.
# Note: subLabelX_tup could also be identified as a Label object
# (even a LabelStr)
if len(name) == 0:
if args: return LabelTupTupWithArgs((), time, args)
else: return LabelTupTup((), time)
elif isinstance(name[0], (tuple, list, Label)):
if len(name) > 1:
if args: return LabelTupTupWithArgs(name, time, args)
else: return LabelTupTup(name, time)
else:
return Label(name[0], time=time, args=args)
else:
#Case when stateSpaceLabels, etc, are given after name in a single tuple
tup = name
name = tup[0]
tup_args = []; stateSpaceLabels = []
next_is_arg = False
next_is_time = False
for x in tup[1:]:
if next_is_arg:
next_is_arg = False
tup_args.append(x); continue
if next_is_time:
next_is_time = False
time = x; continue
if isstr(x):
if x.startswith(';'):
assert(args is None), "Cannot supply args in tuple when `args` is given!"
if x == ';':
next_is_arg = True
else:
tup_args.append(x[1:])
continue
if x.startswith('!'):
assert(time is None), "Cannot supply time in tuple when `time` is given!"
if x == '!':
next_is_time = True
else:
time = float(x[1:])
continue
stateSpaceLabels.append(x)
args = tup_args if len(tup_args) > 0 else None
stateSpaceLabels = tuple(stateSpaceLabels) # needed for () and (None,) comparison below
if time is None:
time = 0.0 # for non-TupTup labels not setting a time is equivalent to setting it to 0.0
#print(" -> preproc with name=", name, "sslbls=", stateSpaceLabels, "t=", time, "args=", args)
if stateSpaceLabels is None or stateSpaceLabels in ((), (None,)):
if args:
return LabelTupWithArgs(name, (), time, args) # just use empty sslbls
else:
return LabelStr(name, time)
else:
if args: return LabelTupWithArgs(name, stateSpaceLabels, time, args)
else: return LabelTup(name, stateSpaceLabels, time)
def depth(self):
return 1 # most labels are depth=1
@property
def reps(self):
return 1 # most labels have only reps==1
def expand_subcircuits(self):
"""
Expand any sub-circuits within this label and return a resulting list
of component labels which doesn't include any :class:`CircuitLabel`
labels. This effectively expands any "boxes" or "exponentiation"
within this label.
Returns
-------
tuple
A tuple of component Labels (none of which should be
:class:`CircuitLabel`s).
"""
return (self,) # most labels just expand to themselves
class LabelTup(Label, tuple):
"""
A label consisting of a string along with a tuple of
integers or sector-names specifying which qubits, or
more generally, parts of the Hilbert space that is
acted upon by an object so-labeled.
"""
def __new__(cls, name, stateSpaceLabels, time=0.0):
"""
Creates a new Model-item label, which is divided into a simple string
label and a tuple specifying the part of the Hilbert space upon which the
item acts (often just qubit indices).
Parameters
----------
name : str
The item name. E.g., 'CNOT' or 'H'.
stateSpaceLabels : list or tuple
A list or tuple that identifies which sectors/parts of the Hilbert
space is acted upon. In many cases, this is a list of integers
specifying the qubits on which a gate acts, when the ordering in the
list defines the 'direction' of the gate. If something other than
a list or tuple is passed, a single-element tuple is created
containing the passed object.
time : float
The time at which this label occurs (can be relative or absolute)
"""
#Type checking
assert(isstr(name)), "`name` must be a string, but it's '%s'" % str(name)
assert(stateSpaceLabels is not None), "LabelTup must be initialized with non-None state-space labels"
assert(isinstance(time, float)), "`time` must be a floating point value, received: " + str(time)
if not isinstance(stateSpaceLabels, (tuple, list)):
stateSpaceLabels = (stateSpaceLabels,)
for ssl in stateSpaceLabels:
assert(isstr(ssl) or isinstance(ssl, _numbers.Integral)), \
"State space label '%s' must be a string or integer!" % str(ssl)
#Try to convert integer-strings to ints (for parsing from files...)
integerized_sslbls = []
for ssl in stateSpaceLabels:
try: integerized_sslbls.append(int(ssl))
except: integerized_sslbls.append(ssl)
# Regardless of whether the input is a list, tuple, or int, the state space labels
# (qubits) that the item/gate acts on are stored as a tuple (because tuples are immutable).
sslbls = tuple(integerized_sslbls)
tup = (name,) + sslbls
ret = tuple.__new__(cls, tup) # creates a LabelTup object using tuple's __new__
ret.time = time
return ret
@property
def name(self):
return self[0]
@property
def sslbls(self):
if len(self) > 1:
return self[1:]
else: return None
@property
def args(self):
return ()
@property
def components(self):
return (self,) # just a single "sub-label" component
@property
def qubits(self): # Used in Circuit
"""An alias for sslbls, since commonly these are just qubit indices"""
return self.sslbls
@property
def number_of_qubits(self): # Used in Circuit
return len(self.sslbls) if (self.sslbls is not None) else None
def has_prefix(self, prefix, typ="all"):
"""
Whether this label has the given `prefix`. Usually used to test whether
the label names a given type.
Parameters
----------
prefix : str
The prefix to check for.
typ : {"any","all"}
Whether, when there are multiple parts to the label, the prefix
must occur in any or all of the parts.
Returns
-------
bool
"""
return self.name.startswith(prefix)
def map_state_space_labels(self, mapper):
"""
Return a copy of this Label with all of the state-space-labels
(often just qubit labels) updated according to a mapping function.
For example, calling this function with `mapper = {0: 1, 1: 3}`
on the Label "Gcnot:0:1" would return "Gcnot:1:3".
Parameters
----------
mapper : dict or function
A dictionary whose keys are the existing state-space-label values
and whose value are the new labels, or a function which takes a
single (existing label) argument and returns a new label.
Returns
-------
Label
"""
if isinstance(mapper, dict):
mapped_sslbls = [mapper[sslbl] for sslbl in self.sslbls]
else: # assume mapper is callable
mapped_sslbls = [mapper(sslbl) for sslbl in self.sslbls]
return Label(self.name, mapped_sslbls)
#OLD
#def __iter__(self):
# return self.tup.__iter__()
#OLD
#def __iter__(self):
# """ Iterate over the name + state space labels """
# # Note: tuple(.) uses __iter__ to construct tuple rep.
# yield self.name
# if self.sslbls is not None:
# for ssl in self.sslbls:
# yield ssl
def __str__(self):
"""
Defines how a Label is printed out, e.g. Gx:0 or Gcnot:1:2
"""
#caller = inspect.getframeinfo(inspect.currentframe().f_back)
#ky = "%s:%s:%d" % (caller[2],os.path.basename(caller[0]),caller[1])
#debug_record[ky] = debug_record.get(ky, 0) + 1
s = str(self.name)
if self.sslbls: # test for None and len == 0
s += ":" + ":".join(map(str, self.sslbls))
if self.time != 0.0:
s += ("!%f" % self.time).rstrip('0').rstrip('.')
return s
def __repr__(self):
return "Label[" + str(self) + "]"
def __add__(self, s):
if isstr(s):
return LabelTup(self.name + s, self.sslbls)
else:
raise NotImplementedError("Cannot add %s to a Label" % str(type(s)))
def __eq__(self, other):
"""
Defines equality between gates, so that they are equal if their values
are equal.
"""
#Unnecessary now that we have a separate LabelStr
#if isstr(other):
# if self.sslbls: return False # tests for None and len > 0
# return self.name == other
return tuple.__eq__(self, other)
#OLD return self.name == other.name and self.sslbls == other.sslbls # ok to compare None
def __lt__(self, x):
return tuple.__lt__(self, tuple(x))
def __gt__(self, x):
return tuple.__gt__(self, tuple(x))
def __pygsti_reduce__(self):
return self.__reduce__()
def __reduce__(self):
# Need to tell serialization logic how to create a new Label since it's derived
# from the immutable tuple type (so cannot have its state set after creation)
return (LabelTup, (self[0], self[1:]), None)
def tonative(self):
""" Returns this label as native python types. Useful for
faster serialization.
"""
return tuple(self)
def replacename(self, oldname, newname):
""" Returns a label with `oldname` replaced by `newname`."""
return LabelTup(newname, self.sslbls) if (self.name == oldname) else self
def issimple(self):
""" Whether this is a "simple" (opaque w/a true name, from a
circuit perspective) label or not """
return True
__hash__ = tuple.__hash__ # this is why we derive from tuple - using the
# native tuple.__hash__ directly == speed boost
# We want LabelStr to act like the string literal type (not
# 'str' when we import unicode_literals above)
strlittype = str if _sys.version_info >= (3, 0) else unicode # (a *native* python type) # noqa: F821
class LabelStr(Label, strlittype):
"""
A Label for the special case when only a name is present (no
state-space-labels). We create this as a separate class
so that we can use the string hash function in a
"hardcoded" way - if we put switching logic in __hash__
the hashing gets *much* slower.
"""
def __new__(cls, name, time=0.0):
"""
Creates a new Model-item label, which is just a simple string label.
Parameters
----------
name : str
The item name. E.g., 'CNOT' or 'H'.
time : float
The time at which this label occurs (can be relative or absolute)
"""
#Type checking
assert(isstr(name)), "`name` must be a string, but it's '%s'" % str(name)
assert(isinstance(time, float)), "`time` must be a floating point value, received: " + str(time)
ret = strlittype.__new__(cls, name)
ret.time = time
return ret
@property
def name(self):
return strlittype(self[:])
@property
def sslbls(self):
return None
@property
def args(self):
return ()
@property
def components(self):
return (self,) # just a single "sub-label" component
@property
def qubits(self): # Used in Circuit
"""An alias for sslbls, since commonly these are just qubit indices"""
return None
@property
def number_of_qubits(self): # Used in Circuit
return None
def has_prefix(self, prefix, typ="all"):
"""
Whether this label has the given `prefix`. Usually used to test whether
the label names a given type.
Parameters
----------
prefix : str
The prefix to check for.
typ : {"any","all"}
Whether, when there are multiple parts to the label, the prefix
must occur in any or all of the parts.
Returns
-------
bool
"""
return self.startswith(prefix)
def __str__(self):
s = self[:] # converts to a normal str
if self.time != 0.0:
s += ("!%f" % self.time).rstrip('0').rstrip('.')
return s
def __repr__(self):
return "Label{" + strlittype(self) + "}"
def __add__(self, s):
if isstr(s):
return LabelStr(self.name + strlittype(s))
else:
raise NotImplementedError("Cannot add %s to a Label" % str(type(s)))
def __eq__(self, other):
"""
Defines equality between gates, so that they are equal if their values
are equal.
"""
return strlittype.__eq__(self, other)
def __lt__(self, x):
return strlittype.__lt__(self, strlittype(x))
def __gt__(self, x):
return strlittype.__gt__(self, strlittype(x))
def __pygsti_reduce__(self):
return self.__reduce__()
def __reduce__(self):
# Need to tell serialization logic how to create a new Label since it's derived
# from the immutable tuple type (so cannot have its state set after creation)
return (LabelStr, (strlittype(self),), None)
def tonative(self):
""" Returns this label as native python types. Useful for
faster serialization.
"""
return strlittype(self)
def replacename(self, oldname, newname):
""" Returns a label with `oldname` replaced by `newname`."""
return LabelStr(newname) if (self.name == oldname) else self
def issimple(self):
""" Whether this is a "simple" (opaque w/a true name, from a
circuit perspective) label or not """
return True
__hash__ = strlittype.__hash__ # this is why we derive from tuple - using the
# native tuple.__hash__ directly == speed boost
class LabelTupTup(Label, tuple):
"""
A label consisting of a *tuple* of (string, state-space-labels) tuples
which labels a parallel layer/level of a circuit.
"""
def __new__(cls, tupOfTups, time=None):
"""
Creates a new Model-item label, which is a tuple of tuples of simple
string labels and tuples specifying the part of the Hilbert space upon
which that item acts (often just qubit indices).
Parameters
----------
tupOfTups : tuple
The item data - a tuple of (string, state-space-labels) tuples
which labels a parallel layer/level of a circuit.
"""
assert(time is None or isinstance(time, float)), "`time` must be a floating point value, received: " + str(time)
tupOfLabels = tuple((Label(tup) for tup in tupOfTups)) # Note: tup can also be a Label obj
ret = tuple.__new__(cls, tupOfLabels) # creates a LabelTupTup object using tuple's __new__
if time is None:
ret.time = 0.0 if len(tupOfLabels) == 0 else \
max([lbl.time for lbl in tupOfLabels])
else:
ret.time = time
return ret
@property
def name(self):
# TODO - something intelligent here?
# no real "name" for a compound label... but want it to be a string so
# users can use .startswith, etc.
return "COMPOUND"
@property
def sslbls(self):
# Note: if any component has sslbls == None, which signifies operating
# on *all* qubits, then this label is on *all* qubites
s = set()
for lbl in self:
if lbl.sslbls is None: return None
s.update(lbl.sslbls)
return tuple(sorted(list(s)))
@property
def args(self):
return ()
@property
def components(self):
return self # self is a tuple of "sub-label" components
@property
def qubits(self): # Used in Circuit
"""An alias for sslbls, since commonly these are just qubit indices"""
return self.sslbls
@property
def number_of_qubits(self): # Used in Circuit
return len(self.sslbls) if (self.sslbls is not None) else None
def has_prefix(self, prefix, typ="all"):
"""
Whether this label has the given `prefix`. Usually used to test whether
the label names a given type.
Parameters
----------
prefix : str
The prefix to check for.
typ : {"any","all"}
Whether, when there are multiple parts to the label, the prefix
must occur in any or all of the parts.
Returns
-------
bool
"""
if typ == "all":
return all([lbl.has_prefix(prefix) for lbl in self])
elif typ == "any":
return any([lbl.has_prefix(prefix) for lbl in self])
else: raise ValueError("Invalid `typ` arg: %s" % str(typ))
def map_state_space_labels(self, mapper):
"""
Return a copy of this Label with all of the state-space-labels
(often just qubit labels) updated according to a mapping function.
For example, calling this function with `mapper = {0: 1, 1: 3}`
on the Label "Gcnot:0:1" would return "Gcnot:1:3".
Parameters
----------
mapper : dict or function
A dictionary whose keys are the existing state-space-label values
and whose value are the new labels, or a function which takes a
single (existing label) argument and returns a new label.
Returns
-------
Label
"""
return LabelTupTup(tuple((lbl.map_state_space_labels(mapper) for lbl in self)))
def __str__(self):
"""
Defines how a Label is printed out, e.g. Gx:0 or Gcnot:1:2
"""
return "[" + "".join([str(lbl) for lbl in self]) + "]"
def __repr__(self):
return "Label[" + str(self) + "]"
def __add__(self, s):
raise NotImplementedError("Cannot add %s to a Label" % str(type(s)))
def __eq__(self, other):
"""
Defines equality between gates, so that they are equal if their values
are equal.
"""
#Unnecessary now that we have a separate LabelStr
#if isstr(other):
# if self.sslbls: return False # tests for None and len > 0
# return self.name == other
return tuple.__eq__(self, other)
#OLD return self.name == other.name and self.sslbls == other.sslbls # ok to compare None
def __lt__(self, x):
return tuple.__lt__(self, tuple(x))
def __gt__(self, x):
return tuple.__gt__(self, tuple(x))
def __pygsti_reduce__(self):
return self.__reduce__()
def __reduce__(self):
# Need to tell serialization logic how to create a new Label since it's derived
# from the immutable tuple type (so cannot have its state set after creation)
return (LabelTupTup, (self[:],), None)
def __contains__(self, x):
# "recursive" contains checks component containers
return any([(x == layer or x in layer) for layer in self.components])
def tonative(self):
""" Returns this label as native python types. Useful for
faster serialization.
"""
return tuple((x.tonative() for x in self))
def replacename(self, oldname, newname):
""" Returns a label with `oldname` replaced by `newname`."""
return LabelTupTup(tuple((x.replacename(oldname, newname) for x in self)))
def issimple(self):
""" Whether this is a "simple" (opaque w/a true name, from a
circuit perspective) label or not """
return False
def depth(self):
if len(self.components) == 0: return 1 # still depth 1 even if empty
return max([x.depth() for x in self.components])
def expand_subcircuits(self):
"""
Expand any sub-circuits within this label and return a resulting list
of component labels which doesn't include any :class:`CircuitLabel`
labels. This effectively expands any "boxes" or "exponentiation"
within this label.
Returns
-------
tuple
A tuple of component Labels (none of which should be
:class:`CircuitLabel`s).
"""
ret = []
expanded_comps = [x.expand_subcircuits() for x in self.components]
#DEBUG TODO REMOVE
#print("DB: expaned comps:")
#for i,x in enumerate(expanded_comps):
# print(i,": ",x)
for i in range(self.depth()): # depth == # of layers when expanded
ec = []
for expanded_comp in expanded_comps:
if i < len(expanded_comp):
ec.extend(expanded_comp[i].components) # .components = vertical expansion
#assert(len(ec) > 0), "Logic error!" #this is ok (e.g. an idle subcircuit)
ret.append(LabelTupTup(ec))
return tuple(ret)
__hash__ = tuple.__hash__ # this is why we derive from tuple - using the
# native tuple.__hash__ directly == speed boost
class CircuitLabel(Label, tuple):
def __new__(cls, name, tupOfLayers, stateSpaceLabels, reps=1, time=None):
"""
Creates a new Model-item label, which defines a set of other labels
as a sub-circuit and allows that sub-circuit to be repeated some integer
number of times. A `CircuitLabel` can be visualized as placing a
(named) box around some set of labels and optionally exponentiating
that box.
Internally, a circuit labels look very similar to `LabelTupTup` objects,
holding a tuple of tuples defining the component labels (circuit layers).
Parameters
----------
name : str
The name of the sub-circuit (box). Cannot be `None`, but can be
empty.
tupOfLayers : tuple
The item data - a tuple of tuples which label the components
(layers) within this label.
stateSpaceLabels : list or tuple
A list or tuple that identifies which sectors/parts of the Hilbert
space is acted upon. In many cases, this is a list of integers
specifying the qubits on which a gate acts, when the ordering in the
list defines the 'direction' of the gate.
reps : int, optional
The "exponent" - the number of times the `tupOfLayers` labels are
repeated.
time : float
The time at which this label occurs (can be relative or absolute)
"""
#if name is None: name = '' # backward compatibility (temporary - TODO REMOVE)
assert(isinstance(reps, _numbers.Integral) and isstr(name)
), "Invalid name or reps: %s %s" % (str(name), str(reps))
tupOfLabels = tuple((Label(tup) for tup in tupOfLayers)) # Note: tup can also be a Label obj
# creates a CircuitLabel object using tuple's __new__
ret = tuple.__new__(cls, (name, stateSpaceLabels, reps) + tupOfLabels)
if time is None:
ret.time = 0.0 if len(tupOfLabels) == 0 else \
sum([lbl.time for lbl in tupOfLabels]) # sum b/c components are *layers* of sub-circuit
else:
ret.time = time
return ret
@property
def name(self):
return self[0]
@property
def sslbls(self):
return self[1]
@property
def reps(self):
return self[2]
@property
def args(self):
raise NotImplementedError("TODO!")
@property
def components(self):
return self[3:]
@property
def qubits(self): # Used in Circuit
"""An alias for sslbls, since commonly these are just qubit indices"""
return self.sslbls
@property
def number_of_qubits(self): # Used in Circuit
return len(self.sslbls) if (self.sslbls is not None) else None
def has_prefix(self, prefix, typ="all"):
"""
Whether this label has the given `prefix`. Usually used to test whether
the label names a given type.
Parameters
----------
prefix : str
The prefix to check for.
typ : {"any","all"}
Whether, when there are multiple parts to the label, the prefix
must occur in any or all of the parts.
Returns
-------
bool
"""
return self.name.startswith(prefix)
def map_state_space_labels(self, mapper):
"""
Return a copy of this Label with all of the state-space-labels
(often just qubit labels) updated according to a mapping function.
For example, calling this function with `mapper = {0: 1, 1: 3}`
on the Label "Gcnot:0:1" would return "Gcnot:1:3".
Parameters
----------
mapper : dict or function
A dictionary whose keys are the existing state-space-label values
and whose value are the new labels, or a function which takes a
single (existing label) argument and returns a new label.
Returns
-------
Label
"""
if isinstance(mapper, dict):
mapped_sslbls = [mapper[sslbl] for sslbl in self.sslbls]
else: # assume mapper is callable
mapped_sslbls = [mapper(sslbl) for sslbl in self.sslbls]
return CircuitLabel(self.name,
tuple((lbl.map_state_space_labels(mapper) for lbl in self.components)),
mapped_sslbls,
self[2])
def __str__(self):
"""
Defines how a Label is printed out, e.g. Gx:0 or Gcnot:1:2
"""
if len(self.name) > 0:
s = self.name
if self.time != 0.0:
s += ("!%f" % self.time).rstrip('0').rstrip('.')
else:
s = "".join([str(lbl) for lbl in self.components])
if self.time != 0.0:
s += ("!%f" % self.time).rstrip('0').rstrip('.')
if len(self.components) > 1:
s = "(" + s + ")" # add parenthesis
if self[2] != 1: s += "^%d" % self[2]
return s
def __repr__(self):
return "CircuitLabel[" + str(self) + "]"
def __add__(self, s):
raise NotImplementedError("Cannot add %s to a Label" % str(type(s)))
def __eq__(self, other):
"""
Defines equality between gates, so that they are equal if their values
are equal.
"""
#Unnecessary now that we have a separate LabelStr
#if isstr(other):
# if self.sslbls: return False # tests for None and len > 0
# return self.name == other
return tuple.__eq__(self, other)
#OLD return self.name == other.name and self.sslbls == other.sslbls # ok to compare None
def __lt__(self, x):
return tuple.__lt__(self, tuple(x))
def __gt__(self, x):
return tuple.__gt__(self, tuple(x))
def __pygsti_reduce__(self):
return self.__reduce__()
def __reduce__(self):
# Need to tell serialization logic how to create a new Label since it's derived
# from the immutable tuple type (so cannot have its state set after creation)
return (CircuitLabel, (self[0], self[3:], self[1], self[2]), None)
def __contains__(self, x):
# "recursive" contains checks component containers
return any([(x == layer or x in layer) for layer in self.components])
def tonative(self):
""" Returns this label as native python types. Useful for
faster serialization.
"""
return self[0:3] + tuple((x.tonative() for x in self.components))
def replacename(self, oldname, newname):
""" Returns a label with `oldname` replaced by `newname`."""
return CircuitLabel(self.name,
tuple((x.replacename(oldname, newname) for x in self.components)),
self.sslbls,
self[2])
def issimple(self):
""" Whether this is a "simple" (opaque w/a true name, from a
circuit perspective) label or not """
return True # still true - even though can have components!
def depth(self):
return sum([x.depth() for x in self.components]) * self.reps
def expand_subcircuits(self):
"""
Expand any sub-circuits within this label and return a resulting list
of component labels which doesn't include any :class:`CircuitLabel`
labels. This effectively expands any "boxes" or "exponentiation"
within this label.
Returns
-------
tuple
A tuple of component Labels (none of which should be
:class:`CircuitLabel`s).
"""
#REMOVE print("Expanding subcircuit components: ",self.components)
#REMOVE print(" --> ",[ x.expand_subcircuits() for x in self.components ])
return tuple(_itertools.chain(*[x.expand_subcircuits() for x in self.components])) * self.reps
__hash__ = tuple.__hash__ # this is why we derive from tuple - using the
# native tuple.__hash__ directly == speed boost
#class NamedLabelTupTup(Label,tuple):
# def __new__(cls,name,tupOfTups):
# pass
class LabelTupWithArgs(Label, tuple):
"""
Same as LabelTup, but includes slots for args and time
"""
def __new__(cls, name, stateSpaceLabels, time=0.0, args=()):
"""
Creates a new Model-item label, which is divided into a simple string
label, a tuple specifying the part of the Hilbert space upon which the
item acts (often just qubit indices), a time, and arguments.
Parameters
----------
name : str
The item name. E.g., 'CNOT' or 'H'.
stateSpaceLabels : list or tuple
A list or tuple that identifies which sectors/parts of the Hilbert
space is acted upon. In many cases, this is a list of integers
specifying the qubits on which a gate acts, when the ordering in the
list defines the 'direction' of the gate. If something other than
a list or tuple is passed, a single-element tuple is created
containing the passed object.
time : float
The time at which this label occurs (can be relative or absolute)
args : iterable of hashable types
A list of "arguments" for this label.
"""
#Type checking
assert(isstr(name)), "`name` must be a string, but it's '%s'" % str(name)
assert(stateSpaceLabels is not None), "LabelTup must be initialized with non-None state-space labels"
if not isinstance(stateSpaceLabels, (tuple, list)):
stateSpaceLabels = (stateSpaceLabels,)
for ssl in stateSpaceLabels:
assert(isstr(ssl) or isinstance(ssl, _numbers.Integral)), \
"State space label '%s' must be a string or integer!" % str(ssl)
assert(isinstance(time, float)), "`time` must be a floating point value, received: " + str(time)
assert(len(args) > 0), "`args` must be a nonempty list/tuple of hashable arguments"
#TODO: check that all args are hashable?
#Try to convert integer-strings to ints (for parsing from files...)
integerized_sslbls = []
for ssl in stateSpaceLabels:
try: integerized_sslbls.append(int(ssl))
except: integerized_sslbls.append(ssl)
# Regardless of whether the input is a list, tuple, or int, the state space labels
# (qubits) that the item/gate acts on are stored as a tuple (because tuples are immutable).
sslbls = tuple(integerized_sslbls)
args = tuple(args)
tup = (name, 2 + len(args)) + args + sslbls # stores: (name, K, args, sslbls)
# where K is the index of the start of the sslbls (or 1 more than the last arg index)
ret = tuple.__new__(cls, tup) # creates a LabelTup object using tuple's __new__
ret.time = time
return ret
@property
def name(self):
return self[0]