conformance.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682
  1. from services.bottom.V0 import Bottom
  2. from services import od
  3. from services.primitives.actioncode_type import ActionCode
  4. from uuid import UUID
  5. from state.base import State
  6. from typing import Dict, Tuple, Set, Any, List
  7. from pprint import pprint
  8. import traceback
  9. from concrete_syntax.common import indent
  10. from api.cd import CDAPI
  11. from api.od import ODAPI
  12. import functools
  13. # based on https://stackoverflow.com/a/39381428
  14. # Parses and executes a block of Python code, and returns the eval result of the last statement
  15. import ast
  16. def exec_then_eval(code, _globals, _locals):
  17. block = ast.parse(code, mode='exec')
  18. # assumes last node is an expression
  19. last = ast.Expression(block.body.pop().value)
  20. exec(compile(block, '<string>', mode='exec'), _globals, _locals)
  21. return eval(compile(last, '<string>', mode='eval'), _globals, _locals)
  22. def render_conformance_check_result(error_list):
  23. if len(error_list) == 0:
  24. return "CONFORM"
  25. else:
  26. joined = ''.join(('\n ▸ ' + err for err in error_list))
  27. return f"NOT CONFORM, {len(error_list)} errors:{joined}"
  28. class Conformance:
  29. def __init__(self, state: State, model: UUID, type_model: UUID, constraint_check_subtypes=True):
  30. self.state = state
  31. self.bottom = Bottom(state)
  32. type_model_id = state.read_dict(state.read_root(), "SCD")
  33. self.scd_model = UUID(state.read_value(type_model_id))
  34. self.model = model
  35. self.type_model = type_model
  36. self.constraint_check_subtypes = constraint_check_subtypes # for a class-level constraint, also check the constraint on the subtypes of that class? In other words, are constraints inherited.
  37. self.type_mapping: Dict[str, str] = {}
  38. self.model_names = {
  39. # map model elements to their names to prevent iterating too much
  40. self.bottom.read_outgoing_elements(self.model, e)[0]: e
  41. for e in self.bottom.read_keys(self.model)
  42. }
  43. self.type_model_names = {
  44. # map type model elements to their names to prevent iterating too much
  45. self.bottom.read_outgoing_elements(self.type_model, e)[0]
  46. : e for e in self.bottom.read_keys(self.type_model)
  47. }
  48. self.sub_types: Dict[str, Set[str]] = {
  49. k: set() for k in self.bottom.read_keys(self.type_model)
  50. }
  51. self.primitive_values: Dict[UUID, Any] = {}
  52. self.abstract_types: List[str] = []
  53. self.multiplicities: Dict[str, Tuple] = {}
  54. self.source_multiplicities: Dict[str, Tuple] = {}
  55. self.target_multiplicities: Dict[str, Tuple] = {}
  56. self.structures = {}
  57. self.matches = {}
  58. self.candidates = {}
  59. self.odapi = ODAPI(state, model, type_model)
  60. def check_nominal(self, *, log=False):
  61. """
  62. Perform a nominal conformance check
  63. Args:
  64. log: boolean indicating whether to log errors
  65. Returns:
  66. Boolean indicating whether the check has passed
  67. """
  68. errors = []
  69. errors += self.check_typing()
  70. errors += self.check_link_typing()
  71. errors += self.check_multiplicities()
  72. errors += self.check_constraints()
  73. return errors
  74. # def check_structural(self, *, build_morphisms=True, log=False):
  75. # """
  76. # Perform a structural conformance check
  77. # Args:
  78. # build_morphisms: boolean indicating whether to create morpishm links
  79. # log: boolean indicating whether to log errors
  80. # Returns:
  81. # Boolean indicating whether the check has passed
  82. # """
  83. # try:
  84. # self.precompute_structures()
  85. # self.match_structures()
  86. # if build_morphisms:
  87. # self.build_morphisms()
  88. # self.check_nominal(log=log)
  89. # return True
  90. # except RuntimeError as e:
  91. # if log:
  92. # print(e)
  93. # return False
  94. def read_attribute(self, element: UUID, attr_name: str):
  95. """
  96. Read an attribute value attached to an element
  97. Args:
  98. element: UUID of the element
  99. attr_name: name of the attribute to read
  100. Returns:
  101. The value of hte attribute, if no attribute with given name is found, returns None
  102. """
  103. if element in self.type_model_names:
  104. # type model element
  105. element_name = self.type_model_names[element]
  106. model = self.type_model
  107. else:
  108. # model element
  109. element_name = self.model_names[element]
  110. model = self.model
  111. try:
  112. attr_elem, = self.bottom.read_outgoing_elements(model, f"{element_name}.{attr_name}")
  113. return self.primitive_values.get(attr_elem, self.bottom.read_value(UUID(self.bottom.read_value(attr_elem))))
  114. except ValueError:
  115. return None
  116. def precompute_sub_types(self):
  117. """
  118. Creates an internal representation of sub-type hierarchies that is
  119. more easily queryable that the state graph
  120. """
  121. # collect inheritance link instances
  122. inh_element, = self.bottom.read_outgoing_elements(self.scd_model, "Inheritance")
  123. inh_links = []
  124. for tm_element, tm_name in self.type_model_names.items():
  125. morphisms = self.bottom.read_outgoing_elements(tm_element, "Morphism")
  126. if inh_element in morphisms:
  127. # we have an instance of an inheritance link
  128. inh_links.append(tm_element)
  129. # for each inheritance link we add the parent and child to the sub types map
  130. for link in inh_links:
  131. tm_source = self.bottom.read_edge_source(link)
  132. tm_target = self.bottom.read_edge_target(link)
  133. parent_name = self.type_model_names[tm_target]
  134. child_name = self.type_model_names[tm_source]
  135. self.sub_types[parent_name].add(child_name)
  136. # iteratively expand the sub type hierarchies in the sub types map
  137. stop = False
  138. while not stop:
  139. stop = True
  140. for child_name, child_children in self.sub_types.items():
  141. for parent_name, parent_children in self.sub_types.items():
  142. if child_name in parent_children:
  143. original_size = len(parent_children)
  144. parent_children.update(child_children)
  145. if len(parent_children) != original_size:
  146. stop = False
  147. def deref_primitive_values(self):
  148. """
  149. Prefetch the values stored in referenced primitive type models
  150. """
  151. ref_element, = self.bottom.read_outgoing_elements(self.scd_model, "ModelRef")
  152. string_element, = self.bottom.read_outgoing_elements(self.scd_model, "String")
  153. boolean_element, = self.bottom.read_outgoing_elements(self.scd_model, "Boolean")
  154. integer_element, = self.bottom.read_outgoing_elements(self.scd_model, "Integer")
  155. t_deref = []
  156. t_refs = []
  157. for tm_element, tm_name in self.type_model_names.items():
  158. morphisms = self.bottom.read_outgoing_elements(tm_element, "Morphism")
  159. if ref_element in morphisms:
  160. t_refs.append(self.type_model_names[tm_element])
  161. elif string_element in morphisms:
  162. t_deref.append(tm_element)
  163. elif boolean_element in morphisms:
  164. t_deref.append(tm_element)
  165. elif integer_element in morphisms:
  166. t_deref.append(tm_element)
  167. for elem in t_deref:
  168. primitive_model = UUID(self.bottom.read_value(elem))
  169. primitive_value_node, = self.bottom.read_outgoing_elements(primitive_model)
  170. primitive_value = self.bottom.read_value(primitive_value_node)
  171. self.primitive_values[elem] = primitive_value
  172. for m_name, tm_name in self.type_mapping.items():
  173. if tm_name in t_refs:
  174. # dereference
  175. m_element, = self.bottom.read_outgoing_elements(self.model, m_name)
  176. primitive_model = UUID(self.bottom.read_value(m_element))
  177. try:
  178. primitive_value_node, = self.bottom.read_outgoing_elements(primitive_model)
  179. primitive_value = self.bottom.read_value(primitive_value_node)
  180. self.primitive_values[m_element] = primitive_value
  181. except ValueError:
  182. pass # multiple elements in model indicate that we're not dealing with a primitive
  183. def precompute_multiplicities(self):
  184. """
  185. Creates an internal representation of type multiplicities that is
  186. more easily queryable that the state graph
  187. """
  188. for tm_element, tm_name in self.type_model_names.items():
  189. # class abstract flags and multiplicities
  190. abstract = self.read_attribute(tm_element, "abstract")
  191. lc = self.read_attribute(tm_element, "lower_cardinality")
  192. uc = self.read_attribute(tm_element, "upper_cardinality")
  193. if abstract:
  194. self.abstract_types.append(tm_name)
  195. if lc or uc:
  196. mult = (
  197. lc if lc != None else float("-inf"),
  198. uc if uc != None else float("inf")
  199. )
  200. self.multiplicities[tm_name] = mult
  201. # multiplicities for associations
  202. slc = self.read_attribute(tm_element, "source_lower_cardinality")
  203. suc = self.read_attribute(tm_element, "source_upper_cardinality")
  204. if slc or suc:
  205. mult = (
  206. # slc if slc != None else float("-inf"),
  207. slc if slc != None else 0,
  208. suc if suc != None else float("inf")
  209. )
  210. self.source_multiplicities[tm_name] = mult
  211. tlc = self.read_attribute(tm_element, "target_lower_cardinality")
  212. tuc = self.read_attribute(tm_element, "target_upper_cardinality")
  213. if tlc or tuc:
  214. mult = (
  215. # tlc if tlc != None else float("-inf"),
  216. tlc if tlc != None else 0,
  217. tuc if tuc != None else float("inf")
  218. )
  219. self.target_multiplicities[tm_name] = mult
  220. # optional for attribute links
  221. opt = self.read_attribute(tm_element, "optional")
  222. if opt != None:
  223. self.source_multiplicities[tm_name] = (0, float('inf'))
  224. self.target_multiplicities[tm_name] = (0 if opt else 1, 1)
  225. def get_type(self, element: UUID):
  226. """
  227. Retrieve the type of an element (wrt. current type model)
  228. """
  229. morphisms = self.bottom.read_outgoing_elements(element, "Morphism")
  230. tm_element, = [m for m in morphisms if m in self.type_model_names.keys()]
  231. return tm_element
  232. def check_typing(self):
  233. """
  234. for each element of model check whether a morphism
  235. link exists to some element of type_model
  236. """
  237. errors = []
  238. ref_element, = self.bottom.read_outgoing_elements(self.scd_model, "ModelRef")
  239. model_names = self.bottom.read_keys(self.model)
  240. for m_name in model_names:
  241. m_element, = self.bottom.read_outgoing_elements(self.model, m_name)
  242. try:
  243. tm_element = self.get_type(m_element)
  244. tm_name = self.type_model_names[tm_element]
  245. self.type_mapping[m_name] = tm_name
  246. if ref_element in self.bottom.read_outgoing_elements(tm_element, "Morphism"):
  247. sub_m = UUID(self.bottom.read_value(m_element))
  248. sub_tm = UUID(self.bottom.read_value(tm_element))
  249. nested_errors = Conformance(self.state, sub_m, sub_tm).check_nominal()
  250. errors += [f"In ModelRef ({m_name}):" + err for err in nested_errors]
  251. except ValueError as e:
  252. import traceback
  253. traceback.format_exc(e)
  254. # no or too many morphism links found
  255. errors.append(f"Incorrectly typed element: '{m_name}'")
  256. return errors
  257. def check_link_typing(self):
  258. """
  259. for each link, check whether its source and target are of a valid type
  260. """
  261. errors = []
  262. self.precompute_sub_types()
  263. for m_name, tm_name in self.type_mapping.items():
  264. m_element, = self.bottom.read_outgoing_elements(self.model, m_name)
  265. m_source = self.bottom.read_edge_source(m_element)
  266. m_target = self.bottom.read_edge_target(m_element)
  267. if m_source == None or m_target == None:
  268. # element is not a link
  269. continue
  270. tm_element, = self.bottom.read_outgoing_elements(self.type_model, tm_name)
  271. tm_source = self.bottom.read_edge_source(tm_element)
  272. tm_target = self.bottom.read_edge_target(tm_element)
  273. # check if source is typed correctly
  274. source_name = self.model_names[m_source]
  275. source_type_actual = self.type_mapping[source_name]
  276. source_type_expected = self.type_model_names[tm_source]
  277. if source_type_actual != source_type_expected:
  278. if source_type_actual not in self.sub_types[source_type_expected]:
  279. errors.append(f"Invalid source type '{source_type_actual}' for element '{m_name}'")
  280. # check if target is typed correctly
  281. target_name = self.model_names[m_target]
  282. target_type_actual = self.type_mapping[target_name]
  283. target_type_expected = self.type_model_names[tm_target]
  284. if target_type_actual != target_type_expected:
  285. if target_type_actual not in self.sub_types[target_type_expected]:
  286. errors.append(f"Invalid target type '{target_type_actual}' for element '{m_name}'")
  287. return errors
  288. def check_multiplicities(self):
  289. """
  290. Check whether multiplicities for all types are respected
  291. """
  292. self.deref_primitive_values()
  293. self.precompute_multiplicities()
  294. errors = []
  295. for tm_name in self.type_model_names.values():
  296. # abstract classes
  297. if tm_name in self.abstract_types:
  298. type_count = list(self.type_mapping.values()).count(tm_name)
  299. if type_count > 0:
  300. errors.append(f"Invalid instantiation of abstract class: '{tm_name}'")
  301. # class multiplicities
  302. if tm_name in self.multiplicities:
  303. lc, uc = self.multiplicities[tm_name]
  304. type_count = list(self.type_mapping.values()).count(tm_name)
  305. for sub_type in self.sub_types[tm_name]:
  306. type_count += list(self.type_mapping.values()).count(sub_type)
  307. if type_count < lc or type_count > uc:
  308. errors.append(f"Cardinality of type exceeds valid multiplicity range: '{tm_name}' ({type_count})")
  309. # association source multiplicities
  310. if tm_name in self.source_multiplicities:
  311. tm_element, = self.bottom.read_outgoing_elements(self.type_model, tm_name)
  312. tm_tgt_element = self.bottom.read_edge_target(tm_element)
  313. tm_tgt_name = self.type_model_names[tm_tgt_element]
  314. lc, uc = self.source_multiplicities[tm_name]
  315. for tgt_obj_name, t in self.type_mapping.items():
  316. if t == tm_tgt_name or t in self.sub_types[tm_tgt_name]:
  317. count = 0
  318. tgt_obj_node, = self.bottom.read_outgoing_elements(self.model, tgt_obj_name)
  319. incoming = self.bottom.read_incoming_edges(tgt_obj_node)
  320. for i in incoming:
  321. try:
  322. if self.type_mapping[self.model_names[i]] == tm_name:
  323. count += 1
  324. except KeyError:
  325. pass # for elements not part of model, e.g. morphism links
  326. if count < lc or count > uc:
  327. errors.append(f"Source cardinality of type '{tm_name}' ({count}) out of bounds ({lc}..{uc}) in '{tgt_obj_name}'.")
  328. # association target multiplicities
  329. if tm_name in self.target_multiplicities:
  330. tm_element, = self.bottom.read_outgoing_elements(self.type_model, tm_name)
  331. # tm_target_element = self.bottom.read_edge_target(tm_element)
  332. tm_src_element = self.bottom.read_edge_source(tm_element)
  333. tm_src_name = self.type_model_names[tm_src_element]
  334. lc, uc = self.target_multiplicities[tm_name]
  335. # print("checking assoc", tm_name, "source", tm_src_name)
  336. # print("subtypes of", tm_src_name, self.sub_types[tm_src_name])
  337. for src_obj_name, t in self.type_mapping.items():
  338. if t == tm_src_name or t in self.sub_types[tm_src_name]:
  339. # print("got obj", src_obj_name, "of type", t)
  340. count = 0
  341. src_obj_node, = self.bottom.read_outgoing_elements(self.model, src_obj_name)
  342. # outgoing = self.bottom.read_incoming_edges(src_obj_node)
  343. outgoing = self.bottom.read_outgoing_edges(src_obj_node)
  344. for o in outgoing:
  345. try:
  346. if self.type_mapping[self.model_names[o]] == tm_name:
  347. # print("have an outgoing edge", self.model_names[o], self.type_mapping[self.model_names[o]], "---> increase counter")
  348. count += 1
  349. except KeyError:
  350. pass # for elements not part of model, e.g. morphism links
  351. if count < lc or count > uc:
  352. errors.append(f"Target cardinality of type '{tm_name}' ({count}) out of bounds ({lc}..{uc}) in '{src_obj_name}'.")
  353. # else:
  354. # print(f"OK: Target cardinality of type {tm_name} ({count}) within bounds ({lc}..{uc}) in {src_obj_name}.")
  355. return errors
  356. def evaluate_constraint(self, code, **kwargs):
  357. """
  358. Evaluate constraint code (Python code)
  359. """
  360. funcs = {
  361. 'read_value': self.state.read_value,
  362. 'get_value': self.odapi.get_value,
  363. 'get_target': self.odapi.get_target,
  364. 'get_source': self.odapi.get_source,
  365. 'get_slot': self.odapi.get_slot,
  366. 'get_slot_value': self.odapi.get_slot_value,
  367. 'get_all_instances': self.odapi.get_all_instances,
  368. 'get_name': self.odapi.get_name,
  369. 'get_type_name': self.odapi.get_type_name,
  370. 'get_outgoing': self.odapi.get_outgoing,
  371. 'get_incoming': self.odapi.get_incoming,
  372. }
  373. # print("evaluating constraint ...", code)
  374. loc = {**kwargs, }
  375. result = exec_then_eval(
  376. code,
  377. {'__builtins__': {'isinstance': isinstance, 'print': print,
  378. 'int': int, 'float': float, 'bool': bool, 'str': str, 'tuple': tuple, 'len': len, 'set': set, 'dict': dict},
  379. **funcs
  380. }, # globals
  381. loc # locals
  382. )
  383. return result
  384. def check_constraints(self):
  385. """
  386. Check whether all constraints defined for a model are respected
  387. """
  388. errors = []
  389. def get_code(tm_name):
  390. constraints = self.bottom.read_outgoing_elements(self.type_model, f"{tm_name}.constraint")
  391. if len(constraints) == 1:
  392. constraint = constraints[0]
  393. code = ActionCode(UUID(self.bottom.read_value(constraint)), self.bottom.state).read()
  394. return code
  395. def check_result(result, description):
  396. if result == None:
  397. return # OK
  398. if isinstance(result, str):
  399. errors.append(f"{description} not satisfied. Reason: {result}")
  400. elif isinstance(result, bool):
  401. if not result:
  402. errors.append(f"{description} not satisfied.")
  403. elif isinstance(result, list):
  404. if len(result) > 0:
  405. reasons = indent('\n'.join(result), 4)
  406. errors.append(f"{description} not satisfied. Reasons:\n{reasons}")
  407. else:
  408. raise Exception(f"{description} evaluation result should be boolean or string! Instead got {result}")
  409. # local constraints
  410. for type_name in self.bottom.read_keys(self.type_model):
  411. code = get_code(type_name)
  412. if code != None:
  413. instances = self.odapi.get_all_instances(type_name, include_subtypes=self.constraint_check_subtypes)
  414. for obj_name, obj_id in instances:
  415. description = f"Local constraint of \"{type_name}\" in \"{obj_name}\""
  416. # print(description)
  417. try:
  418. result = self.evaluate_constraint(code, this=obj_id)
  419. except:
  420. errors.append(f"Runtime error during evaluation of {description}:\n{indent(traceback.format_exc(), 6)}")
  421. # raise Exception(f"Context of above error = {description}") from e
  422. check_result(result, description)
  423. # global constraints
  424. glob_constraints = []
  425. # find global constraints...
  426. glob_constraint_type, = self.bottom.read_outgoing_elements(self.scd_model, "GlobalConstraint")
  427. for tm_name in self.bottom.read_keys(self.type_model):
  428. tm_node, = self.bottom.read_outgoing_elements(self.type_model, tm_name)
  429. # print(key, node)
  430. for type_of_node in self.bottom.read_outgoing_elements(tm_node, "Morphism"):
  431. if type_of_node == glob_constraint_type:
  432. # node is GlobalConstraint
  433. glob_constraints.append(tm_name)
  434. # evaluate them (each constraint once)
  435. for tm_name in glob_constraints:
  436. code = get_code(tm_name)
  437. if code != None:
  438. description = f"Global constraint \"{tm_name}\""
  439. try:
  440. result = self.evaluate_constraint(code, model=self.model)
  441. except:
  442. errors.append(f"Runtime error during evaluation of {description}:\n{indent(traceback.format_exc(), 6)}")
  443. check_result(result, description)
  444. return errors
  445. def precompute_structures(self):
  446. """
  447. Make an internal representation of type structures such that comparing type structures is easier
  448. """
  449. self.precompute_sub_types()
  450. scd_elements = self.bottom.read_outgoing_elements(self.scd_model)
  451. # collect types
  452. class_element, = self.bottom.read_outgoing_elements(self.scd_model, "Class")
  453. association_element, = self.bottom.read_outgoing_elements(self.scd_model, "Association")
  454. for tm_element, tm_name in self.type_model_names.items():
  455. # retrieve elements that tm_element is a morphism of
  456. morphisms = self.bottom.read_outgoing_elements(tm_element, "Morphism")
  457. morphism, = [m for m in morphisms if m in scd_elements]
  458. # check if tm_element is a morphism of AttributeLink
  459. if class_element == morphism or association_element == morphism:
  460. self.structures[tm_name] = set()
  461. # collect type structures
  462. # retrieve AttributeLink to check whether element is a morphism of AttributeLink
  463. attr_link_element, = self.bottom.read_outgoing_elements(self.scd_model, "AttributeLink")
  464. for tm_element, tm_name in self.type_model_names.items():
  465. # retrieve elements that tm_element is a morphism of
  466. morphisms = self.bottom.read_outgoing_elements(tm_element, "Morphism")
  467. morphism, = [m for m in morphisms if m in scd_elements]
  468. # check if tm_element is a morphism of AttributeLink
  469. if attr_link_element == morphism:
  470. # retrieve attributes of attribute link, i.e. 'name' and 'optional'
  471. attrs = self.bottom.read_outgoing_elements(tm_element)
  472. name_model_node, = filter(lambda x: self.type_model_names.get(x, "").endswith(".name"), attrs)
  473. opt_model_node, = filter(lambda x: self.type_model_names.get(x, "").endswith(".optional"), attrs)
  474. # get attr name value
  475. name_model = UUID(self.bottom.read_value(name_model_node))
  476. name_node, = self.bottom.read_outgoing_elements(name_model)
  477. name = self.bottom.read_value(name_node)
  478. # get attr opt value
  479. opt_model = UUID(self.bottom.read_value(opt_model_node))
  480. opt_node, = self.bottom.read_outgoing_elements(opt_model)
  481. opt = self.bottom.read_value(opt_node)
  482. # get attr type name
  483. source_type_node = self.bottom.read_edge_source(tm_element)
  484. source_type_name = self.type_model_names[source_type_node]
  485. target_type_node = self.bottom.read_edge_target(tm_element)
  486. target_type_name = self.type_model_names[target_type_node]
  487. # add attribute to the structure of its source type
  488. # attribute is stored as a (name, optional, type) triple
  489. self.structures.setdefault(source_type_name, set()).add((name, opt, target_type_name))
  490. # extend structures of sub types with attrs of super types
  491. for super_type, sub_types in self.sub_types.items():
  492. for sub_type in sub_types:
  493. self.structures.setdefault(sub_type, set()).update(self.structures[super_type])
  494. # filter out abstract types, as they cannot be instantiated
  495. # retrieve Class_abstract to check whether element is a morphism of Class_abstract
  496. class_abs_element, = self.bottom.read_outgoing_elements(self.scd_model, "Class_abstract")
  497. for tm_element, tm_name in self.type_model_names.items():
  498. # retrieve elements that tm_element is a morphism of
  499. morphisms = self.bottom.read_outgoing_elements(tm_element, "Morphism")
  500. morphism, = [m for m in morphisms if m in scd_elements]
  501. # check if tm_element is a morphism of Class_abstract
  502. if class_abs_element == morphism:
  503. # retrieve 'abstract' attribute value
  504. target_node = self.bottom.read_edge_target(tm_element)
  505. abst_model = UUID(self.bottom.read_value(target_node))
  506. abst_node, = self.bottom.read_outgoing_elements(abst_model)
  507. is_abstract = self.bottom.read_value(abst_node)
  508. # retrieve type name
  509. source_node = self.bottom.read_edge_source(tm_element)
  510. type_name = self.type_model_names[source_node]
  511. if is_abstract:
  512. self.structures.pop(type_name)
  513. def match_structures(self):
  514. """
  515. Try to match the structure of each element in the instance model to some element in the type model
  516. """
  517. ref_element, = self.bottom.read_outgoing_elements(self.scd_model, "ModelRef")
  518. # matching
  519. for m_element, m_name in self.model_names.items():
  520. is_edge = self.bottom.read_edge_source(m_element) != None
  521. print('element:', m_element, 'name:', m_name, 'is_edge', is_edge)
  522. for type_name, structure in self.structures.items():
  523. tm_element, = self.bottom.read_outgoing_elements(self.type_model, type_name)
  524. type_is_edge = self.bottom.read_edge_source(tm_element) != None
  525. if is_edge == type_is_edge:
  526. print(' type_name:', type_name, 'type_is_edge:', type_is_edge, "structure:", structure)
  527. mismatch = False
  528. matched = 0
  529. for name, optional, attr_type in structure:
  530. print(' name:', name, "optional:", optional, "attr_type:", attr_type)
  531. try:
  532. attr, = self.bottom.read_outgoing_elements(self.model, f"{m_name}.{name}")
  533. attr_tm, = self.bottom.read_outgoing_elements(self.type_model, attr_type)
  534. # if attribute is a modelref, we need to check whether it
  535. # linguistically conforms to the specified type
  536. # if its an internally defined attribute, this will be checked by constraints
  537. morphisms = self.bottom.read_outgoing_elements(attr_tm, "Morphism")
  538. attr_conforms = True
  539. if ref_element in morphisms:
  540. # check conformance of reference model
  541. type_model_uuid = UUID(self.bottom.read_value(attr_tm))
  542. model_uuid = UUID(self.bottom.read_value(attr))
  543. attr_conforms = Conformance(self.state, model_uuid, type_model_uuid)\
  544. .check_nominal()
  545. else:
  546. # eval constraints
  547. code = self.read_attribute(attr_tm, "constraint")
  548. if code != None:
  549. attr_conforms = self.evaluate_constraint(code, this=attr)
  550. if attr_conforms:
  551. matched += 1
  552. print(" attr_conforms -> matched:", matched)
  553. except ValueError as e:
  554. # attr not found or failed parsing UUID
  555. if optional:
  556. print(" skipping:", e)
  557. continue
  558. else:
  559. # did not match mandatory attribute
  560. print(" breaking:", e)
  561. mismatch = True
  562. break
  563. print(' matched:', matched, 'len(structure):', len(structure))
  564. # if matched == len(structure):
  565. if not mismatch:
  566. print(' add to candidates:', m_name, type_name)
  567. self.candidates.setdefault(m_name, set()).add(type_name)
  568. # filter out candidates for links based on source and target types
  569. for m_element, m_name in self.model_names.items():
  570. is_edge = self.bottom.read_edge_source(m_element) != None
  571. if is_edge and m_name in self.candidates:
  572. m_source = self.bottom.read_edge_source(m_element)
  573. m_target = self.bottom.read_edge_target(m_element)
  574. print(self.candidates)
  575. source_candidates = self.candidates[self.model_names[m_source]]
  576. target_candidates = self.candidates[self.model_names[m_target]]
  577. remove = set()
  578. for candidate_name in self.candidates[m_name]:
  579. candidate_element, = self.bottom.read_outgoing_elements(self.type_model, candidate_name)
  580. candidate_source = self.type_model_names[self.bottom.read_edge_source(candidate_element)]
  581. if candidate_source not in source_candidates:
  582. if len(source_candidates.intersection(set(self.sub_types[candidate_source]))) == 0:
  583. remove.add(candidate_name)
  584. candidate_target = self.type_model_names[self.bottom.read_edge_target(candidate_element)]
  585. if candidate_target not in target_candidates:
  586. if len(target_candidates.intersection(set(self.sub_types[candidate_target]))) == 0:
  587. remove.add(candidate_name)
  588. self.candidates[m_name] = self.candidates[m_name].difference(remove)
  589. def build_morphisms(self):
  590. """
  591. Build the morphisms between an instance and a type model that structurally match
  592. """
  593. if not all([len(c) == 1 for c in self.candidates.values()]):
  594. raise RuntimeError("Cannot build incomplete or ambiguous morphism.")
  595. mapping = {k: v.pop() for k, v in self.candidates.items()}
  596. for m_name, tm_name in mapping.items():
  597. # morphism to class/assoc
  598. m_element, = self.bottom.read_outgoing_elements(self.model, m_name)
  599. tm_element, = self.bottom.read_outgoing_elements(self.type_model, tm_name)
  600. self.bottom.create_edge(m_element, tm_element, "Morphism")
  601. # morphism for attributes and attribute links
  602. structure = self.structures[tm_name]
  603. for attr_name, _, attr_type in structure:
  604. try:
  605. # attribute node
  606. attr_element, = self.bottom.read_outgoing_elements(self.model, f"{m_name}.{attr_name}")
  607. attr_type_element, = self.bottom.read_outgoing_elements(self.type_model, attr_type)
  608. self.bottom.create_edge(attr_element, attr_type_element, "Morphism")
  609. # attribute link
  610. attr_link_element, = self.bottom.read_outgoing_elements(self.model, f"{m_name}_{attr_name}")
  611. attr_link_type_element, = self.bottom.read_outgoing_elements(self.type_model, f"{tm_name}_{attr_name}")
  612. self.bottom.create_edge(attr_link_element, attr_link_type_element, "Morphism")
  613. except ValueError:
  614. pass
  615. if __name__ == '__main__':
  616. from state.devstate import DevState as State
  617. s = State()
  618. from bootstrap.scd import bootstrap_scd
  619. scd = bootstrap_scd(s)
  620. from bootstrap.pn import bootstrap_pn
  621. ltm_pn = bootstrap_pn(s, "PN")
  622. ltm_pn_lola = bootstrap_pn(s, "PNlola")
  623. from services.pn import PN
  624. my_pn = s.create_node()
  625. PNserv = PN(my_pn, s)
  626. PNserv.create_place("p1", 5)
  627. PNserv.create_place("p2", 0)
  628. PNserv.create_transition("t1")
  629. PNserv.create_p2t("p1", "t1", 1)
  630. PNserv.create_t2p("t1", "p2", 1)
  631. cf = Conformance(s, my_pn, ltm_pn_lola)
  632. # cf = Conformance(s, scd, ltm_pn, scd)
  633. cf.precompute_structures()
  634. cf.match_structures()
  635. cf.build_morphisms()
  636. print(cf.check_nominal())