libqasm 0.5.2__cp38-cp38-win_amd64.whl → 0.6.1__cp38-cp38-win_amd64.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/values.py CHANGED
@@ -589,9 +589,7 @@ def _cloned(obj):
589
589
  return obj
590
590
 
591
591
 
592
- class Constant(Node):
593
- """Constant value"""
594
-
592
+ class ValueBase(Node):
595
593
  __slots__ = []
596
594
 
597
595
  def __init__(self):
@@ -610,22 +608,16 @@ class Constant(Node):
610
608
  typ = cbor.get('@t', None)
611
609
  if typ is None:
612
610
  raise ValueError('type (@t) field is missing from node serialization')
613
- if typ == 'ConstAxis':
614
- return ConstAxis._deserialize(cbor, seq_to_ob, links)
615
611
  if typ == 'ConstBool':
616
612
  return ConstBool._deserialize(cbor, seq_to_ob, links)
617
613
  if typ == 'ConstInt':
618
614
  return ConstInt._deserialize(cbor, seq_to_ob, links)
619
- if typ == 'ConstReal':
620
- return ConstReal._deserialize(cbor, seq_to_ob, links)
621
- if typ == 'ConstComplex':
622
- return ConstComplex._deserialize(cbor, seq_to_ob, links)
623
- if typ == 'ConstBoolArray':
624
- return ConstBoolArray._deserialize(cbor, seq_to_ob, links)
625
- if typ == 'ConstIntArray':
626
- return ConstIntArray._deserialize(cbor, seq_to_ob, links)
627
- if typ == 'ConstRealArray':
628
- return ConstRealArray._deserialize(cbor, seq_to_ob, links)
615
+ if typ == 'ConstFloat':
616
+ return ConstFloat._deserialize(cbor, seq_to_ob, links)
617
+ if typ == 'IndexRef':
618
+ return IndexRef._deserialize(cbor, seq_to_ob, links)
619
+ if typ == 'VariableRef':
620
+ return VariableRef._deserialize(cbor, seq_to_ob, links)
629
621
  raise ValueError('unknown or unexpected type (@t) found in node serialization')
630
622
 
631
623
  def _serialize(self, id_map):
@@ -633,7 +625,7 @@ class Constant(Node):
633
625
  CBOR serialization. The tree that the node belongs to must be
634
626
  well-formed. id_map must match Python id() calls for all nodes to unique
635
627
  integers, to use for the sequence number representation of links."""
636
- cbor = {'@i': id_map[id(self)], '@t': 'Constant'}
628
+ cbor = {'@i': id_map[id(self)], '@t': 'ValueBase'}
637
629
 
638
630
  # Serialize annotations.
639
631
  for key, val in self._annot.items():
@@ -642,116 +634,21 @@ class Constant(Node):
642
634
  return cbor
643
635
 
644
636
 
645
- class MultiConstant(_Multiple):
646
- """Wrapper for an edge with multiple Constant objects."""
637
+ class MultiValueBase(_Multiple):
638
+ """Wrapper for an edge with multiple ValueBase objects."""
647
639
 
648
- _T = Constant
640
+ _T = ValueBase
649
641
 
650
642
 
651
- _typemap['Constant'] = Constant
643
+ _typemap['ValueBase'] = ValueBase
652
644
 
653
- class ConstAxis(Constant):
654
- """Represents an axis value (x, y, and z vectors)."""
645
+ class Constant(ValueBase):
646
+ """Constant value"""
655
647
 
656
- __slots__ = [
657
- '_attr_value',
658
- ]
648
+ __slots__ = []
659
649
 
660
- def __init__(
661
- self,
662
- value=None,
663
- ):
650
+ def __init__(self):
664
651
  super().__init__()
665
- self.value = value
666
-
667
- @property
668
- def value(self):
669
- return self._attr_value
670
-
671
- @value.setter
672
- def value(self, val):
673
- if val is None:
674
- del self.value
675
- return
676
- if not isinstance(val, cqasm.v3x.primitives.Axis):
677
- # Try to "typecast" if this isn't an obvious mistake.
678
- if isinstance(val, Node):
679
- raise TypeError('value must be of type cqasm.v3x.primitives.Axis')
680
- val = cqasm.v3x.primitives.Axis(val)
681
- self._attr_value = val
682
-
683
- @value.deleter
684
- def value(self):
685
- self._attr_value = cqasm.v3x.primitives.Axis()
686
-
687
- def __eq__(self, other):
688
- """Equality operator. Ignores annotations!"""
689
- if not isinstance(other, ConstAxis):
690
- return False
691
- if self.value != other.value:
692
- return False
693
- return True
694
-
695
- def dump(self, indent=0, annotations=None, links=1):
696
- """Returns a debug representation of this tree as a multiline string.
697
- indent is the number of double spaces prefixed before every line.
698
- annotations, if specified, must be a set-like object containing the key
699
- strings of the annotations that are to be printed. links specifies the
700
- maximum link recursion depth."""
701
- s = [' '*indent]
702
- s.append('ConstAxis(')
703
- if annotations is None:
704
- annotations = []
705
- for key in annotations:
706
- if key in self:
707
- s.append(' # {}: {}'.format(key, self[key]))
708
- s.append('\n')
709
- indent += 1
710
- s.append(' '*indent)
711
- s.append('value: ')
712
- s.append(str(self.value) + '\n')
713
- indent -= 1
714
- s.append(' '*indent)
715
- s.append(')')
716
- return ''.join(s)
717
-
718
- __str__ = dump
719
- __repr__ = dump
720
-
721
- def find_reachable(self, id_map=None):
722
- """Returns a dictionary mapping Python id() values to stable sequence
723
- numbers for all nodes in the tree rooted at this node. If id_map is
724
- specified, found nodes are appended to it."""
725
- if id_map is None:
726
- id_map = {}
727
- if id(self) in id_map:
728
- raise NotWellFormed('node {!r} with id {} occurs more than once'.format(self, id(self)))
729
- id_map[id(self)] = len(id_map)
730
- return id_map
731
-
732
- def check_complete(self, id_map=None):
733
- """Raises NotWellFormed if the tree rooted at this node is not
734
- well-formed. If id_map is specified, this tree is only a subtree in the
735
- context of a larger tree, and id_map must be a dict mapping from Python
736
- id() codes to tree indices for all reachable nodes."""
737
- if id_map is None:
738
- id_map = self.find_reachable()
739
-
740
- def copy(self):
741
- """Returns a shallow copy of this node."""
742
- return ConstAxis(
743
- value=self._attr_value
744
- )
745
-
746
- def clone(self):
747
- """Returns a deep copy of this node. This mimics the C++ interface,
748
- deficiencies with links included; that is, links always point to the
749
- original tree. If you're not cloning a subtree in a context where this
750
- is the desired behavior, you may want to use the copy.deepcopy() from
751
- the stdlib instead, which should copy links correctly."""
752
- return ConstAxis(
753
- value=_cloned(self._attr_value)
754
- )
755
652
 
756
653
  @staticmethod
757
654
  def _deserialize(cbor, seq_to_ob, links):
@@ -766,50 +663,20 @@ class ConstAxis(Constant):
766
663
  typ = cbor.get('@t', None)
767
664
  if typ is None:
768
665
  raise ValueError('type (@t) field is missing from node serialization')
769
- if typ != 'ConstAxis':
770
- raise ValueError('found node serialization for ' + typ + ', but expected ConstAxis')
771
-
772
- # Deserialize the value field.
773
- field = cbor.get('value', None)
774
- if not isinstance(field, dict):
775
- raise ValueError('missing or invalid serialization of field value')
776
- if hasattr(cqasm.v3x.primitives.Axis, 'deserialize_cbor'):
777
- f_value = cqasm.v3x.primitives.Axis.deserialize_cbor(field)
778
- else:
779
- f_value = cqasm.v3x.primitives.deserialize(cqasm.v3x.primitives.Axis, field)
780
-
781
- # Construct the ConstAxis node.
782
- node = ConstAxis(f_value)
783
-
784
- # Deserialize annotations.
785
- for key, val in cbor.items():
786
- if not (key.startswith('{') and key.endswith('}')):
787
- continue
788
- key = key[1:-1]
789
- node[key] = cqasm.v3x.primitives.deserialize(key, val)
790
-
791
- # Register node in sequence number lookup.
792
- seq = cbor.get('@i', None)
793
- if not isinstance(seq, int):
794
- raise ValueError('sequence number field (@i) is not an integer or missing from node serialization')
795
- if seq in seq_to_ob:
796
- raise ValueError('duplicate sequence number %d' % seq)
797
- seq_to_ob[seq] = node
798
-
799
- return node
666
+ if typ == 'ConstBool':
667
+ return ConstBool._deserialize(cbor, seq_to_ob, links)
668
+ if typ == 'ConstInt':
669
+ return ConstInt._deserialize(cbor, seq_to_ob, links)
670
+ if typ == 'ConstFloat':
671
+ return ConstFloat._deserialize(cbor, seq_to_ob, links)
672
+ raise ValueError('unknown or unexpected type (@t) found in node serialization')
800
673
 
801
674
  def _serialize(self, id_map):
802
675
  """Serializes this node to the Python primitive representation of its
803
676
  CBOR serialization. The tree that the node belongs to must be
804
677
  well-formed. id_map must match Python id() calls for all nodes to unique
805
678
  integers, to use for the sequence number representation of links."""
806
- cbor = {'@i': id_map[id(self)], '@t': 'ConstAxis'}
807
-
808
- # Serialize the value field.
809
- if hasattr(self._attr_value, 'serialize_cbor'):
810
- cbor['value'] = self._attr_value.serialize_cbor()
811
- else:
812
- cbor['value'] = cqasm.v3x.primitives.serialize(cqasm.v3x.primitives.Axis, self._attr_value)
679
+ cbor = {'@i': id_map[id(self)], '@t': 'Constant'}
813
680
 
814
681
  # Serialize annotations.
815
682
  for key, val in self._annot.items():
@@ -818,13 +685,13 @@ class ConstAxis(Constant):
818
685
  return cbor
819
686
 
820
687
 
821
- class MultiConstAxis(_Multiple):
822
- """Wrapper for an edge with multiple ConstAxis objects."""
688
+ class MultiConstant(_Multiple):
689
+ """Wrapper for an edge with multiple Constant objects."""
823
690
 
824
- _T = ConstAxis
691
+ _T = Constant
825
692
 
826
693
 
827
- _typemap['ConstAxis'] = ConstAxis
694
+ _typemap['Constant'] = Constant
828
695
 
829
696
  class ConstBool(Constant):
830
697
  __slots__ = [
@@ -1000,7 +867,7 @@ class MultiConstBool(_Multiple):
1000
867
 
1001
868
  _typemap['ConstBool'] = ConstBool
1002
869
 
1003
- class ConstBoolArray(Constant):
870
+ class ConstFloat(Constant):
1004
871
  __slots__ = [
1005
872
  '_attr_value',
1006
873
  ]
@@ -1021,20 +888,20 @@ class ConstBoolArray(Constant):
1021
888
  if val is None:
1022
889
  del self.value
1023
890
  return
1024
- if not isinstance(val, MultiConstBool):
891
+ if not isinstance(val, cqasm.v3x.primitives.Float):
1025
892
  # Try to "typecast" if this isn't an obvious mistake.
1026
893
  if isinstance(val, Node):
1027
- raise TypeError('value must be of type MultiConstBool')
1028
- val = MultiConstBool(val)
894
+ raise TypeError('value must be of type cqasm.v3x.primitives.Float')
895
+ val = cqasm.v3x.primitives.Float(val)
1029
896
  self._attr_value = val
1030
897
 
1031
898
  @value.deleter
1032
899
  def value(self):
1033
- self._attr_value = MultiConstBool()
900
+ self._attr_value = cqasm.v3x.primitives.Float()
1034
901
 
1035
902
  def __eq__(self, other):
1036
903
  """Equality operator. Ignores annotations!"""
1037
- if not isinstance(other, ConstBoolArray):
904
+ if not isinstance(other, ConstFloat):
1038
905
  return False
1039
906
  if self.value != other.value:
1040
907
  return False
@@ -1047,7 +914,7 @@ class ConstBoolArray(Constant):
1047
914
  strings of the annotations that are to be printed. links specifies the
1048
915
  maximum link recursion depth."""
1049
916
  s = [' '*indent]
1050
- s.append('ConstBoolArray(')
917
+ s.append('ConstFloat(')
1051
918
  if annotations is None:
1052
919
  annotations = []
1053
920
  for key in annotations:
@@ -1057,13 +924,7 @@ class ConstBoolArray(Constant):
1057
924
  indent += 1
1058
925
  s.append(' '*indent)
1059
926
  s.append('value: ')
1060
- if not self.value:
1061
- s.append('!MISSING\n')
1062
- else:
1063
- s.append('[\n')
1064
- for child in self.value:
1065
- s.append(child.dump(indent + 1, annotations, links) + '\n')
1066
- s.append(' '*indent + ']\n')
927
+ s.append(str(self.value) + '\n')
1067
928
  indent -= 1
1068
929
  s.append(' '*indent)
1069
930
  s.append(')')
@@ -1081,8 +942,6 @@ class ConstBoolArray(Constant):
1081
942
  if id(self) in id_map:
1082
943
  raise NotWellFormed('node {!r} with id {} occurs more than once'.format(self, id(self)))
1083
944
  id_map[id(self)] = len(id_map)
1084
- for el in self._attr_value:
1085
- el.find_reachable(id_map)
1086
945
  return id_map
1087
946
 
1088
947
  def check_complete(self, id_map=None):
@@ -1092,15 +951,11 @@ class ConstBoolArray(Constant):
1092
951
  id() codes to tree indices for all reachable nodes."""
1093
952
  if id_map is None:
1094
953
  id_map = self.find_reachable()
1095
- if not self._attr_value:
1096
- raise NotWellFormed('value needs at least one node but has zero')
1097
- for child in self._attr_value:
1098
- child.check_complete(id_map)
1099
954
 
1100
955
  def copy(self):
1101
956
  """Returns a shallow copy of this node."""
1102
- return ConstBoolArray(
1103
- value=self._attr_value.copy()
957
+ return ConstFloat(
958
+ value=self._attr_value
1104
959
  )
1105
960
 
1106
961
  def clone(self):
@@ -1109,7 +964,7 @@ class ConstBoolArray(Constant):
1109
964
  original tree. If you're not cloning a subtree in a context where this
1110
965
  is the desired behavior, you may want to use the copy.deepcopy() from
1111
966
  the stdlib instead, which should copy links correctly."""
1112
- return ConstBoolArray(
967
+ return ConstFloat(
1113
968
  value=_cloned(self._attr_value)
1114
969
  )
1115
970
 
@@ -1126,26 +981,20 @@ class ConstBoolArray(Constant):
1126
981
  typ = cbor.get('@t', None)
1127
982
  if typ is None:
1128
983
  raise ValueError('type (@t) field is missing from node serialization')
1129
- if typ != 'ConstBoolArray':
1130
- raise ValueError('found node serialization for ' + typ + ', but expected ConstBoolArray')
984
+ if typ != 'ConstFloat':
985
+ raise ValueError('found node serialization for ' + typ + ', but expected ConstFloat')
1131
986
 
1132
987
  # Deserialize the value field.
1133
988
  field = cbor.get('value', None)
1134
989
  if not isinstance(field, dict):
1135
990
  raise ValueError('missing or invalid serialization of field value')
1136
- if field.get('@T') != '+':
1137
- raise ValueError('unexpected edge type for field value')
1138
- data = field.get('@d', None)
1139
- if not isinstance(data, list):
1140
- raise ValueError('missing serialization of Any/Many contents')
1141
- f_value = MultiConstBool()
1142
- for element in data:
1143
- if element.get('@T') != '1':
1144
- raise ValueError('unexpected edge type for Any/Many element')
1145
- f_value.append(ConstBool._deserialize(element, seq_to_ob, links))
991
+ if hasattr(cqasm.v3x.primitives.Float, 'deserialize_cbor'):
992
+ f_value = cqasm.v3x.primitives.Float.deserialize_cbor(field)
993
+ else:
994
+ f_value = cqasm.v3x.primitives.deserialize(cqasm.v3x.primitives.Float, field)
1146
995
 
1147
- # Construct the ConstBoolArray node.
1148
- node = ConstBoolArray(f_value)
996
+ # Construct the ConstFloat node.
997
+ node = ConstFloat(f_value)
1149
998
 
1150
999
  # Deserialize annotations.
1151
1000
  for key, val in cbor.items():
@@ -1169,17 +1018,13 @@ class ConstBoolArray(Constant):
1169
1018
  CBOR serialization. The tree that the node belongs to must be
1170
1019
  well-formed. id_map must match Python id() calls for all nodes to unique
1171
1020
  integers, to use for the sequence number representation of links."""
1172
- cbor = {'@i': id_map[id(self)], '@t': 'ConstBoolArray'}
1021
+ cbor = {'@i': id_map[id(self)], '@t': 'ConstFloat'}
1173
1022
 
1174
1023
  # Serialize the value field.
1175
- field = {'@T': '+'}
1176
- lst = []
1177
- for el in self._attr_value:
1178
- el = el._serialize(id_map)
1179
- el['@T'] = '1'
1180
- lst.append(el)
1181
- field['@d'] = lst
1182
- cbor['value'] = field
1024
+ if hasattr(self._attr_value, 'serialize_cbor'):
1025
+ cbor['value'] = self._attr_value.serialize_cbor()
1026
+ else:
1027
+ cbor['value'] = cqasm.v3x.primitives.serialize(cqasm.v3x.primitives.Float, self._attr_value)
1183
1028
 
1184
1029
  # Serialize annotations.
1185
1030
  for key, val in self._annot.items():
@@ -1188,15 +1033,15 @@ class ConstBoolArray(Constant):
1188
1033
  return cbor
1189
1034
 
1190
1035
 
1191
- class MultiConstBoolArray(_Multiple):
1192
- """Wrapper for an edge with multiple ConstBoolArray objects."""
1036
+ class MultiConstFloat(_Multiple):
1037
+ """Wrapper for an edge with multiple ConstFloat objects."""
1193
1038
 
1194
- _T = ConstBoolArray
1039
+ _T = ConstFloat
1195
1040
 
1196
1041
 
1197
- _typemap['ConstBoolArray'] = ConstBoolArray
1042
+ _typemap['ConstFloat'] = ConstFloat
1198
1043
 
1199
- class ConstComplex(Constant):
1044
+ class ConstInt(Constant):
1200
1045
  __slots__ = [
1201
1046
  '_attr_value',
1202
1047
  ]
@@ -1217,20 +1062,20 @@ class ConstComplex(Constant):
1217
1062
  if val is None:
1218
1063
  del self.value
1219
1064
  return
1220
- if not isinstance(val, cqasm.v3x.primitives.Complex):
1065
+ if not isinstance(val, cqasm.v3x.primitives.Int):
1221
1066
  # Try to "typecast" if this isn't an obvious mistake.
1222
1067
  if isinstance(val, Node):
1223
- raise TypeError('value must be of type cqasm.v3x.primitives.Complex')
1224
- val = cqasm.v3x.primitives.Complex(val)
1068
+ raise TypeError('value must be of type cqasm.v3x.primitives.Int')
1069
+ val = cqasm.v3x.primitives.Int(val)
1225
1070
  self._attr_value = val
1226
1071
 
1227
1072
  @value.deleter
1228
1073
  def value(self):
1229
- self._attr_value = cqasm.v3x.primitives.Complex()
1074
+ self._attr_value = cqasm.v3x.primitives.Int()
1230
1075
 
1231
1076
  def __eq__(self, other):
1232
1077
  """Equality operator. Ignores annotations!"""
1233
- if not isinstance(other, ConstComplex):
1078
+ if not isinstance(other, ConstInt):
1234
1079
  return False
1235
1080
  if self.value != other.value:
1236
1081
  return False
@@ -1243,7 +1088,7 @@ class ConstComplex(Constant):
1243
1088
  strings of the annotations that are to be printed. links specifies the
1244
1089
  maximum link recursion depth."""
1245
1090
  s = [' '*indent]
1246
- s.append('ConstComplex(')
1091
+ s.append('ConstInt(')
1247
1092
  if annotations is None:
1248
1093
  annotations = []
1249
1094
  for key in annotations:
@@ -1283,7 +1128,7 @@ class ConstComplex(Constant):
1283
1128
 
1284
1129
  def copy(self):
1285
1130
  """Returns a shallow copy of this node."""
1286
- return ConstComplex(
1131
+ return ConstInt(
1287
1132
  value=self._attr_value
1288
1133
  )
1289
1134
 
@@ -1293,7 +1138,7 @@ class ConstComplex(Constant):
1293
1138
  original tree. If you're not cloning a subtree in a context where this
1294
1139
  is the desired behavior, you may want to use the copy.deepcopy() from
1295
1140
  the stdlib instead, which should copy links correctly."""
1296
- return ConstComplex(
1141
+ return ConstInt(
1297
1142
  value=_cloned(self._attr_value)
1298
1143
  )
1299
1144
 
@@ -1310,20 +1155,20 @@ class ConstComplex(Constant):
1310
1155
  typ = cbor.get('@t', None)
1311
1156
  if typ is None:
1312
1157
  raise ValueError('type (@t) field is missing from node serialization')
1313
- if typ != 'ConstComplex':
1314
- raise ValueError('found node serialization for ' + typ + ', but expected ConstComplex')
1158
+ if typ != 'ConstInt':
1159
+ raise ValueError('found node serialization for ' + typ + ', but expected ConstInt')
1315
1160
 
1316
1161
  # Deserialize the value field.
1317
1162
  field = cbor.get('value', None)
1318
1163
  if not isinstance(field, dict):
1319
1164
  raise ValueError('missing or invalid serialization of field value')
1320
- if hasattr(cqasm.v3x.primitives.Complex, 'deserialize_cbor'):
1321
- f_value = cqasm.v3x.primitives.Complex.deserialize_cbor(field)
1165
+ if hasattr(cqasm.v3x.primitives.Int, 'deserialize_cbor'):
1166
+ f_value = cqasm.v3x.primitives.Int.deserialize_cbor(field)
1322
1167
  else:
1323
- f_value = cqasm.v3x.primitives.deserialize(cqasm.v3x.primitives.Complex, field)
1168
+ f_value = cqasm.v3x.primitives.deserialize(cqasm.v3x.primitives.Int, field)
1324
1169
 
1325
- # Construct the ConstComplex node.
1326
- node = ConstComplex(f_value)
1170
+ # Construct the ConstInt node.
1171
+ node = ConstInt(f_value)
1327
1172
 
1328
1173
  # Deserialize annotations.
1329
1174
  for key, val in cbor.items():
@@ -1347,13 +1192,13 @@ class ConstComplex(Constant):
1347
1192
  CBOR serialization. The tree that the node belongs to must be
1348
1193
  well-formed. id_map must match Python id() calls for all nodes to unique
1349
1194
  integers, to use for the sequence number representation of links."""
1350
- cbor = {'@i': id_map[id(self)], '@t': 'ConstComplex'}
1195
+ cbor = {'@i': id_map[id(self)], '@t': 'ConstInt'}
1351
1196
 
1352
1197
  # Serialize the value field.
1353
1198
  if hasattr(self._attr_value, 'serialize_cbor'):
1354
1199
  cbor['value'] = self._attr_value.serialize_cbor()
1355
1200
  else:
1356
- cbor['value'] = cqasm.v3x.primitives.serialize(cqasm.v3x.primitives.Complex, self._attr_value)
1201
+ cbor['value'] = cqasm.v3x.primitives.serialize(cqasm.v3x.primitives.Int, self._attr_value)
1357
1202
 
1358
1203
  # Serialize annotations.
1359
1204
  for key, val in self._annot.items():
@@ -1362,755 +1207,15 @@ class ConstComplex(Constant):
1362
1207
  return cbor
1363
1208
 
1364
1209
 
1365
- class MultiConstComplex(_Multiple):
1366
- """Wrapper for an edge with multiple ConstComplex objects."""
1367
-
1368
- _T = ConstComplex
1369
-
1370
-
1371
- _typemap['ConstComplex'] = ConstComplex
1372
-
1373
- class ConstInt(Constant):
1374
- __slots__ = [
1375
- '_attr_value',
1376
- ]
1377
-
1378
- def __init__(
1379
- self,
1380
- value=None,
1381
- ):
1382
- super().__init__()
1383
- self.value = value
1384
-
1385
- @property
1386
- def value(self):
1387
- return self._attr_value
1388
-
1389
- @value.setter
1390
- def value(self, val):
1391
- if val is None:
1392
- del self.value
1393
- return
1394
- if not isinstance(val, cqasm.v3x.primitives.Int):
1395
- # Try to "typecast" if this isn't an obvious mistake.
1396
- if isinstance(val, Node):
1397
- raise TypeError('value must be of type cqasm.v3x.primitives.Int')
1398
- val = cqasm.v3x.primitives.Int(val)
1399
- self._attr_value = val
1400
-
1401
- @value.deleter
1402
- def value(self):
1403
- self._attr_value = cqasm.v3x.primitives.Int()
1404
-
1405
- def __eq__(self, other):
1406
- """Equality operator. Ignores annotations!"""
1407
- if not isinstance(other, ConstInt):
1408
- return False
1409
- if self.value != other.value:
1410
- return False
1411
- return True
1210
+ class MultiConstInt(_Multiple):
1211
+ """Wrapper for an edge with multiple ConstInt objects."""
1412
1212
 
1413
- def dump(self, indent=0, annotations=None, links=1):
1414
- """Returns a debug representation of this tree as a multiline string.
1415
- indent is the number of double spaces prefixed before every line.
1416
- annotations, if specified, must be a set-like object containing the key
1417
- strings of the annotations that are to be printed. links specifies the
1418
- maximum link recursion depth."""
1419
- s = [' '*indent]
1420
- s.append('ConstInt(')
1421
- if annotations is None:
1422
- annotations = []
1423
- for key in annotations:
1424
- if key in self:
1425
- s.append(' # {}: {}'.format(key, self[key]))
1426
- s.append('\n')
1427
- indent += 1
1428
- s.append(' '*indent)
1429
- s.append('value: ')
1430
- s.append(str(self.value) + '\n')
1431
- indent -= 1
1432
- s.append(' '*indent)
1433
- s.append(')')
1434
- return ''.join(s)
1435
-
1436
- __str__ = dump
1437
- __repr__ = dump
1438
-
1439
- def find_reachable(self, id_map=None):
1440
- """Returns a dictionary mapping Python id() values to stable sequence
1441
- numbers for all nodes in the tree rooted at this node. If id_map is
1442
- specified, found nodes are appended to it."""
1443
- if id_map is None:
1444
- id_map = {}
1445
- if id(self) in id_map:
1446
- raise NotWellFormed('node {!r} with id {} occurs more than once'.format(self, id(self)))
1447
- id_map[id(self)] = len(id_map)
1448
- return id_map
1449
-
1450
- def check_complete(self, id_map=None):
1451
- """Raises NotWellFormed if the tree rooted at this node is not
1452
- well-formed. If id_map is specified, this tree is only a subtree in the
1453
- context of a larger tree, and id_map must be a dict mapping from Python
1454
- id() codes to tree indices for all reachable nodes."""
1455
- if id_map is None:
1456
- id_map = self.find_reachable()
1457
-
1458
- def copy(self):
1459
- """Returns a shallow copy of this node."""
1460
- return ConstInt(
1461
- value=self._attr_value
1462
- )
1463
-
1464
- def clone(self):
1465
- """Returns a deep copy of this node. This mimics the C++ interface,
1466
- deficiencies with links included; that is, links always point to the
1467
- original tree. If you're not cloning a subtree in a context where this
1468
- is the desired behavior, you may want to use the copy.deepcopy() from
1469
- the stdlib instead, which should copy links correctly."""
1470
- return ConstInt(
1471
- value=_cloned(self._attr_value)
1472
- )
1473
-
1474
- @staticmethod
1475
- def _deserialize(cbor, seq_to_ob, links):
1476
- """Attempts to deserialize the given cbor object (in Python primitive
1477
- representation) into a node of this type. All (sub)nodes are added to
1478
- the seq_to_ob dict, indexed by their cbor sequence number. All links are
1479
- registered in the links list by means of a two-tuple of the setter
1480
- function for the link field and the sequence number of the target node.
1481
- """
1482
- if not isinstance(cbor, dict):
1483
- raise TypeError('node description object must be a dict')
1484
- typ = cbor.get('@t', None)
1485
- if typ is None:
1486
- raise ValueError('type (@t) field is missing from node serialization')
1487
- if typ != 'ConstInt':
1488
- raise ValueError('found node serialization for ' + typ + ', but expected ConstInt')
1489
-
1490
- # Deserialize the value field.
1491
- field = cbor.get('value', None)
1492
- if not isinstance(field, dict):
1493
- raise ValueError('missing or invalid serialization of field value')
1494
- if hasattr(cqasm.v3x.primitives.Int, 'deserialize_cbor'):
1495
- f_value = cqasm.v3x.primitives.Int.deserialize_cbor(field)
1496
- else:
1497
- f_value = cqasm.v3x.primitives.deserialize(cqasm.v3x.primitives.Int, field)
1498
-
1499
- # Construct the ConstInt node.
1500
- node = ConstInt(f_value)
1501
-
1502
- # Deserialize annotations.
1503
- for key, val in cbor.items():
1504
- if not (key.startswith('{') and key.endswith('}')):
1505
- continue
1506
- key = key[1:-1]
1507
- node[key] = cqasm.v3x.primitives.deserialize(key, val)
1508
-
1509
- # Register node in sequence number lookup.
1510
- seq = cbor.get('@i', None)
1511
- if not isinstance(seq, int):
1512
- raise ValueError('sequence number field (@i) is not an integer or missing from node serialization')
1513
- if seq in seq_to_ob:
1514
- raise ValueError('duplicate sequence number %d' % seq)
1515
- seq_to_ob[seq] = node
1516
-
1517
- return node
1518
-
1519
- def _serialize(self, id_map):
1520
- """Serializes this node to the Python primitive representation of its
1521
- CBOR serialization. The tree that the node belongs to must be
1522
- well-formed. id_map must match Python id() calls for all nodes to unique
1523
- integers, to use for the sequence number representation of links."""
1524
- cbor = {'@i': id_map[id(self)], '@t': 'ConstInt'}
1525
-
1526
- # Serialize the value field.
1527
- if hasattr(self._attr_value, 'serialize_cbor'):
1528
- cbor['value'] = self._attr_value.serialize_cbor()
1529
- else:
1530
- cbor['value'] = cqasm.v3x.primitives.serialize(cqasm.v3x.primitives.Int, self._attr_value)
1531
-
1532
- # Serialize annotations.
1533
- for key, val in self._annot.items():
1534
- cbor['{%s}' % key] = _py_to_cbor(cqasm.v3x.primitives.serialize(key, val))
1535
-
1536
- return cbor
1537
-
1538
-
1539
- class MultiConstInt(_Multiple):
1540
- """Wrapper for an edge with multiple ConstInt objects."""
1541
-
1542
- _T = ConstInt
1213
+ _T = ConstInt
1543
1214
 
1544
1215
 
1545
1216
  _typemap['ConstInt'] = ConstInt
1546
1217
 
1547
- class ConstIntArray(Constant):
1548
- __slots__ = [
1549
- '_attr_value',
1550
- ]
1551
-
1552
- def __init__(
1553
- self,
1554
- value=None,
1555
- ):
1556
- super().__init__()
1557
- self.value = value
1558
-
1559
- @property
1560
- def value(self):
1561
- return self._attr_value
1562
-
1563
- @value.setter
1564
- def value(self, val):
1565
- if val is None:
1566
- del self.value
1567
- return
1568
- if not isinstance(val, MultiConstInt):
1569
- # Try to "typecast" if this isn't an obvious mistake.
1570
- if isinstance(val, Node):
1571
- raise TypeError('value must be of type MultiConstInt')
1572
- val = MultiConstInt(val)
1573
- self._attr_value = val
1574
-
1575
- @value.deleter
1576
- def value(self):
1577
- self._attr_value = MultiConstInt()
1578
-
1579
- def __eq__(self, other):
1580
- """Equality operator. Ignores annotations!"""
1581
- if not isinstance(other, ConstIntArray):
1582
- return False
1583
- if self.value != other.value:
1584
- return False
1585
- return True
1586
-
1587
- def dump(self, indent=0, annotations=None, links=1):
1588
- """Returns a debug representation of this tree as a multiline string.
1589
- indent is the number of double spaces prefixed before every line.
1590
- annotations, if specified, must be a set-like object containing the key
1591
- strings of the annotations that are to be printed. links specifies the
1592
- maximum link recursion depth."""
1593
- s = [' '*indent]
1594
- s.append('ConstIntArray(')
1595
- if annotations is None:
1596
- annotations = []
1597
- for key in annotations:
1598
- if key in self:
1599
- s.append(' # {}: {}'.format(key, self[key]))
1600
- s.append('\n')
1601
- indent += 1
1602
- s.append(' '*indent)
1603
- s.append('value: ')
1604
- if not self.value:
1605
- s.append('!MISSING\n')
1606
- else:
1607
- s.append('[\n')
1608
- for child in self.value:
1609
- s.append(child.dump(indent + 1, annotations, links) + '\n')
1610
- s.append(' '*indent + ']\n')
1611
- indent -= 1
1612
- s.append(' '*indent)
1613
- s.append(')')
1614
- return ''.join(s)
1615
-
1616
- __str__ = dump
1617
- __repr__ = dump
1618
-
1619
- def find_reachable(self, id_map=None):
1620
- """Returns a dictionary mapping Python id() values to stable sequence
1621
- numbers for all nodes in the tree rooted at this node. If id_map is
1622
- specified, found nodes are appended to it."""
1623
- if id_map is None:
1624
- id_map = {}
1625
- if id(self) in id_map:
1626
- raise NotWellFormed('node {!r} with id {} occurs more than once'.format(self, id(self)))
1627
- id_map[id(self)] = len(id_map)
1628
- for el in self._attr_value:
1629
- el.find_reachable(id_map)
1630
- return id_map
1631
-
1632
- def check_complete(self, id_map=None):
1633
- """Raises NotWellFormed if the tree rooted at this node is not
1634
- well-formed. If id_map is specified, this tree is only a subtree in the
1635
- context of a larger tree, and id_map must be a dict mapping from Python
1636
- id() codes to tree indices for all reachable nodes."""
1637
- if id_map is None:
1638
- id_map = self.find_reachable()
1639
- if not self._attr_value:
1640
- raise NotWellFormed('value needs at least one node but has zero')
1641
- for child in self._attr_value:
1642
- child.check_complete(id_map)
1643
-
1644
- def copy(self):
1645
- """Returns a shallow copy of this node."""
1646
- return ConstIntArray(
1647
- value=self._attr_value.copy()
1648
- )
1649
-
1650
- def clone(self):
1651
- """Returns a deep copy of this node. This mimics the C++ interface,
1652
- deficiencies with links included; that is, links always point to the
1653
- original tree. If you're not cloning a subtree in a context where this
1654
- is the desired behavior, you may want to use the copy.deepcopy() from
1655
- the stdlib instead, which should copy links correctly."""
1656
- return ConstIntArray(
1657
- value=_cloned(self._attr_value)
1658
- )
1659
-
1660
- @staticmethod
1661
- def _deserialize(cbor, seq_to_ob, links):
1662
- """Attempts to deserialize the given cbor object (in Python primitive
1663
- representation) into a node of this type. All (sub)nodes are added to
1664
- the seq_to_ob dict, indexed by their cbor sequence number. All links are
1665
- registered in the links list by means of a two-tuple of the setter
1666
- function for the link field and the sequence number of the target node.
1667
- """
1668
- if not isinstance(cbor, dict):
1669
- raise TypeError('node description object must be a dict')
1670
- typ = cbor.get('@t', None)
1671
- if typ is None:
1672
- raise ValueError('type (@t) field is missing from node serialization')
1673
- if typ != 'ConstIntArray':
1674
- raise ValueError('found node serialization for ' + typ + ', but expected ConstIntArray')
1675
-
1676
- # Deserialize the value field.
1677
- field = cbor.get('value', None)
1678
- if not isinstance(field, dict):
1679
- raise ValueError('missing or invalid serialization of field value')
1680
- if field.get('@T') != '+':
1681
- raise ValueError('unexpected edge type for field value')
1682
- data = field.get('@d', None)
1683
- if not isinstance(data, list):
1684
- raise ValueError('missing serialization of Any/Many contents')
1685
- f_value = MultiConstInt()
1686
- for element in data:
1687
- if element.get('@T') != '1':
1688
- raise ValueError('unexpected edge type for Any/Many element')
1689
- f_value.append(ConstInt._deserialize(element, seq_to_ob, links))
1690
-
1691
- # Construct the ConstIntArray node.
1692
- node = ConstIntArray(f_value)
1693
-
1694
- # Deserialize annotations.
1695
- for key, val in cbor.items():
1696
- if not (key.startswith('{') and key.endswith('}')):
1697
- continue
1698
- key = key[1:-1]
1699
- node[key] = cqasm.v3x.primitives.deserialize(key, val)
1700
-
1701
- # Register node in sequence number lookup.
1702
- seq = cbor.get('@i', None)
1703
- if not isinstance(seq, int):
1704
- raise ValueError('sequence number field (@i) is not an integer or missing from node serialization')
1705
- if seq in seq_to_ob:
1706
- raise ValueError('duplicate sequence number %d' % seq)
1707
- seq_to_ob[seq] = node
1708
-
1709
- return node
1710
-
1711
- def _serialize(self, id_map):
1712
- """Serializes this node to the Python primitive representation of its
1713
- CBOR serialization. The tree that the node belongs to must be
1714
- well-formed. id_map must match Python id() calls for all nodes to unique
1715
- integers, to use for the sequence number representation of links."""
1716
- cbor = {'@i': id_map[id(self)], '@t': 'ConstIntArray'}
1717
-
1718
- # Serialize the value field.
1719
- field = {'@T': '+'}
1720
- lst = []
1721
- for el in self._attr_value:
1722
- el = el._serialize(id_map)
1723
- el['@T'] = '1'
1724
- lst.append(el)
1725
- field['@d'] = lst
1726
- cbor['value'] = field
1727
-
1728
- # Serialize annotations.
1729
- for key, val in self._annot.items():
1730
- cbor['{%s}' % key] = _py_to_cbor(cqasm.v3x.primitives.serialize(key, val))
1731
-
1732
- return cbor
1733
-
1734
-
1735
- class MultiConstIntArray(_Multiple):
1736
- """Wrapper for an edge with multiple ConstIntArray objects."""
1737
-
1738
- _T = ConstIntArray
1739
-
1740
-
1741
- _typemap['ConstIntArray'] = ConstIntArray
1742
-
1743
- class ConstReal(Constant):
1744
- __slots__ = [
1745
- '_attr_value',
1746
- ]
1747
-
1748
- def __init__(
1749
- self,
1750
- value=None,
1751
- ):
1752
- super().__init__()
1753
- self.value = value
1754
-
1755
- @property
1756
- def value(self):
1757
- return self._attr_value
1758
-
1759
- @value.setter
1760
- def value(self, val):
1761
- if val is None:
1762
- del self.value
1763
- return
1764
- if not isinstance(val, cqasm.v3x.primitives.Real):
1765
- # Try to "typecast" if this isn't an obvious mistake.
1766
- if isinstance(val, Node):
1767
- raise TypeError('value must be of type cqasm.v3x.primitives.Real')
1768
- val = cqasm.v3x.primitives.Real(val)
1769
- self._attr_value = val
1770
-
1771
- @value.deleter
1772
- def value(self):
1773
- self._attr_value = cqasm.v3x.primitives.Real()
1774
-
1775
- def __eq__(self, other):
1776
- """Equality operator. Ignores annotations!"""
1777
- if not isinstance(other, ConstReal):
1778
- return False
1779
- if self.value != other.value:
1780
- return False
1781
- return True
1782
-
1783
- def dump(self, indent=0, annotations=None, links=1):
1784
- """Returns a debug representation of this tree as a multiline string.
1785
- indent is the number of double spaces prefixed before every line.
1786
- annotations, if specified, must be a set-like object containing the key
1787
- strings of the annotations that are to be printed. links specifies the
1788
- maximum link recursion depth."""
1789
- s = [' '*indent]
1790
- s.append('ConstReal(')
1791
- if annotations is None:
1792
- annotations = []
1793
- for key in annotations:
1794
- if key in self:
1795
- s.append(' # {}: {}'.format(key, self[key]))
1796
- s.append('\n')
1797
- indent += 1
1798
- s.append(' '*indent)
1799
- s.append('value: ')
1800
- s.append(str(self.value) + '\n')
1801
- indent -= 1
1802
- s.append(' '*indent)
1803
- s.append(')')
1804
- return ''.join(s)
1805
-
1806
- __str__ = dump
1807
- __repr__ = dump
1808
-
1809
- def find_reachable(self, id_map=None):
1810
- """Returns a dictionary mapping Python id() values to stable sequence
1811
- numbers for all nodes in the tree rooted at this node. If id_map is
1812
- specified, found nodes are appended to it."""
1813
- if id_map is None:
1814
- id_map = {}
1815
- if id(self) in id_map:
1816
- raise NotWellFormed('node {!r} with id {} occurs more than once'.format(self, id(self)))
1817
- id_map[id(self)] = len(id_map)
1818
- return id_map
1819
-
1820
- def check_complete(self, id_map=None):
1821
- """Raises NotWellFormed if the tree rooted at this node is not
1822
- well-formed. If id_map is specified, this tree is only a subtree in the
1823
- context of a larger tree, and id_map must be a dict mapping from Python
1824
- id() codes to tree indices for all reachable nodes."""
1825
- if id_map is None:
1826
- id_map = self.find_reachable()
1827
-
1828
- def copy(self):
1829
- """Returns a shallow copy of this node."""
1830
- return ConstReal(
1831
- value=self._attr_value
1832
- )
1833
-
1834
- def clone(self):
1835
- """Returns a deep copy of this node. This mimics the C++ interface,
1836
- deficiencies with links included; that is, links always point to the
1837
- original tree. If you're not cloning a subtree in a context where this
1838
- is the desired behavior, you may want to use the copy.deepcopy() from
1839
- the stdlib instead, which should copy links correctly."""
1840
- return ConstReal(
1841
- value=_cloned(self._attr_value)
1842
- )
1843
-
1844
- @staticmethod
1845
- def _deserialize(cbor, seq_to_ob, links):
1846
- """Attempts to deserialize the given cbor object (in Python primitive
1847
- representation) into a node of this type. All (sub)nodes are added to
1848
- the seq_to_ob dict, indexed by their cbor sequence number. All links are
1849
- registered in the links list by means of a two-tuple of the setter
1850
- function for the link field and the sequence number of the target node.
1851
- """
1852
- if not isinstance(cbor, dict):
1853
- raise TypeError('node description object must be a dict')
1854
- typ = cbor.get('@t', None)
1855
- if typ is None:
1856
- raise ValueError('type (@t) field is missing from node serialization')
1857
- if typ != 'ConstReal':
1858
- raise ValueError('found node serialization for ' + typ + ', but expected ConstReal')
1859
-
1860
- # Deserialize the value field.
1861
- field = cbor.get('value', None)
1862
- if not isinstance(field, dict):
1863
- raise ValueError('missing or invalid serialization of field value')
1864
- if hasattr(cqasm.v3x.primitives.Real, 'deserialize_cbor'):
1865
- f_value = cqasm.v3x.primitives.Real.deserialize_cbor(field)
1866
- else:
1867
- f_value = cqasm.v3x.primitives.deserialize(cqasm.v3x.primitives.Real, field)
1868
-
1869
- # Construct the ConstReal node.
1870
- node = ConstReal(f_value)
1871
-
1872
- # Deserialize annotations.
1873
- for key, val in cbor.items():
1874
- if not (key.startswith('{') and key.endswith('}')):
1875
- continue
1876
- key = key[1:-1]
1877
- node[key] = cqasm.v3x.primitives.deserialize(key, val)
1878
-
1879
- # Register node in sequence number lookup.
1880
- seq = cbor.get('@i', None)
1881
- if not isinstance(seq, int):
1882
- raise ValueError('sequence number field (@i) is not an integer or missing from node serialization')
1883
- if seq in seq_to_ob:
1884
- raise ValueError('duplicate sequence number %d' % seq)
1885
- seq_to_ob[seq] = node
1886
-
1887
- return node
1888
-
1889
- def _serialize(self, id_map):
1890
- """Serializes this node to the Python primitive representation of its
1891
- CBOR serialization. The tree that the node belongs to must be
1892
- well-formed. id_map must match Python id() calls for all nodes to unique
1893
- integers, to use for the sequence number representation of links."""
1894
- cbor = {'@i': id_map[id(self)], '@t': 'ConstReal'}
1895
-
1896
- # Serialize the value field.
1897
- if hasattr(self._attr_value, 'serialize_cbor'):
1898
- cbor['value'] = self._attr_value.serialize_cbor()
1899
- else:
1900
- cbor['value'] = cqasm.v3x.primitives.serialize(cqasm.v3x.primitives.Real, self._attr_value)
1901
-
1902
- # Serialize annotations.
1903
- for key, val in self._annot.items():
1904
- cbor['{%s}' % key] = _py_to_cbor(cqasm.v3x.primitives.serialize(key, val))
1905
-
1906
- return cbor
1907
-
1908
-
1909
- class MultiConstReal(_Multiple):
1910
- """Wrapper for an edge with multiple ConstReal objects."""
1911
-
1912
- _T = ConstReal
1913
-
1914
-
1915
- _typemap['ConstReal'] = ConstReal
1916
-
1917
- class ConstRealArray(Constant):
1918
- __slots__ = [
1919
- '_attr_value',
1920
- ]
1921
-
1922
- def __init__(
1923
- self,
1924
- value=None,
1925
- ):
1926
- super().__init__()
1927
- self.value = value
1928
-
1929
- @property
1930
- def value(self):
1931
- return self._attr_value
1932
-
1933
- @value.setter
1934
- def value(self, val):
1935
- if val is None:
1936
- del self.value
1937
- return
1938
- if not isinstance(val, MultiConstReal):
1939
- # Try to "typecast" if this isn't an obvious mistake.
1940
- if isinstance(val, Node):
1941
- raise TypeError('value must be of type MultiConstReal')
1942
- val = MultiConstReal(val)
1943
- self._attr_value = val
1944
-
1945
- @value.deleter
1946
- def value(self):
1947
- self._attr_value = MultiConstReal()
1948
-
1949
- def __eq__(self, other):
1950
- """Equality operator. Ignores annotations!"""
1951
- if not isinstance(other, ConstRealArray):
1952
- return False
1953
- if self.value != other.value:
1954
- return False
1955
- return True
1956
-
1957
- def dump(self, indent=0, annotations=None, links=1):
1958
- """Returns a debug representation of this tree as a multiline string.
1959
- indent is the number of double spaces prefixed before every line.
1960
- annotations, if specified, must be a set-like object containing the key
1961
- strings of the annotations that are to be printed. links specifies the
1962
- maximum link recursion depth."""
1963
- s = [' '*indent]
1964
- s.append('ConstRealArray(')
1965
- if annotations is None:
1966
- annotations = []
1967
- for key in annotations:
1968
- if key in self:
1969
- s.append(' # {}: {}'.format(key, self[key]))
1970
- s.append('\n')
1971
- indent += 1
1972
- s.append(' '*indent)
1973
- s.append('value: ')
1974
- if not self.value:
1975
- s.append('!MISSING\n')
1976
- else:
1977
- s.append('[\n')
1978
- for child in self.value:
1979
- s.append(child.dump(indent + 1, annotations, links) + '\n')
1980
- s.append(' '*indent + ']\n')
1981
- indent -= 1
1982
- s.append(' '*indent)
1983
- s.append(')')
1984
- return ''.join(s)
1985
-
1986
- __str__ = dump
1987
- __repr__ = dump
1988
-
1989
- def find_reachable(self, id_map=None):
1990
- """Returns a dictionary mapping Python id() values to stable sequence
1991
- numbers for all nodes in the tree rooted at this node. If id_map is
1992
- specified, found nodes are appended to it."""
1993
- if id_map is None:
1994
- id_map = {}
1995
- if id(self) in id_map:
1996
- raise NotWellFormed('node {!r} with id {} occurs more than once'.format(self, id(self)))
1997
- id_map[id(self)] = len(id_map)
1998
- for el in self._attr_value:
1999
- el.find_reachable(id_map)
2000
- return id_map
2001
-
2002
- def check_complete(self, id_map=None):
2003
- """Raises NotWellFormed if the tree rooted at this node is not
2004
- well-formed. If id_map is specified, this tree is only a subtree in the
2005
- context of a larger tree, and id_map must be a dict mapping from Python
2006
- id() codes to tree indices for all reachable nodes."""
2007
- if id_map is None:
2008
- id_map = self.find_reachable()
2009
- if not self._attr_value:
2010
- raise NotWellFormed('value needs at least one node but has zero')
2011
- for child in self._attr_value:
2012
- child.check_complete(id_map)
2013
-
2014
- def copy(self):
2015
- """Returns a shallow copy of this node."""
2016
- return ConstRealArray(
2017
- value=self._attr_value.copy()
2018
- )
2019
-
2020
- def clone(self):
2021
- """Returns a deep copy of this node. This mimics the C++ interface,
2022
- deficiencies with links included; that is, links always point to the
2023
- original tree. If you're not cloning a subtree in a context where this
2024
- is the desired behavior, you may want to use the copy.deepcopy() from
2025
- the stdlib instead, which should copy links correctly."""
2026
- return ConstRealArray(
2027
- value=_cloned(self._attr_value)
2028
- )
2029
-
2030
- @staticmethod
2031
- def _deserialize(cbor, seq_to_ob, links):
2032
- """Attempts to deserialize the given cbor object (in Python primitive
2033
- representation) into a node of this type. All (sub)nodes are added to
2034
- the seq_to_ob dict, indexed by their cbor sequence number. All links are
2035
- registered in the links list by means of a two-tuple of the setter
2036
- function for the link field and the sequence number of the target node.
2037
- """
2038
- if not isinstance(cbor, dict):
2039
- raise TypeError('node description object must be a dict')
2040
- typ = cbor.get('@t', None)
2041
- if typ is None:
2042
- raise ValueError('type (@t) field is missing from node serialization')
2043
- if typ != 'ConstRealArray':
2044
- raise ValueError('found node serialization for ' + typ + ', but expected ConstRealArray')
2045
-
2046
- # Deserialize the value field.
2047
- field = cbor.get('value', None)
2048
- if not isinstance(field, dict):
2049
- raise ValueError('missing or invalid serialization of field value')
2050
- if field.get('@T') != '+':
2051
- raise ValueError('unexpected edge type for field value')
2052
- data = field.get('@d', None)
2053
- if not isinstance(data, list):
2054
- raise ValueError('missing serialization of Any/Many contents')
2055
- f_value = MultiConstReal()
2056
- for element in data:
2057
- if element.get('@T') != '1':
2058
- raise ValueError('unexpected edge type for Any/Many element')
2059
- f_value.append(ConstReal._deserialize(element, seq_to_ob, links))
2060
-
2061
- # Construct the ConstRealArray node.
2062
- node = ConstRealArray(f_value)
2063
-
2064
- # Deserialize annotations.
2065
- for key, val in cbor.items():
2066
- if not (key.startswith('{') and key.endswith('}')):
2067
- continue
2068
- key = key[1:-1]
2069
- node[key] = cqasm.v3x.primitives.deserialize(key, val)
2070
-
2071
- # Register node in sequence number lookup.
2072
- seq = cbor.get('@i', None)
2073
- if not isinstance(seq, int):
2074
- raise ValueError('sequence number field (@i) is not an integer or missing from node serialization')
2075
- if seq in seq_to_ob:
2076
- raise ValueError('duplicate sequence number %d' % seq)
2077
- seq_to_ob[seq] = node
2078
-
2079
- return node
2080
-
2081
- def _serialize(self, id_map):
2082
- """Serializes this node to the Python primitive representation of its
2083
- CBOR serialization. The tree that the node belongs to must be
2084
- well-formed. id_map must match Python id() calls for all nodes to unique
2085
- integers, to use for the sequence number representation of links."""
2086
- cbor = {'@i': id_map[id(self)], '@t': 'ConstRealArray'}
2087
-
2088
- # Serialize the value field.
2089
- field = {'@T': '+'}
2090
- lst = []
2091
- for el in self._attr_value:
2092
- el = el._serialize(id_map)
2093
- el['@T'] = '1'
2094
- lst.append(el)
2095
- field['@d'] = lst
2096
- cbor['value'] = field
2097
-
2098
- # Serialize annotations.
2099
- for key, val in self._annot.items():
2100
- cbor['{%s}' % key] = _py_to_cbor(cqasm.v3x.primitives.serialize(key, val))
2101
-
2102
- return cbor
2103
-
2104
-
2105
- class MultiConstRealArray(_Multiple):
2106
- """Wrapper for an edge with multiple ConstRealArray objects."""
2107
-
2108
- _T = ConstRealArray
2109
-
2110
-
2111
- _typemap['ConstRealArray'] = ConstRealArray
2112
-
2113
- class Reference(Node):
1218
+ class Reference(ValueBase):
2114
1219
  """Reference to some storage location"""
2115
1220
 
2116
1221
  __slots__ = []