od.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. from services import od
  2. from api import cd
  3. from services.bottom.V0 import Bottom
  4. from services.primitives.boolean_type import Boolean
  5. from services.primitives.integer_type import Integer
  6. from services.primitives.string_type import String
  7. from services.primitives.actioncode_type import ActionCode
  8. from uuid import UUID
  9. from typing import Optional
  10. from util.timer import Timer
  11. NEXT_ID = 0
  12. # Models map names to elements
  13. # This builds the inverse mapping, so we can quickly lookup the name of an element
  14. def build_name_mapping(state, m):
  15. mapping = {}
  16. bottom = Bottom(state)
  17. for name in bottom.read_keys(m):
  18. elements = bottom.read_outgoing_elements(m, name)
  19. if len(elements) > 1:
  20. print(f"Warning: more than one element with name '{name}'")
  21. mapping[elements[0]] = name
  22. return mapping
  23. class NoSuchSlotException(Exception):
  24. pass
  25. # Object Diagram API
  26. # Intended to replace the 'services.od.OD' class eventually
  27. class ODAPI:
  28. def __init__(self, state, m: UUID, mm: UUID):
  29. self.state = state
  30. self.bottom = Bottom(state)
  31. self.m = m
  32. self.mm = mm
  33. self.od = od.OD(mm, m, state)
  34. self.cdapi = cd.CDAPI(state, mm)
  35. self.create_boolean_value = self.od.create_boolean_value
  36. self.create_integer_value = self.od.create_integer_value
  37. self.create_string_value = self.od.create_string_value
  38. self.create_actioncode_value = self.od.create_actioncode_value
  39. self.__recompute_mappings()
  40. # Called after every change - makes querying faster but modifying slower
  41. def __recompute_mappings(self):
  42. self.m_obj_to_name = build_name_mapping(self.state, self.m)
  43. self.mm_obj_to_name = build_name_mapping(self.state, self.mm)
  44. self.type_to_objs = { type_name : set() for type_name in self.bottom.read_keys(self.mm)}
  45. for m_name in self.bottom.read_keys(self.m):
  46. m_element, = self.bottom.read_outgoing_elements(self.m, m_name)
  47. tm_element = self.get_type(m_element)
  48. if tm_element in self.mm_obj_to_name:
  49. tm_name = self.mm_obj_to_name[tm_element]
  50. # self.obj_to_type[m_name] = tm_name
  51. self.type_to_objs[tm_name].add(m_name)
  52. def get_value(self, obj: UUID):
  53. return od.read_primitive_value(self.bottom, obj, self.mm)[0]
  54. def get_target(self, link: UUID):
  55. return self.bottom.read_edge_target(link)
  56. def get_source(self, link: UUID):
  57. return self.bottom.read_edge_source(link)
  58. def get_slot(self, obj: UUID, attr_name: str):
  59. slot = self.od.get_slot(obj, attr_name)
  60. if slot == None:
  61. raise NoSuchSlotException(f"Object '{self.m_obj_to_name[obj]}' has no slot '{attr_name}'")
  62. return slot
  63. def get_slot_link(self, obj: UUID, attr_name: str):
  64. return self.od.get_slot_link(obj, attr_name)
  65. # Parameter 'include_subtypes': whether to include subtypes of the given association
  66. def get_outgoing(self, obj: UUID, assoc_name: str, include_subtypes=True):
  67. outgoing = self.bottom.read_outgoing_edges(obj)
  68. result = []
  69. for o in outgoing:
  70. try:
  71. type_of_outgoing_link = self.get_type_name(o)
  72. except:
  73. continue # OK, not all edges are typed
  74. if (include_subtypes and self.cdapi.is_subtype(super_type_name=assoc_name, sub_type_name=type_of_outgoing_link)
  75. or not include_subtypes and type_of_outgoing_link == assoc_name):
  76. result.append(o)
  77. return result
  78. # Parameter 'include_subtypes': whether to include subtypes of the given association
  79. def get_incoming(self, obj: UUID, assoc_name: str, include_subtypes=True):
  80. incoming = self.bottom.read_incoming_edges(obj)
  81. result = []
  82. for i in incoming:
  83. try:
  84. type_of_incoming_link = self.get_type_name(i)
  85. except:
  86. continue # OK, not all edges are typed
  87. if (include_subtypes and self.cdapi.is_subtype(super_type_name=assoc_name, sub_type_name=type_of_incoming_link)
  88. or not include_subtypes and type_of_incoming_link == assoc_name):
  89. result.append(i)
  90. return result
  91. def get_all_instances(self, type_name: str, include_subtypes=True):
  92. if include_subtypes:
  93. all_types = self.cdapi.transitive_sub_types[type_name]
  94. else:
  95. all_types = set([type_name])
  96. obj_names = [obj_name for type_name in all_types for obj_name in self.type_to_objs[type_name]]
  97. return [(obj_name, self.bottom.read_outgoing_elements(self.m, obj_name)[0]) for obj_name in obj_names]
  98. def get_type(self, obj: UUID):
  99. types = self.bottom.read_outgoing_elements(obj, "Morphism")
  100. if len(types) != 1:
  101. raise Exception(f"Expected obj to have 1 type, instead got {len(types)} types.")
  102. return types[0]
  103. def get_name(self, obj: UUID):
  104. if obj in self.m_obj_to_name:
  105. return self.m_obj_to_name[obj]
  106. elif obj in self.mm_obj_to_name:
  107. return self.mm_obj_to_name[obj]
  108. else:
  109. raise Exception(f"Couldn't find name of {obj} - are you sure it exists in the (meta-)model?")
  110. def get(self, name: str):
  111. results = self.bottom.read_outgoing_elements(self.m, name)
  112. if len(results) == 1:
  113. return results[0]
  114. elif len(results) >= 2:
  115. raise Exception("this should never happen")
  116. else:
  117. raise Exception(f"No such element in model: '{name}'")
  118. def get_type_name(self, obj: UUID):
  119. return self.get_name(self.get_type(obj))
  120. def is_instance(self, obj: UUID, type_name: str, include_subtypes=True):
  121. typ = self.cdapi.get_type(type_name)
  122. types = set(typ) if not include_subtypes else self.cdapi.transitive_sub_types[type_name]
  123. for type_of_obj in self.bottom.read_outgoing_elements(obj, "Morphism"):
  124. if type_of_obj in types:
  125. return True
  126. return False
  127. def delete(self, obj: UUID):
  128. self.bottom.delete_element(obj)
  129. self.__recompute_mappings()
  130. # Does the class of the object have the given attribute?
  131. def has_slot(self, obj: UUID, attr_name: str):
  132. class_name = self.get_name(self.get_type(obj))
  133. return self.od.get_attr_link_name(class_name, attr_name) != None
  134. def get_slots(self, obj: UUID) -> list[str]:
  135. return [attr_name for attr_name, _ in self.od.get_slots(obj)]
  136. def get_slot_value(self, obj: UUID, attr_name: str):
  137. slot = self.get_slot(obj, attr_name)
  138. return self.get_value(slot)
  139. # does the given slot contain code?
  140. # this complements `get_slot_value` which will return code as a string
  141. def slot_has_code(self, obj: UUID, attr_name: str):
  142. slot = self.get_slot(obj, attr_name)
  143. return self.get_type_name(slot) == "ActionCode"
  144. # Returns the given default value if the slot does not exist on the object.
  145. # The attribute must exist in the object's class, or an exception will be thrown.
  146. # The slot may not exist however, if the attribute is defined as 'optional' in the class.
  147. def get_slot_value_default(self, obj: UUID, attr_name: str, default: any):
  148. try:
  149. return self.get_slot_value(obj, attr_name)
  150. except NoSuchSlotException:
  151. return default
  152. # create or update slot value
  153. def set_slot_value(self, obj: UUID, attr_name: str, new_value: any, is_code=False):
  154. obj_name = self.get_name(obj)
  155. link_name = f"{obj_name}_{attr_name}"
  156. target_name = f"{obj_name}.{attr_name}"
  157. old_slot_link = self.get_slot_link(obj, attr_name)
  158. if old_slot_link != None:
  159. old_target = self.get_target(old_slot_link)
  160. # if old_target != None:
  161. self.bottom.delete_element(old_target) # this also deletes the slot-link
  162. new_target = self.create_primitive_value(target_name, new_value, is_code)
  163. slot_type = self.cdapi.find_attribute_type(self.get_type_name(obj), attr_name)
  164. new_link = self.od._create_link(link_name, slot_type, obj, new_target)
  165. self.__recompute_mappings()
  166. def create_primitive_value(self, name: str, value: any, is_code=False):
  167. # watch out: in Python, 'bool' is subtype of 'int'
  168. # so we must check for 'bool' first
  169. if isinstance(value, bool):
  170. tgt = self.create_boolean_value(name, value)
  171. elif isinstance(value, int):
  172. tgt = self.create_integer_value(name, value)
  173. elif isinstance(value, str):
  174. if is_code:
  175. tgt = self.create_actioncode_value(name, value)
  176. else:
  177. tgt = self.create_string_value(name, value)
  178. else:
  179. raise Exception("Unimplemented type "+value)
  180. self.__recompute_mappings()
  181. return tgt
  182. def overwrite_primitive_value(self, name: str, value: any, is_code=False):
  183. referred_model = UUID(self.bottom.read_value(self.get(name)))
  184. # watch out: in Python, 'bool' is subtype of 'int'
  185. # so we must check for 'bool' first
  186. if isinstance(value, bool):
  187. Boolean(referred_model, self.state).create(value)
  188. elif isinstance(value, int):
  189. Integer(referred_model, self.state).create(value)
  190. elif isinstance(value, str):
  191. if is_code:
  192. ActionCode(referred_model, self.state).create(value)
  193. else:
  194. String(referred_model, self.state).create(value)
  195. else:
  196. raise Exception("Unimplemented type "+value)
  197. def create_link(self, link_name: Optional[str], assoc_name: str, src: UUID, tgt: UUID):
  198. global NEXT_ID
  199. types = self.bottom.read_outgoing_elements(self.mm, assoc_name)
  200. if len(types) == 0:
  201. raise Exception(f"No such association: '{assoc_name}'")
  202. elif len(types) >= 2:
  203. raise Exception(f"More than one association exists with name '{assoc_name}' - this means the MM is invalid.")
  204. typ = types[0]
  205. if link_name == None:
  206. link_name = f"__{assoc_name}{NEXT_ID}"
  207. NEXT_ID += 1
  208. link_id = self.od._create_link(link_name, typ, src, tgt)
  209. self.__recompute_mappings()
  210. return link_id
  211. def create_object(self, object_name: Optional[str], class_name: str):
  212. obj = self.od.create_object(object_name, class_name)
  213. self.__recompute_mappings()
  214. return obj
  215. # internal use
  216. # Get API methods as bound functions, to pass as globals to 'eval'
  217. # Readonly version is used for:
  218. # - Conformance checking
  219. # - Pattern matching (LHS/NAC of rule)
  220. def bind_api_readonly(odapi):
  221. funcs = {
  222. 'read_value': odapi.state.read_value,
  223. 'get': odapi.get,
  224. 'get_value': odapi.get_value,
  225. 'get_target': odapi.get_target,
  226. 'get_source': odapi.get_source,
  227. 'get_slot': odapi.get_slot,
  228. 'get_slot_value': odapi.get_slot_value,
  229. 'get_slot_value_default': odapi.get_slot_value_default,
  230. 'get_all_instances': odapi.get_all_instances,
  231. 'get_name': odapi.get_name,
  232. 'get_type_name': odapi.get_type_name,
  233. 'get_outgoing': odapi.get_outgoing,
  234. 'get_incoming': odapi.get_incoming,
  235. 'has_slot': odapi.has_slot,
  236. }
  237. return funcs
  238. # internal use
  239. # Get API methods as bound functions, to pass as globals to 'eval'
  240. # Read/write version is used for:
  241. # - Graph rewriting (RHS of rule)
  242. def bind_api(odapi):
  243. funcs = {
  244. **bind_api_readonly(odapi),
  245. 'create_object': odapi.create_object,
  246. 'create_link': odapi.create_link,
  247. 'delete': odapi.delete,
  248. 'set_slot_value': odapi.set_slot_value,
  249. }
  250. return funcs