od.py 11 KB

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