conformance.py 33 KB

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