libqasm 0.5.2__cp311-cp311-macosx_10_10_universal2.whl → 0.6.1__cp311-cp311-macosx_10_10_universal2.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
cqasm/v3x/types.py CHANGED
@@ -633,28 +633,14 @@ class TypeBase(Node):
633
633
  typ = cbor.get('@t', None)
634
634
  if typ is None:
635
635
  raise ValueError('type (@t) field is missing from node serialization')
636
- if typ == 'Axis':
637
- return Axis._deserialize(cbor, seq_to_ob, links)
638
636
  if typ == 'Bool':
639
637
  return Bool._deserialize(cbor, seq_to_ob, links)
640
638
  if typ == 'Int':
641
639
  return Int._deserialize(cbor, seq_to_ob, links)
642
- if typ == 'Real':
643
- return Real._deserialize(cbor, seq_to_ob, links)
644
- if typ == 'Complex':
645
- return Complex._deserialize(cbor, seq_to_ob, links)
646
- if typ == 'Bit':
647
- return Bit._deserialize(cbor, seq_to_ob, links)
640
+ if typ == 'Float':
641
+ return Float._deserialize(cbor, seq_to_ob, links)
648
642
  if typ == 'Qubit':
649
643
  return Qubit._deserialize(cbor, seq_to_ob, links)
650
- if typ == 'BoolArray':
651
- return BoolArray._deserialize(cbor, seq_to_ob, links)
652
- if typ == 'IntArray':
653
- return IntArray._deserialize(cbor, seq_to_ob, links)
654
- if typ == 'RealArray':
655
- return RealArray._deserialize(cbor, seq_to_ob, links)
656
- if typ == 'BitArray':
657
- return BitArray._deserialize(cbor, seq_to_ob, links)
658
644
  if typ == 'QubitArray':
659
645
  return QubitArray._deserialize(cbor, seq_to_ob, links)
660
646
  raise ValueError('unknown or unexpected type (@t) found in node serialization')
@@ -687,8 +673,8 @@ class MultiTypeBase(_Multiple):
687
673
 
688
674
  _typemap['TypeBase'] = TypeBase
689
675
 
690
- class Axis(TypeBase):
691
- """Type of an axis (x, y, and z vectors)."""
676
+ class Bool(TypeBase):
677
+ """Type of a boolean."""
692
678
 
693
679
  __slots__ = []
694
680
 
@@ -700,7 +686,7 @@ class Axis(TypeBase):
700
686
 
701
687
  def __eq__(self, other):
702
688
  """Equality operator. Ignores annotations!"""
703
- if not isinstance(other, Axis):
689
+ if not isinstance(other, Bool):
704
690
  return False
705
691
  if self.size != other.size:
706
692
  return False
@@ -713,7 +699,7 @@ class Axis(TypeBase):
713
699
  strings of the annotations that are to be printed. links specifies the
714
700
  maximum link recursion depth."""
715
701
  s = [' '*indent]
716
- s.append('Axis(')
702
+ s.append('Bool(')
717
703
  if annotations is None:
718
704
  annotations = []
719
705
  for key in annotations:
@@ -753,7 +739,7 @@ class Axis(TypeBase):
753
739
 
754
740
  def copy(self):
755
741
  """Returns a shallow copy of this node."""
756
- return Axis(
742
+ return Bool(
757
743
  size=self._attr_size
758
744
  )
759
745
 
@@ -763,7 +749,7 @@ class Axis(TypeBase):
763
749
  original tree. If you're not cloning a subtree in a context where this
764
750
  is the desired behavior, you may want to use the copy.deepcopy() from
765
751
  the stdlib instead, which should copy links correctly."""
766
- return Axis(
752
+ return Bool(
767
753
  size=_cloned(self._attr_size)
768
754
  )
769
755
 
@@ -780,8 +766,8 @@ class Axis(TypeBase):
780
766
  typ = cbor.get('@t', None)
781
767
  if typ is None:
782
768
  raise ValueError('type (@t) field is missing from node serialization')
783
- if typ != 'Axis':
784
- raise ValueError('found node serialization for ' + typ + ', but expected Axis')
769
+ if typ != 'Bool':
770
+ raise ValueError('found node serialization for ' + typ + ', but expected Bool')
785
771
 
786
772
  # Deserialize the size field.
787
773
  field = cbor.get('size', None)
@@ -792,8 +778,8 @@ class Axis(TypeBase):
792
778
  else:
793
779
  f_size = cqasm.v3x.primitives.deserialize(cqasm.v3x.primitives.Int, field)
794
780
 
795
- # Construct the Axis node.
796
- node = Axis(f_size)
781
+ # Construct the Bool node.
782
+ node = Bool(f_size)
797
783
 
798
784
  # Deserialize annotations.
799
785
  for key, val in cbor.items():
@@ -817,7 +803,7 @@ class Axis(TypeBase):
817
803
  CBOR serialization. The tree that the node belongs to must be
818
804
  well-formed. id_map must match Python id() calls for all nodes to unique
819
805
  integers, to use for the sequence number representation of links."""
820
- cbor = {'@i': id_map[id(self)], '@t': 'Axis'}
806
+ cbor = {'@i': id_map[id(self)], '@t': 'Bool'}
821
807
 
822
808
  # Serialize the size field.
823
809
  if hasattr(self._attr_size, 'serialize_cbor'):
@@ -832,166 +818,17 @@ class Axis(TypeBase):
832
818
  return cbor
833
819
 
834
820
 
835
- class MultiAxis(_Multiple):
836
- """Wrapper for an edge with multiple Axis objects."""
837
-
838
- _T = Axis
839
-
840
-
841
- _typemap['Axis'] = Axis
842
-
843
- class Bit(TypeBase):
844
- __slots__ = []
845
-
846
- def __init__(
847
- self,
848
- size=None,
849
- ):
850
- super().__init__(size=size)
851
-
852
- def __eq__(self, other):
853
- """Equality operator. Ignores annotations!"""
854
- if not isinstance(other, Bit):
855
- return False
856
- if self.size != other.size:
857
- return False
858
- return True
859
-
860
- def dump(self, indent=0, annotations=None, links=1):
861
- """Returns a debug representation of this tree as a multiline string.
862
- indent is the number of double spaces prefixed before every line.
863
- annotations, if specified, must be a set-like object containing the key
864
- strings of the annotations that are to be printed. links specifies the
865
- maximum link recursion depth."""
866
- s = [' '*indent]
867
- s.append('Bit(')
868
- if annotations is None:
869
- annotations = []
870
- for key in annotations:
871
- if key in self:
872
- s.append(' # {}: {}'.format(key, self[key]))
873
- s.append('\n')
874
- indent += 1
875
- s.append(' '*indent)
876
- s.append('size: ')
877
- s.append(str(self.size) + '\n')
878
- indent -= 1
879
- s.append(' '*indent)
880
- s.append(')')
881
- return ''.join(s)
882
-
883
- __str__ = dump
884
- __repr__ = dump
885
-
886
- def find_reachable(self, id_map=None):
887
- """Returns a dictionary mapping Python id() values to stable sequence
888
- numbers for all nodes in the tree rooted at this node. If id_map is
889
- specified, found nodes are appended to it."""
890
- if id_map is None:
891
- id_map = {}
892
- if id(self) in id_map:
893
- raise NotWellFormed('node {!r} with id {} occurs more than once'.format(self, id(self)))
894
- id_map[id(self)] = len(id_map)
895
- return id_map
896
-
897
- def check_complete(self, id_map=None):
898
- """Raises NotWellFormed if the tree rooted at this node is not
899
- well-formed. If id_map is specified, this tree is only a subtree in the
900
- context of a larger tree, and id_map must be a dict mapping from Python
901
- id() codes to tree indices for all reachable nodes."""
902
- if id_map is None:
903
- id_map = self.find_reachable()
904
-
905
- def copy(self):
906
- """Returns a shallow copy of this node."""
907
- return Bit(
908
- size=self._attr_size
909
- )
910
-
911
- def clone(self):
912
- """Returns a deep copy of this node. This mimics the C++ interface,
913
- deficiencies with links included; that is, links always point to the
914
- original tree. If you're not cloning a subtree in a context where this
915
- is the desired behavior, you may want to use the copy.deepcopy() from
916
- the stdlib instead, which should copy links correctly."""
917
- return Bit(
918
- size=_cloned(self._attr_size)
919
- )
920
-
921
- @staticmethod
922
- def _deserialize(cbor, seq_to_ob, links):
923
- """Attempts to deserialize the given cbor object (in Python primitive
924
- representation) into a node of this type. All (sub)nodes are added to
925
- the seq_to_ob dict, indexed by their cbor sequence number. All links are
926
- registered in the links list by means of a two-tuple of the setter
927
- function for the link field and the sequence number of the target node.
928
- """
929
- if not isinstance(cbor, dict):
930
- raise TypeError('node description object must be a dict')
931
- typ = cbor.get('@t', None)
932
- if typ is None:
933
- raise ValueError('type (@t) field is missing from node serialization')
934
- if typ != 'Bit':
935
- raise ValueError('found node serialization for ' + typ + ', but expected Bit')
936
-
937
- # Deserialize the size field.
938
- field = cbor.get('size', None)
939
- if not isinstance(field, dict):
940
- raise ValueError('missing or invalid serialization of field size')
941
- if hasattr(cqasm.v3x.primitives.Int, 'deserialize_cbor'):
942
- f_size = cqasm.v3x.primitives.Int.deserialize_cbor(field)
943
- else:
944
- f_size = cqasm.v3x.primitives.deserialize(cqasm.v3x.primitives.Int, field)
945
-
946
- # Construct the Bit node.
947
- node = Bit(f_size)
948
-
949
- # Deserialize annotations.
950
- for key, val in cbor.items():
951
- if not (key.startswith('{') and key.endswith('}')):
952
- continue
953
- key = key[1:-1]
954
- node[key] = cqasm.v3x.primitives.deserialize(key, val)
955
-
956
- # Register node in sequence number lookup.
957
- seq = cbor.get('@i', None)
958
- if not isinstance(seq, int):
959
- raise ValueError('sequence number field (@i) is not an integer or missing from node serialization')
960
- if seq in seq_to_ob:
961
- raise ValueError('duplicate sequence number %d' % seq)
962
- seq_to_ob[seq] = node
963
-
964
- return node
965
-
966
- def _serialize(self, id_map):
967
- """Serializes this node to the Python primitive representation of its
968
- CBOR serialization. The tree that the node belongs to must be
969
- well-formed. id_map must match Python id() calls for all nodes to unique
970
- integers, to use for the sequence number representation of links."""
971
- cbor = {'@i': id_map[id(self)], '@t': 'Bit'}
972
-
973
- # Serialize the size field.
974
- if hasattr(self._attr_size, 'serialize_cbor'):
975
- cbor['size'] = self._attr_size.serialize_cbor()
976
- else:
977
- cbor['size'] = cqasm.v3x.primitives.serialize(cqasm.v3x.primitives.Int, self._attr_size)
978
-
979
- # Serialize annotations.
980
- for key, val in self._annot.items():
981
- cbor['{%s}' % key] = _py_to_cbor(cqasm.v3x.primitives.serialize(key, val))
982
-
983
- return cbor
984
-
821
+ class MultiBool(_Multiple):
822
+ """Wrapper for an edge with multiple Bool objects."""
985
823
 
986
- class MultiBit(_Multiple):
987
- """Wrapper for an edge with multiple Bit objects."""
824
+ _T = Bool
988
825
 
989
- _T = Bit
990
826
 
827
+ _typemap['Bool'] = Bool
991
828
 
992
- _typemap['Bit'] = Bit
829
+ class Float(TypeBase):
830
+ """Type of a float number (IEEE double)."""
993
831
 
994
- class BitArray(TypeBase):
995
832
  __slots__ = []
996
833
 
997
834
  def __init__(
@@ -1002,7 +839,7 @@ class BitArray(TypeBase):
1002
839
 
1003
840
  def __eq__(self, other):
1004
841
  """Equality operator. Ignores annotations!"""
1005
- if not isinstance(other, BitArray):
842
+ if not isinstance(other, Float):
1006
843
  return False
1007
844
  if self.size != other.size:
1008
845
  return False
@@ -1015,7 +852,7 @@ class BitArray(TypeBase):
1015
852
  strings of the annotations that are to be printed. links specifies the
1016
853
  maximum link recursion depth."""
1017
854
  s = [' '*indent]
1018
- s.append('BitArray(')
855
+ s.append('Float(')
1019
856
  if annotations is None:
1020
857
  annotations = []
1021
858
  for key in annotations:
@@ -1055,7 +892,7 @@ class BitArray(TypeBase):
1055
892
 
1056
893
  def copy(self):
1057
894
  """Returns a shallow copy of this node."""
1058
- return BitArray(
895
+ return Float(
1059
896
  size=self._attr_size
1060
897
  )
1061
898
 
@@ -1065,7 +902,7 @@ class BitArray(TypeBase):
1065
902
  original tree. If you're not cloning a subtree in a context where this
1066
903
  is the desired behavior, you may want to use the copy.deepcopy() from
1067
904
  the stdlib instead, which should copy links correctly."""
1068
- return BitArray(
905
+ return Float(
1069
906
  size=_cloned(self._attr_size)
1070
907
  )
1071
908
 
@@ -1082,8 +919,8 @@ class BitArray(TypeBase):
1082
919
  typ = cbor.get('@t', None)
1083
920
  if typ is None:
1084
921
  raise ValueError('type (@t) field is missing from node serialization')
1085
- if typ != 'BitArray':
1086
- raise ValueError('found node serialization for ' + typ + ', but expected BitArray')
922
+ if typ != 'Float':
923
+ raise ValueError('found node serialization for ' + typ + ', but expected Float')
1087
924
 
1088
925
  # Deserialize the size field.
1089
926
  field = cbor.get('size', None)
@@ -1094,8 +931,8 @@ class BitArray(TypeBase):
1094
931
  else:
1095
932
  f_size = cqasm.v3x.primitives.deserialize(cqasm.v3x.primitives.Int, field)
1096
933
 
1097
- # Construct the BitArray node.
1098
- node = BitArray(f_size)
934
+ # Construct the Float node.
935
+ node = Float(f_size)
1099
936
 
1100
937
  # Deserialize annotations.
1101
938
  for key, val in cbor.items():
@@ -1119,7 +956,7 @@ class BitArray(TypeBase):
1119
956
  CBOR serialization. The tree that the node belongs to must be
1120
957
  well-formed. id_map must match Python id() calls for all nodes to unique
1121
958
  integers, to use for the sequence number representation of links."""
1122
- cbor = {'@i': id_map[id(self)], '@t': 'BitArray'}
959
+ cbor = {'@i': id_map[id(self)], '@t': 'Float'}
1123
960
 
1124
961
  # Serialize the size field.
1125
962
  if hasattr(self._attr_size, 'serialize_cbor'):
@@ -1134,16 +971,16 @@ class BitArray(TypeBase):
1134
971
  return cbor
1135
972
 
1136
973
 
1137
- class MultiBitArray(_Multiple):
1138
- """Wrapper for an edge with multiple BitArray objects."""
974
+ class MultiFloat(_Multiple):
975
+ """Wrapper for an edge with multiple Float objects."""
1139
976
 
1140
- _T = BitArray
977
+ _T = Float
1141
978
 
1142
979
 
1143
- _typemap['BitArray'] = BitArray
980
+ _typemap['Float'] = Float
1144
981
 
1145
- class Bool(TypeBase):
1146
- """Type of a boolean."""
982
+ class Int(TypeBase):
983
+ """Type of an integer (signed 64-bit)."""
1147
984
 
1148
985
  __slots__ = []
1149
986
 
@@ -1155,7 +992,7 @@ class Bool(TypeBase):
1155
992
 
1156
993
  def __eq__(self, other):
1157
994
  """Equality operator. Ignores annotations!"""
1158
- if not isinstance(other, Bool):
995
+ if not isinstance(other, Int):
1159
996
  return False
1160
997
  if self.size != other.size:
1161
998
  return False
@@ -1168,7 +1005,7 @@ class Bool(TypeBase):
1168
1005
  strings of the annotations that are to be printed. links specifies the
1169
1006
  maximum link recursion depth."""
1170
1007
  s = [' '*indent]
1171
- s.append('Bool(')
1008
+ s.append('Int(')
1172
1009
  if annotations is None:
1173
1010
  annotations = []
1174
1011
  for key in annotations:
@@ -1208,7 +1045,7 @@ class Bool(TypeBase):
1208
1045
 
1209
1046
  def copy(self):
1210
1047
  """Returns a shallow copy of this node."""
1211
- return Bool(
1048
+ return Int(
1212
1049
  size=self._attr_size
1213
1050
  )
1214
1051
 
@@ -1218,7 +1055,7 @@ class Bool(TypeBase):
1218
1055
  original tree. If you're not cloning a subtree in a context where this
1219
1056
  is the desired behavior, you may want to use the copy.deepcopy() from
1220
1057
  the stdlib instead, which should copy links correctly."""
1221
- return Bool(
1058
+ return Int(
1222
1059
  size=_cloned(self._attr_size)
1223
1060
  )
1224
1061
 
@@ -1235,8 +1072,8 @@ class Bool(TypeBase):
1235
1072
  typ = cbor.get('@t', None)
1236
1073
  if typ is None:
1237
1074
  raise ValueError('type (@t) field is missing from node serialization')
1238
- if typ != 'Bool':
1239
- raise ValueError('found node serialization for ' + typ + ', but expected Bool')
1075
+ if typ != 'Int':
1076
+ raise ValueError('found node serialization for ' + typ + ', but expected Int')
1240
1077
 
1241
1078
  # Deserialize the size field.
1242
1079
  field = cbor.get('size', None)
@@ -1247,8 +1084,8 @@ class Bool(TypeBase):
1247
1084
  else:
1248
1085
  f_size = cqasm.v3x.primitives.deserialize(cqasm.v3x.primitives.Int, field)
1249
1086
 
1250
- # Construct the Bool node.
1251
- node = Bool(f_size)
1087
+ # Construct the Int node.
1088
+ node = Int(f_size)
1252
1089
 
1253
1090
  # Deserialize annotations.
1254
1091
  for key, val in cbor.items():
@@ -1272,7 +1109,7 @@ class Bool(TypeBase):
1272
1109
  CBOR serialization. The tree that the node belongs to must be
1273
1110
  well-formed. id_map must match Python id() calls for all nodes to unique
1274
1111
  integers, to use for the sequence number representation of links."""
1275
- cbor = {'@i': id_map[id(self)], '@t': 'Bool'}
1112
+ cbor = {'@i': id_map[id(self)], '@t': 'Int'}
1276
1113
 
1277
1114
  # Serialize the size field.
1278
1115
  if hasattr(self._attr_size, 'serialize_cbor'):
@@ -1287,15 +1124,15 @@ class Bool(TypeBase):
1287
1124
  return cbor
1288
1125
 
1289
1126
 
1290
- class MultiBool(_Multiple):
1291
- """Wrapper for an edge with multiple Bool objects."""
1127
+ class MultiInt(_Multiple):
1128
+ """Wrapper for an edge with multiple Int objects."""
1292
1129
 
1293
- _T = Bool
1130
+ _T = Int
1294
1131
 
1295
1132
 
1296
- _typemap['Bool'] = Bool
1133
+ _typemap['Int'] = Int
1297
1134
 
1298
- class BoolArray(TypeBase):
1135
+ class Qubit(TypeBase):
1299
1136
  __slots__ = []
1300
1137
 
1301
1138
  def __init__(
@@ -1306,7 +1143,7 @@ class BoolArray(TypeBase):
1306
1143
 
1307
1144
  def __eq__(self, other):
1308
1145
  """Equality operator. Ignores annotations!"""
1309
- if not isinstance(other, BoolArray):
1146
+ if not isinstance(other, Qubit):
1310
1147
  return False
1311
1148
  if self.size != other.size:
1312
1149
  return False
@@ -1319,7 +1156,7 @@ class BoolArray(TypeBase):
1319
1156
  strings of the annotations that are to be printed. links specifies the
1320
1157
  maximum link recursion depth."""
1321
1158
  s = [' '*indent]
1322
- s.append('BoolArray(')
1159
+ s.append('Qubit(')
1323
1160
  if annotations is None:
1324
1161
  annotations = []
1325
1162
  for key in annotations:
@@ -1359,7 +1196,7 @@ class BoolArray(TypeBase):
1359
1196
 
1360
1197
  def copy(self):
1361
1198
  """Returns a shallow copy of this node."""
1362
- return BoolArray(
1199
+ return Qubit(
1363
1200
  size=self._attr_size
1364
1201
  )
1365
1202
 
@@ -1369,7 +1206,7 @@ class BoolArray(TypeBase):
1369
1206
  original tree. If you're not cloning a subtree in a context where this
1370
1207
  is the desired behavior, you may want to use the copy.deepcopy() from
1371
1208
  the stdlib instead, which should copy links correctly."""
1372
- return BoolArray(
1209
+ return Qubit(
1373
1210
  size=_cloned(self._attr_size)
1374
1211
  )
1375
1212
 
@@ -1386,8 +1223,8 @@ class BoolArray(TypeBase):
1386
1223
  typ = cbor.get('@t', None)
1387
1224
  if typ is None:
1388
1225
  raise ValueError('type (@t) field is missing from node serialization')
1389
- if typ != 'BoolArray':
1390
- raise ValueError('found node serialization for ' + typ + ', but expected BoolArray')
1226
+ if typ != 'Qubit':
1227
+ raise ValueError('found node serialization for ' + typ + ', but expected Qubit')
1391
1228
 
1392
1229
  # Deserialize the size field.
1393
1230
  field = cbor.get('size', None)
@@ -1398,8 +1235,8 @@ class BoolArray(TypeBase):
1398
1235
  else:
1399
1236
  f_size = cqasm.v3x.primitives.deserialize(cqasm.v3x.primitives.Int, field)
1400
1237
 
1401
- # Construct the BoolArray node.
1402
- node = BoolArray(f_size)
1238
+ # Construct the Qubit node.
1239
+ node = Qubit(f_size)
1403
1240
 
1404
1241
  # Deserialize annotations.
1405
1242
  for key, val in cbor.items():
@@ -1423,7 +1260,7 @@ class BoolArray(TypeBase):
1423
1260
  CBOR serialization. The tree that the node belongs to must be
1424
1261
  well-formed. id_map must match Python id() calls for all nodes to unique
1425
1262
  integers, to use for the sequence number representation of links."""
1426
- cbor = {'@i': id_map[id(self)], '@t': 'BoolArray'}
1263
+ cbor = {'@i': id_map[id(self)], '@t': 'Qubit'}
1427
1264
 
1428
1265
  # Serialize the size field.
1429
1266
  if hasattr(self._attr_size, 'serialize_cbor'):
@@ -1438,17 +1275,15 @@ class BoolArray(TypeBase):
1438
1275
  return cbor
1439
1276
 
1440
1277
 
1441
- class MultiBoolArray(_Multiple):
1442
- """Wrapper for an edge with multiple BoolArray objects."""
1443
-
1444
- _T = BoolArray
1278
+ class MultiQubit(_Multiple):
1279
+ """Wrapper for an edge with multiple Qubit objects."""
1445
1280
 
1281
+ _T = Qubit
1446
1282
 
1447
- _typemap['BoolArray'] = BoolArray
1448
1283
 
1449
- class Complex(TypeBase):
1450
- """Type of a complex number (2x IEEE double)."""
1284
+ _typemap['Qubit'] = Qubit
1451
1285
 
1286
+ class QubitArray(TypeBase):
1452
1287
  __slots__ = []
1453
1288
 
1454
1289
  def __init__(
@@ -1459,7 +1294,7 @@ class Complex(TypeBase):
1459
1294
 
1460
1295
  def __eq__(self, other):
1461
1296
  """Equality operator. Ignores annotations!"""
1462
- if not isinstance(other, Complex):
1297
+ if not isinstance(other, QubitArray):
1463
1298
  return False
1464
1299
  if self.size != other.size:
1465
1300
  return False
@@ -1472,7 +1307,7 @@ class Complex(TypeBase):
1472
1307
  strings of the annotations that are to be printed. links specifies the
1473
1308
  maximum link recursion depth."""
1474
1309
  s = [' '*indent]
1475
- s.append('Complex(')
1310
+ s.append('QubitArray(')
1476
1311
  if annotations is None:
1477
1312
  annotations = []
1478
1313
  for key in annotations:
@@ -1512,7 +1347,7 @@ class Complex(TypeBase):
1512
1347
 
1513
1348
  def copy(self):
1514
1349
  """Returns a shallow copy of this node."""
1515
- return Complex(
1350
+ return QubitArray(
1516
1351
  size=self._attr_size
1517
1352
  )
1518
1353
 
@@ -1522,7 +1357,7 @@ class Complex(TypeBase):
1522
1357
  original tree. If you're not cloning a subtree in a context where this
1523
1358
  is the desired behavior, you may want to use the copy.deepcopy() from
1524
1359
  the stdlib instead, which should copy links correctly."""
1525
- return Complex(
1360
+ return QubitArray(
1526
1361
  size=_cloned(self._attr_size)
1527
1362
  )
1528
1363
 
@@ -1539,8 +1374,8 @@ class Complex(TypeBase):
1539
1374
  typ = cbor.get('@t', None)
1540
1375
  if typ is None:
1541
1376
  raise ValueError('type (@t) field is missing from node serialization')
1542
- if typ != 'Complex':
1543
- raise ValueError('found node serialization for ' + typ + ', but expected Complex')
1377
+ if typ != 'QubitArray':
1378
+ raise ValueError('found node serialization for ' + typ + ', but expected QubitArray')
1544
1379
 
1545
1380
  # Deserialize the size field.
1546
1381
  field = cbor.get('size', None)
@@ -1551,8 +1386,8 @@ class Complex(TypeBase):
1551
1386
  else:
1552
1387
  f_size = cqasm.v3x.primitives.deserialize(cqasm.v3x.primitives.Int, field)
1553
1388
 
1554
- # Construct the Complex node.
1555
- node = Complex(f_size)
1389
+ # Construct the QubitArray node.
1390
+ node = QubitArray(f_size)
1556
1391
 
1557
1392
  # Deserialize annotations.
1558
1393
  for key, val in cbor.items():
@@ -1576,7 +1411,7 @@ class Complex(TypeBase):
1576
1411
  CBOR serialization. The tree that the node belongs to must be
1577
1412
  well-formed. id_map must match Python id() calls for all nodes to unique
1578
1413
  integers, to use for the sequence number representation of links."""
1579
- cbor = {'@i': id_map[id(self)], '@t': 'Complex'}
1414
+ cbor = {'@i': id_map[id(self)], '@t': 'QubitArray'}
1580
1415
 
1581
1416
  # Serialize the size field.
1582
1417
  if hasattr(self._attr_size, 'serialize_cbor'):
@@ -1591,921 +1426,11 @@ class Complex(TypeBase):
1591
1426
  return cbor
1592
1427
 
1593
1428
 
1594
- class MultiComplex(_Multiple):
1595
- """Wrapper for an edge with multiple Complex objects."""
1596
-
1597
- _T = Complex
1598
-
1599
-
1600
- _typemap['Complex'] = Complex
1601
-
1602
- class Int(TypeBase):
1603
- """Type of an integer (signed 64-bit)."""
1604
-
1605
- __slots__ = []
1606
-
1607
- def __init__(
1608
- self,
1609
- size=None,
1610
- ):
1611
- super().__init__(size=size)
1612
-
1613
- def __eq__(self, other):
1614
- """Equality operator. Ignores annotations!"""
1615
- if not isinstance(other, Int):
1616
- return False
1617
- if self.size != other.size:
1618
- return False
1619
- return True
1429
+ class MultiQubitArray(_Multiple):
1430
+ """Wrapper for an edge with multiple QubitArray objects."""
1620
1431
 
1621
- def dump(self, indent=0, annotations=None, links=1):
1622
- """Returns a debug representation of this tree as a multiline string.
1623
- indent is the number of double spaces prefixed before every line.
1624
- annotations, if specified, must be a set-like object containing the key
1625
- strings of the annotations that are to be printed. links specifies the
1626
- maximum link recursion depth."""
1627
- s = [' '*indent]
1628
- s.append('Int(')
1629
- if annotations is None:
1630
- annotations = []
1631
- for key in annotations:
1632
- if key in self:
1633
- s.append(' # {}: {}'.format(key, self[key]))
1634
- s.append('\n')
1635
- indent += 1
1636
- s.append(' '*indent)
1637
- s.append('size: ')
1638
- s.append(str(self.size) + '\n')
1639
- indent -= 1
1640
- s.append(' '*indent)
1641
- s.append(')')
1642
- return ''.join(s)
1432
+ _T = QubitArray
1643
1433
 
1644
- __str__ = dump
1645
- __repr__ = dump
1646
1434
 
1647
- def find_reachable(self, id_map=None):
1648
- """Returns a dictionary mapping Python id() values to stable sequence
1649
- numbers for all nodes in the tree rooted at this node. If id_map is
1650
- specified, found nodes are appended to it."""
1651
- if id_map is None:
1652
- id_map = {}
1653
- if id(self) in id_map:
1654
- raise NotWellFormed('node {!r} with id {} occurs more than once'.format(self, id(self)))
1655
- id_map[id(self)] = len(id_map)
1656
- return id_map
1657
-
1658
- def check_complete(self, id_map=None):
1659
- """Raises NotWellFormed if the tree rooted at this node is not
1660
- well-formed. If id_map is specified, this tree is only a subtree in the
1661
- context of a larger tree, and id_map must be a dict mapping from Python
1662
- id() codes to tree indices for all reachable nodes."""
1663
- if id_map is None:
1664
- id_map = self.find_reachable()
1665
-
1666
- def copy(self):
1667
- """Returns a shallow copy of this node."""
1668
- return Int(
1669
- size=self._attr_size
1670
- )
1671
-
1672
- def clone(self):
1673
- """Returns a deep copy of this node. This mimics the C++ interface,
1674
- deficiencies with links included; that is, links always point to the
1675
- original tree. If you're not cloning a subtree in a context where this
1676
- is the desired behavior, you may want to use the copy.deepcopy() from
1677
- the stdlib instead, which should copy links correctly."""
1678
- return Int(
1679
- size=_cloned(self._attr_size)
1680
- )
1681
-
1682
- @staticmethod
1683
- def _deserialize(cbor, seq_to_ob, links):
1684
- """Attempts to deserialize the given cbor object (in Python primitive
1685
- representation) into a node of this type. All (sub)nodes are added to
1686
- the seq_to_ob dict, indexed by their cbor sequence number. All links are
1687
- registered in the links list by means of a two-tuple of the setter
1688
- function for the link field and the sequence number of the target node.
1689
- """
1690
- if not isinstance(cbor, dict):
1691
- raise TypeError('node description object must be a dict')
1692
- typ = cbor.get('@t', None)
1693
- if typ is None:
1694
- raise ValueError('type (@t) field is missing from node serialization')
1695
- if typ != 'Int':
1696
- raise ValueError('found node serialization for ' + typ + ', but expected Int')
1697
-
1698
- # Deserialize the size field.
1699
- field = cbor.get('size', None)
1700
- if not isinstance(field, dict):
1701
- raise ValueError('missing or invalid serialization of field size')
1702
- if hasattr(cqasm.v3x.primitives.Int, 'deserialize_cbor'):
1703
- f_size = cqasm.v3x.primitives.Int.deserialize_cbor(field)
1704
- else:
1705
- f_size = cqasm.v3x.primitives.deserialize(cqasm.v3x.primitives.Int, field)
1706
-
1707
- # Construct the Int node.
1708
- node = Int(f_size)
1709
-
1710
- # Deserialize annotations.
1711
- for key, val in cbor.items():
1712
- if not (key.startswith('{') and key.endswith('}')):
1713
- continue
1714
- key = key[1:-1]
1715
- node[key] = cqasm.v3x.primitives.deserialize(key, val)
1716
-
1717
- # Register node in sequence number lookup.
1718
- seq = cbor.get('@i', None)
1719
- if not isinstance(seq, int):
1720
- raise ValueError('sequence number field (@i) is not an integer or missing from node serialization')
1721
- if seq in seq_to_ob:
1722
- raise ValueError('duplicate sequence number %d' % seq)
1723
- seq_to_ob[seq] = node
1724
-
1725
- return node
1726
-
1727
- def _serialize(self, id_map):
1728
- """Serializes this node to the Python primitive representation of its
1729
- CBOR serialization. The tree that the node belongs to must be
1730
- well-formed. id_map must match Python id() calls for all nodes to unique
1731
- integers, to use for the sequence number representation of links."""
1732
- cbor = {'@i': id_map[id(self)], '@t': 'Int'}
1733
-
1734
- # Serialize the size field.
1735
- if hasattr(self._attr_size, 'serialize_cbor'):
1736
- cbor['size'] = self._attr_size.serialize_cbor()
1737
- else:
1738
- cbor['size'] = cqasm.v3x.primitives.serialize(cqasm.v3x.primitives.Int, self._attr_size)
1739
-
1740
- # Serialize annotations.
1741
- for key, val in self._annot.items():
1742
- cbor['{%s}' % key] = _py_to_cbor(cqasm.v3x.primitives.serialize(key, val))
1743
-
1744
- return cbor
1745
-
1746
-
1747
- class MultiInt(_Multiple):
1748
- """Wrapper for an edge with multiple Int objects."""
1749
-
1750
- _T = Int
1751
-
1752
-
1753
- _typemap['Int'] = Int
1754
-
1755
- class IntArray(TypeBase):
1756
- __slots__ = []
1757
-
1758
- def __init__(
1759
- self,
1760
- size=None,
1761
- ):
1762
- super().__init__(size=size)
1763
-
1764
- def __eq__(self, other):
1765
- """Equality operator. Ignores annotations!"""
1766
- if not isinstance(other, IntArray):
1767
- return False
1768
- if self.size != other.size:
1769
- return False
1770
- return True
1771
-
1772
- def dump(self, indent=0, annotations=None, links=1):
1773
- """Returns a debug representation of this tree as a multiline string.
1774
- indent is the number of double spaces prefixed before every line.
1775
- annotations, if specified, must be a set-like object containing the key
1776
- strings of the annotations that are to be printed. links specifies the
1777
- maximum link recursion depth."""
1778
- s = [' '*indent]
1779
- s.append('IntArray(')
1780
- if annotations is None:
1781
- annotations = []
1782
- for key in annotations:
1783
- if key in self:
1784
- s.append(' # {}: {}'.format(key, self[key]))
1785
- s.append('\n')
1786
- indent += 1
1787
- s.append(' '*indent)
1788
- s.append('size: ')
1789
- s.append(str(self.size) + '\n')
1790
- indent -= 1
1791
- s.append(' '*indent)
1792
- s.append(')')
1793
- return ''.join(s)
1794
-
1795
- __str__ = dump
1796
- __repr__ = dump
1797
-
1798
- def find_reachable(self, id_map=None):
1799
- """Returns a dictionary mapping Python id() values to stable sequence
1800
- numbers for all nodes in the tree rooted at this node. If id_map is
1801
- specified, found nodes are appended to it."""
1802
- if id_map is None:
1803
- id_map = {}
1804
- if id(self) in id_map:
1805
- raise NotWellFormed('node {!r} with id {} occurs more than once'.format(self, id(self)))
1806
- id_map[id(self)] = len(id_map)
1807
- return id_map
1808
-
1809
- def check_complete(self, id_map=None):
1810
- """Raises NotWellFormed if the tree rooted at this node is not
1811
- well-formed. If id_map is specified, this tree is only a subtree in the
1812
- context of a larger tree, and id_map must be a dict mapping from Python
1813
- id() codes to tree indices for all reachable nodes."""
1814
- if id_map is None:
1815
- id_map = self.find_reachable()
1816
-
1817
- def copy(self):
1818
- """Returns a shallow copy of this node."""
1819
- return IntArray(
1820
- size=self._attr_size
1821
- )
1822
-
1823
- def clone(self):
1824
- """Returns a deep copy of this node. This mimics the C++ interface,
1825
- deficiencies with links included; that is, links always point to the
1826
- original tree. If you're not cloning a subtree in a context where this
1827
- is the desired behavior, you may want to use the copy.deepcopy() from
1828
- the stdlib instead, which should copy links correctly."""
1829
- return IntArray(
1830
- size=_cloned(self._attr_size)
1831
- )
1832
-
1833
- @staticmethod
1834
- def _deserialize(cbor, seq_to_ob, links):
1835
- """Attempts to deserialize the given cbor object (in Python primitive
1836
- representation) into a node of this type. All (sub)nodes are added to
1837
- the seq_to_ob dict, indexed by their cbor sequence number. All links are
1838
- registered in the links list by means of a two-tuple of the setter
1839
- function for the link field and the sequence number of the target node.
1840
- """
1841
- if not isinstance(cbor, dict):
1842
- raise TypeError('node description object must be a dict')
1843
- typ = cbor.get('@t', None)
1844
- if typ is None:
1845
- raise ValueError('type (@t) field is missing from node serialization')
1846
- if typ != 'IntArray':
1847
- raise ValueError('found node serialization for ' + typ + ', but expected IntArray')
1848
-
1849
- # Deserialize the size field.
1850
- field = cbor.get('size', None)
1851
- if not isinstance(field, dict):
1852
- raise ValueError('missing or invalid serialization of field size')
1853
- if hasattr(cqasm.v3x.primitives.Int, 'deserialize_cbor'):
1854
- f_size = cqasm.v3x.primitives.Int.deserialize_cbor(field)
1855
- else:
1856
- f_size = cqasm.v3x.primitives.deserialize(cqasm.v3x.primitives.Int, field)
1857
-
1858
- # Construct the IntArray node.
1859
- node = IntArray(f_size)
1860
-
1861
- # Deserialize annotations.
1862
- for key, val in cbor.items():
1863
- if not (key.startswith('{') and key.endswith('}')):
1864
- continue
1865
- key = key[1:-1]
1866
- node[key] = cqasm.v3x.primitives.deserialize(key, val)
1867
-
1868
- # Register node in sequence number lookup.
1869
- seq = cbor.get('@i', None)
1870
- if not isinstance(seq, int):
1871
- raise ValueError('sequence number field (@i) is not an integer or missing from node serialization')
1872
- if seq in seq_to_ob:
1873
- raise ValueError('duplicate sequence number %d' % seq)
1874
- seq_to_ob[seq] = node
1875
-
1876
- return node
1877
-
1878
- def _serialize(self, id_map):
1879
- """Serializes this node to the Python primitive representation of its
1880
- CBOR serialization. The tree that the node belongs to must be
1881
- well-formed. id_map must match Python id() calls for all nodes to unique
1882
- integers, to use for the sequence number representation of links."""
1883
- cbor = {'@i': id_map[id(self)], '@t': 'IntArray'}
1884
-
1885
- # Serialize the size field.
1886
- if hasattr(self._attr_size, 'serialize_cbor'):
1887
- cbor['size'] = self._attr_size.serialize_cbor()
1888
- else:
1889
- cbor['size'] = cqasm.v3x.primitives.serialize(cqasm.v3x.primitives.Int, self._attr_size)
1890
-
1891
- # Serialize annotations.
1892
- for key, val in self._annot.items():
1893
- cbor['{%s}' % key] = _py_to_cbor(cqasm.v3x.primitives.serialize(key, val))
1894
-
1895
- return cbor
1896
-
1897
-
1898
- class MultiIntArray(_Multiple):
1899
- """Wrapper for an edge with multiple IntArray objects."""
1900
-
1901
- _T = IntArray
1902
-
1903
-
1904
- _typemap['IntArray'] = IntArray
1905
-
1906
- class Qubit(TypeBase):
1907
- __slots__ = []
1908
-
1909
- def __init__(
1910
- self,
1911
- size=None,
1912
- ):
1913
- super().__init__(size=size)
1914
-
1915
- def __eq__(self, other):
1916
- """Equality operator. Ignores annotations!"""
1917
- if not isinstance(other, Qubit):
1918
- return False
1919
- if self.size != other.size:
1920
- return False
1921
- return True
1922
-
1923
- def dump(self, indent=0, annotations=None, links=1):
1924
- """Returns a debug representation of this tree as a multiline string.
1925
- indent is the number of double spaces prefixed before every line.
1926
- annotations, if specified, must be a set-like object containing the key
1927
- strings of the annotations that are to be printed. links specifies the
1928
- maximum link recursion depth."""
1929
- s = [' '*indent]
1930
- s.append('Qubit(')
1931
- if annotations is None:
1932
- annotations = []
1933
- for key in annotations:
1934
- if key in self:
1935
- s.append(' # {}: {}'.format(key, self[key]))
1936
- s.append('\n')
1937
- indent += 1
1938
- s.append(' '*indent)
1939
- s.append('size: ')
1940
- s.append(str(self.size) + '\n')
1941
- indent -= 1
1942
- s.append(' '*indent)
1943
- s.append(')')
1944
- return ''.join(s)
1945
-
1946
- __str__ = dump
1947
- __repr__ = dump
1948
-
1949
- def find_reachable(self, id_map=None):
1950
- """Returns a dictionary mapping Python id() values to stable sequence
1951
- numbers for all nodes in the tree rooted at this node. If id_map is
1952
- specified, found nodes are appended to it."""
1953
- if id_map is None:
1954
- id_map = {}
1955
- if id(self) in id_map:
1956
- raise NotWellFormed('node {!r} with id {} occurs more than once'.format(self, id(self)))
1957
- id_map[id(self)] = len(id_map)
1958
- return id_map
1959
-
1960
- def check_complete(self, id_map=None):
1961
- """Raises NotWellFormed if the tree rooted at this node is not
1962
- well-formed. If id_map is specified, this tree is only a subtree in the
1963
- context of a larger tree, and id_map must be a dict mapping from Python
1964
- id() codes to tree indices for all reachable nodes."""
1965
- if id_map is None:
1966
- id_map = self.find_reachable()
1967
-
1968
- def copy(self):
1969
- """Returns a shallow copy of this node."""
1970
- return Qubit(
1971
- size=self._attr_size
1972
- )
1973
-
1974
- def clone(self):
1975
- """Returns a deep copy of this node. This mimics the C++ interface,
1976
- deficiencies with links included; that is, links always point to the
1977
- original tree. If you're not cloning a subtree in a context where this
1978
- is the desired behavior, you may want to use the copy.deepcopy() from
1979
- the stdlib instead, which should copy links correctly."""
1980
- return Qubit(
1981
- size=_cloned(self._attr_size)
1982
- )
1983
-
1984
- @staticmethod
1985
- def _deserialize(cbor, seq_to_ob, links):
1986
- """Attempts to deserialize the given cbor object (in Python primitive
1987
- representation) into a node of this type. All (sub)nodes are added to
1988
- the seq_to_ob dict, indexed by their cbor sequence number. All links are
1989
- registered in the links list by means of a two-tuple of the setter
1990
- function for the link field and the sequence number of the target node.
1991
- """
1992
- if not isinstance(cbor, dict):
1993
- raise TypeError('node description object must be a dict')
1994
- typ = cbor.get('@t', None)
1995
- if typ is None:
1996
- raise ValueError('type (@t) field is missing from node serialization')
1997
- if typ != 'Qubit':
1998
- raise ValueError('found node serialization for ' + typ + ', but expected Qubit')
1999
-
2000
- # Deserialize the size field.
2001
- field = cbor.get('size', None)
2002
- if not isinstance(field, dict):
2003
- raise ValueError('missing or invalid serialization of field size')
2004
- if hasattr(cqasm.v3x.primitives.Int, 'deserialize_cbor'):
2005
- f_size = cqasm.v3x.primitives.Int.deserialize_cbor(field)
2006
- else:
2007
- f_size = cqasm.v3x.primitives.deserialize(cqasm.v3x.primitives.Int, field)
2008
-
2009
- # Construct the Qubit node.
2010
- node = Qubit(f_size)
2011
-
2012
- # Deserialize annotations.
2013
- for key, val in cbor.items():
2014
- if not (key.startswith('{') and key.endswith('}')):
2015
- continue
2016
- key = key[1:-1]
2017
- node[key] = cqasm.v3x.primitives.deserialize(key, val)
2018
-
2019
- # Register node in sequence number lookup.
2020
- seq = cbor.get('@i', None)
2021
- if not isinstance(seq, int):
2022
- raise ValueError('sequence number field (@i) is not an integer or missing from node serialization')
2023
- if seq in seq_to_ob:
2024
- raise ValueError('duplicate sequence number %d' % seq)
2025
- seq_to_ob[seq] = node
2026
-
2027
- return node
2028
-
2029
- def _serialize(self, id_map):
2030
- """Serializes this node to the Python primitive representation of its
2031
- CBOR serialization. The tree that the node belongs to must be
2032
- well-formed. id_map must match Python id() calls for all nodes to unique
2033
- integers, to use for the sequence number representation of links."""
2034
- cbor = {'@i': id_map[id(self)], '@t': 'Qubit'}
2035
-
2036
- # Serialize the size field.
2037
- if hasattr(self._attr_size, 'serialize_cbor'):
2038
- cbor['size'] = self._attr_size.serialize_cbor()
2039
- else:
2040
- cbor['size'] = cqasm.v3x.primitives.serialize(cqasm.v3x.primitives.Int, self._attr_size)
2041
-
2042
- # Serialize annotations.
2043
- for key, val in self._annot.items():
2044
- cbor['{%s}' % key] = _py_to_cbor(cqasm.v3x.primitives.serialize(key, val))
2045
-
2046
- return cbor
2047
-
2048
-
2049
- class MultiQubit(_Multiple):
2050
- """Wrapper for an edge with multiple Qubit objects."""
2051
-
2052
- _T = Qubit
2053
-
2054
-
2055
- _typemap['Qubit'] = Qubit
2056
-
2057
- class QubitArray(TypeBase):
2058
- __slots__ = []
2059
-
2060
- def __init__(
2061
- self,
2062
- size=None,
2063
- ):
2064
- super().__init__(size=size)
2065
-
2066
- def __eq__(self, other):
2067
- """Equality operator. Ignores annotations!"""
2068
- if not isinstance(other, QubitArray):
2069
- return False
2070
- if self.size != other.size:
2071
- return False
2072
- return True
2073
-
2074
- def dump(self, indent=0, annotations=None, links=1):
2075
- """Returns a debug representation of this tree as a multiline string.
2076
- indent is the number of double spaces prefixed before every line.
2077
- annotations, if specified, must be a set-like object containing the key
2078
- strings of the annotations that are to be printed. links specifies the
2079
- maximum link recursion depth."""
2080
- s = [' '*indent]
2081
- s.append('QubitArray(')
2082
- if annotations is None:
2083
- annotations = []
2084
- for key in annotations:
2085
- if key in self:
2086
- s.append(' # {}: {}'.format(key, self[key]))
2087
- s.append('\n')
2088
- indent += 1
2089
- s.append(' '*indent)
2090
- s.append('size: ')
2091
- s.append(str(self.size) + '\n')
2092
- indent -= 1
2093
- s.append(' '*indent)
2094
- s.append(')')
2095
- return ''.join(s)
2096
-
2097
- __str__ = dump
2098
- __repr__ = dump
2099
-
2100
- def find_reachable(self, id_map=None):
2101
- """Returns a dictionary mapping Python id() values to stable sequence
2102
- numbers for all nodes in the tree rooted at this node. If id_map is
2103
- specified, found nodes are appended to it."""
2104
- if id_map is None:
2105
- id_map = {}
2106
- if id(self) in id_map:
2107
- raise NotWellFormed('node {!r} with id {} occurs more than once'.format(self, id(self)))
2108
- id_map[id(self)] = len(id_map)
2109
- return id_map
2110
-
2111
- def check_complete(self, id_map=None):
2112
- """Raises NotWellFormed if the tree rooted at this node is not
2113
- well-formed. If id_map is specified, this tree is only a subtree in the
2114
- context of a larger tree, and id_map must be a dict mapping from Python
2115
- id() codes to tree indices for all reachable nodes."""
2116
- if id_map is None:
2117
- id_map = self.find_reachable()
2118
-
2119
- def copy(self):
2120
- """Returns a shallow copy of this node."""
2121
- return QubitArray(
2122
- size=self._attr_size
2123
- )
2124
-
2125
- def clone(self):
2126
- """Returns a deep copy of this node. This mimics the C++ interface,
2127
- deficiencies with links included; that is, links always point to the
2128
- original tree. If you're not cloning a subtree in a context where this
2129
- is the desired behavior, you may want to use the copy.deepcopy() from
2130
- the stdlib instead, which should copy links correctly."""
2131
- return QubitArray(
2132
- size=_cloned(self._attr_size)
2133
- )
2134
-
2135
- @staticmethod
2136
- def _deserialize(cbor, seq_to_ob, links):
2137
- """Attempts to deserialize the given cbor object (in Python primitive
2138
- representation) into a node of this type. All (sub)nodes are added to
2139
- the seq_to_ob dict, indexed by their cbor sequence number. All links are
2140
- registered in the links list by means of a two-tuple of the setter
2141
- function for the link field and the sequence number of the target node.
2142
- """
2143
- if not isinstance(cbor, dict):
2144
- raise TypeError('node description object must be a dict')
2145
- typ = cbor.get('@t', None)
2146
- if typ is None:
2147
- raise ValueError('type (@t) field is missing from node serialization')
2148
- if typ != 'QubitArray':
2149
- raise ValueError('found node serialization for ' + typ + ', but expected QubitArray')
2150
-
2151
- # Deserialize the size field.
2152
- field = cbor.get('size', None)
2153
- if not isinstance(field, dict):
2154
- raise ValueError('missing or invalid serialization of field size')
2155
- if hasattr(cqasm.v3x.primitives.Int, 'deserialize_cbor'):
2156
- f_size = cqasm.v3x.primitives.Int.deserialize_cbor(field)
2157
- else:
2158
- f_size = cqasm.v3x.primitives.deserialize(cqasm.v3x.primitives.Int, field)
2159
-
2160
- # Construct the QubitArray node.
2161
- node = QubitArray(f_size)
2162
-
2163
- # Deserialize annotations.
2164
- for key, val in cbor.items():
2165
- if not (key.startswith('{') and key.endswith('}')):
2166
- continue
2167
- key = key[1:-1]
2168
- node[key] = cqasm.v3x.primitives.deserialize(key, val)
2169
-
2170
- # Register node in sequence number lookup.
2171
- seq = cbor.get('@i', None)
2172
- if not isinstance(seq, int):
2173
- raise ValueError('sequence number field (@i) is not an integer or missing from node serialization')
2174
- if seq in seq_to_ob:
2175
- raise ValueError('duplicate sequence number %d' % seq)
2176
- seq_to_ob[seq] = node
2177
-
2178
- return node
2179
-
2180
- def _serialize(self, id_map):
2181
- """Serializes this node to the Python primitive representation of its
2182
- CBOR serialization. The tree that the node belongs to must be
2183
- well-formed. id_map must match Python id() calls for all nodes to unique
2184
- integers, to use for the sequence number representation of links."""
2185
- cbor = {'@i': id_map[id(self)], '@t': 'QubitArray'}
2186
-
2187
- # Serialize the size field.
2188
- if hasattr(self._attr_size, 'serialize_cbor'):
2189
- cbor['size'] = self._attr_size.serialize_cbor()
2190
- else:
2191
- cbor['size'] = cqasm.v3x.primitives.serialize(cqasm.v3x.primitives.Int, self._attr_size)
2192
-
2193
- # Serialize annotations.
2194
- for key, val in self._annot.items():
2195
- cbor['{%s}' % key] = _py_to_cbor(cqasm.v3x.primitives.serialize(key, val))
2196
-
2197
- return cbor
2198
-
2199
-
2200
- class MultiQubitArray(_Multiple):
2201
- """Wrapper for an edge with multiple QubitArray objects."""
2202
-
2203
- _T = QubitArray
2204
-
2205
-
2206
- _typemap['QubitArray'] = QubitArray
2207
-
2208
- class Real(TypeBase):
2209
- """Type of a real number (IEEE double)."""
2210
-
2211
- __slots__ = []
2212
-
2213
- def __init__(
2214
- self,
2215
- size=None,
2216
- ):
2217
- super().__init__(size=size)
2218
-
2219
- def __eq__(self, other):
2220
- """Equality operator. Ignores annotations!"""
2221
- if not isinstance(other, Real):
2222
- return False
2223
- if self.size != other.size:
2224
- return False
2225
- return True
2226
-
2227
- def dump(self, indent=0, annotations=None, links=1):
2228
- """Returns a debug representation of this tree as a multiline string.
2229
- indent is the number of double spaces prefixed before every line.
2230
- annotations, if specified, must be a set-like object containing the key
2231
- strings of the annotations that are to be printed. links specifies the
2232
- maximum link recursion depth."""
2233
- s = [' '*indent]
2234
- s.append('Real(')
2235
- if annotations is None:
2236
- annotations = []
2237
- for key in annotations:
2238
- if key in self:
2239
- s.append(' # {}: {}'.format(key, self[key]))
2240
- s.append('\n')
2241
- indent += 1
2242
- s.append(' '*indent)
2243
- s.append('size: ')
2244
- s.append(str(self.size) + '\n')
2245
- indent -= 1
2246
- s.append(' '*indent)
2247
- s.append(')')
2248
- return ''.join(s)
2249
-
2250
- __str__ = dump
2251
- __repr__ = dump
2252
-
2253
- def find_reachable(self, id_map=None):
2254
- """Returns a dictionary mapping Python id() values to stable sequence
2255
- numbers for all nodes in the tree rooted at this node. If id_map is
2256
- specified, found nodes are appended to it."""
2257
- if id_map is None:
2258
- id_map = {}
2259
- if id(self) in id_map:
2260
- raise NotWellFormed('node {!r} with id {} occurs more than once'.format(self, id(self)))
2261
- id_map[id(self)] = len(id_map)
2262
- return id_map
2263
-
2264
- def check_complete(self, id_map=None):
2265
- """Raises NotWellFormed if the tree rooted at this node is not
2266
- well-formed. If id_map is specified, this tree is only a subtree in the
2267
- context of a larger tree, and id_map must be a dict mapping from Python
2268
- id() codes to tree indices for all reachable nodes."""
2269
- if id_map is None:
2270
- id_map = self.find_reachable()
2271
-
2272
- def copy(self):
2273
- """Returns a shallow copy of this node."""
2274
- return Real(
2275
- size=self._attr_size
2276
- )
2277
-
2278
- def clone(self):
2279
- """Returns a deep copy of this node. This mimics the C++ interface,
2280
- deficiencies with links included; that is, links always point to the
2281
- original tree. If you're not cloning a subtree in a context where this
2282
- is the desired behavior, you may want to use the copy.deepcopy() from
2283
- the stdlib instead, which should copy links correctly."""
2284
- return Real(
2285
- size=_cloned(self._attr_size)
2286
- )
2287
-
2288
- @staticmethod
2289
- def _deserialize(cbor, seq_to_ob, links):
2290
- """Attempts to deserialize the given cbor object (in Python primitive
2291
- representation) into a node of this type. All (sub)nodes are added to
2292
- the seq_to_ob dict, indexed by their cbor sequence number. All links are
2293
- registered in the links list by means of a two-tuple of the setter
2294
- function for the link field and the sequence number of the target node.
2295
- """
2296
- if not isinstance(cbor, dict):
2297
- raise TypeError('node description object must be a dict')
2298
- typ = cbor.get('@t', None)
2299
- if typ is None:
2300
- raise ValueError('type (@t) field is missing from node serialization')
2301
- if typ != 'Real':
2302
- raise ValueError('found node serialization for ' + typ + ', but expected Real')
2303
-
2304
- # Deserialize the size field.
2305
- field = cbor.get('size', None)
2306
- if not isinstance(field, dict):
2307
- raise ValueError('missing or invalid serialization of field size')
2308
- if hasattr(cqasm.v3x.primitives.Int, 'deserialize_cbor'):
2309
- f_size = cqasm.v3x.primitives.Int.deserialize_cbor(field)
2310
- else:
2311
- f_size = cqasm.v3x.primitives.deserialize(cqasm.v3x.primitives.Int, field)
2312
-
2313
- # Construct the Real node.
2314
- node = Real(f_size)
2315
-
2316
- # Deserialize annotations.
2317
- for key, val in cbor.items():
2318
- if not (key.startswith('{') and key.endswith('}')):
2319
- continue
2320
- key = key[1:-1]
2321
- node[key] = cqasm.v3x.primitives.deserialize(key, val)
2322
-
2323
- # Register node in sequence number lookup.
2324
- seq = cbor.get('@i', None)
2325
- if not isinstance(seq, int):
2326
- raise ValueError('sequence number field (@i) is not an integer or missing from node serialization')
2327
- if seq in seq_to_ob:
2328
- raise ValueError('duplicate sequence number %d' % seq)
2329
- seq_to_ob[seq] = node
2330
-
2331
- return node
2332
-
2333
- def _serialize(self, id_map):
2334
- """Serializes this node to the Python primitive representation of its
2335
- CBOR serialization. The tree that the node belongs to must be
2336
- well-formed. id_map must match Python id() calls for all nodes to unique
2337
- integers, to use for the sequence number representation of links."""
2338
- cbor = {'@i': id_map[id(self)], '@t': 'Real'}
2339
-
2340
- # Serialize the size field.
2341
- if hasattr(self._attr_size, 'serialize_cbor'):
2342
- cbor['size'] = self._attr_size.serialize_cbor()
2343
- else:
2344
- cbor['size'] = cqasm.v3x.primitives.serialize(cqasm.v3x.primitives.Int, self._attr_size)
2345
-
2346
- # Serialize annotations.
2347
- for key, val in self._annot.items():
2348
- cbor['{%s}' % key] = _py_to_cbor(cqasm.v3x.primitives.serialize(key, val))
2349
-
2350
- return cbor
2351
-
2352
-
2353
- class MultiReal(_Multiple):
2354
- """Wrapper for an edge with multiple Real objects."""
2355
-
2356
- _T = Real
2357
-
2358
-
2359
- _typemap['Real'] = Real
2360
-
2361
- class RealArray(TypeBase):
2362
- __slots__ = []
2363
-
2364
- def __init__(
2365
- self,
2366
- size=None,
2367
- ):
2368
- super().__init__(size=size)
2369
-
2370
- def __eq__(self, other):
2371
- """Equality operator. Ignores annotations!"""
2372
- if not isinstance(other, RealArray):
2373
- return False
2374
- if self.size != other.size:
2375
- return False
2376
- return True
2377
-
2378
- def dump(self, indent=0, annotations=None, links=1):
2379
- """Returns a debug representation of this tree as a multiline string.
2380
- indent is the number of double spaces prefixed before every line.
2381
- annotations, if specified, must be a set-like object containing the key
2382
- strings of the annotations that are to be printed. links specifies the
2383
- maximum link recursion depth."""
2384
- s = [' '*indent]
2385
- s.append('RealArray(')
2386
- if annotations is None:
2387
- annotations = []
2388
- for key in annotations:
2389
- if key in self:
2390
- s.append(' # {}: {}'.format(key, self[key]))
2391
- s.append('\n')
2392
- indent += 1
2393
- s.append(' '*indent)
2394
- s.append('size: ')
2395
- s.append(str(self.size) + '\n')
2396
- indent -= 1
2397
- s.append(' '*indent)
2398
- s.append(')')
2399
- return ''.join(s)
2400
-
2401
- __str__ = dump
2402
- __repr__ = dump
2403
-
2404
- def find_reachable(self, id_map=None):
2405
- """Returns a dictionary mapping Python id() values to stable sequence
2406
- numbers for all nodes in the tree rooted at this node. If id_map is
2407
- specified, found nodes are appended to it."""
2408
- if id_map is None:
2409
- id_map = {}
2410
- if id(self) in id_map:
2411
- raise NotWellFormed('node {!r} with id {} occurs more than once'.format(self, id(self)))
2412
- id_map[id(self)] = len(id_map)
2413
- return id_map
2414
-
2415
- def check_complete(self, id_map=None):
2416
- """Raises NotWellFormed if the tree rooted at this node is not
2417
- well-formed. If id_map is specified, this tree is only a subtree in the
2418
- context of a larger tree, and id_map must be a dict mapping from Python
2419
- id() codes to tree indices for all reachable nodes."""
2420
- if id_map is None:
2421
- id_map = self.find_reachable()
2422
-
2423
- def copy(self):
2424
- """Returns a shallow copy of this node."""
2425
- return RealArray(
2426
- size=self._attr_size
2427
- )
2428
-
2429
- def clone(self):
2430
- """Returns a deep copy of this node. This mimics the C++ interface,
2431
- deficiencies with links included; that is, links always point to the
2432
- original tree. If you're not cloning a subtree in a context where this
2433
- is the desired behavior, you may want to use the copy.deepcopy() from
2434
- the stdlib instead, which should copy links correctly."""
2435
- return RealArray(
2436
- size=_cloned(self._attr_size)
2437
- )
2438
-
2439
- @staticmethod
2440
- def _deserialize(cbor, seq_to_ob, links):
2441
- """Attempts to deserialize the given cbor object (in Python primitive
2442
- representation) into a node of this type. All (sub)nodes are added to
2443
- the seq_to_ob dict, indexed by their cbor sequence number. All links are
2444
- registered in the links list by means of a two-tuple of the setter
2445
- function for the link field and the sequence number of the target node.
2446
- """
2447
- if not isinstance(cbor, dict):
2448
- raise TypeError('node description object must be a dict')
2449
- typ = cbor.get('@t', None)
2450
- if typ is None:
2451
- raise ValueError('type (@t) field is missing from node serialization')
2452
- if typ != 'RealArray':
2453
- raise ValueError('found node serialization for ' + typ + ', but expected RealArray')
2454
-
2455
- # Deserialize the size field.
2456
- field = cbor.get('size', None)
2457
- if not isinstance(field, dict):
2458
- raise ValueError('missing or invalid serialization of field size')
2459
- if hasattr(cqasm.v3x.primitives.Int, 'deserialize_cbor'):
2460
- f_size = cqasm.v3x.primitives.Int.deserialize_cbor(field)
2461
- else:
2462
- f_size = cqasm.v3x.primitives.deserialize(cqasm.v3x.primitives.Int, field)
2463
-
2464
- # Construct the RealArray node.
2465
- node = RealArray(f_size)
2466
-
2467
- # Deserialize annotations.
2468
- for key, val in cbor.items():
2469
- if not (key.startswith('{') and key.endswith('}')):
2470
- continue
2471
- key = key[1:-1]
2472
- node[key] = cqasm.v3x.primitives.deserialize(key, val)
2473
-
2474
- # Register node in sequence number lookup.
2475
- seq = cbor.get('@i', None)
2476
- if not isinstance(seq, int):
2477
- raise ValueError('sequence number field (@i) is not an integer or missing from node serialization')
2478
- if seq in seq_to_ob:
2479
- raise ValueError('duplicate sequence number %d' % seq)
2480
- seq_to_ob[seq] = node
2481
-
2482
- return node
2483
-
2484
- def _serialize(self, id_map):
2485
- """Serializes this node to the Python primitive representation of its
2486
- CBOR serialization. The tree that the node belongs to must be
2487
- well-formed. id_map must match Python id() calls for all nodes to unique
2488
- integers, to use for the sequence number representation of links."""
2489
- cbor = {'@i': id_map[id(self)], '@t': 'RealArray'}
2490
-
2491
- # Serialize the size field.
2492
- if hasattr(self._attr_size, 'serialize_cbor'):
2493
- cbor['size'] = self._attr_size.serialize_cbor()
2494
- else:
2495
- cbor['size'] = cqasm.v3x.primitives.serialize(cqasm.v3x.primitives.Int, self._attr_size)
2496
-
2497
- # Serialize annotations.
2498
- for key, val in self._annot.items():
2499
- cbor['{%s}' % key] = _py_to_cbor(cqasm.v3x.primitives.serialize(key, val))
2500
-
2501
- return cbor
2502
-
2503
-
2504
- class MultiRealArray(_Multiple):
2505
- """Wrapper for an edge with multiple RealArray objects."""
2506
-
2507
- _T = RealArray
2508
-
2509
-
2510
- _typemap['RealArray'] = RealArray
1435
+ _typemap['QubitArray'] = QubitArray
2511
1436