himesis.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802
  1. # Copyright 2023 Modelling, Simulation and Design Lab (MSDL)
  2. # at the University of Antwerp (http://msdl.uantwerpen.be/).
  3. #
  4. # Licensed under the GNU Public License v3 (the "License");
  5. # you may not use this file except in compliance with the
  6. # License. You may obtain a copy of the License at
  7. # https://www.gnu.org/licenses/gpl-3.0.en.html
  8. #
  9. # Unless required by applicable law or agreed to in writing,
  10. # software distributed under the License is distributed on an
  11. # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
  12. # either express or implied. See the License for the specific
  13. # language governing permissions and limitations under the
  14. # License.
  15. """
  16. Core logic for Himesis. Based on the code in AToMPM and earlier work by Marc Provost.
  17. Himesis is a hierarchical, directed and labelled graph kernel, built on top of the ModelVerse State.
  18. The name Himesis has etymological roots from genesis for "origin", mimesis for "representation" and
  19. the syllable "Hi" stands for "Hierarchical".
  20. .. See Also:
  21. http://modelverse.uantwerpen.be/people/mprovost/projects/himesis/index.html
  22. """
  23. import uuid, copy
  24. from pytcore.state.base import State
  25. class HConstants:
  26. """
  27. Himesis constants must start with '$' to ensure there are no name clashes
  28. with user-attributes (which are prohibited from starting with '$')
  29. """
  30. GUID = '$GUID__'
  31. METAMODELS = '$mms__'
  32. MISSING_METAMODELS = '$missing_mms__'
  33. FULLTYPE = '$ft__'
  34. CONNECTOR_TYPE = '$ct__'
  35. ATTRIBUTES = "$attr__"
  36. MT_LABEL = '$MT_label__'
  37. MT_CONSTRAINT = '$MT_constraint__'
  38. MT_ACTION = '$MT_action__'
  39. MT_SUBTYPE_MATCH = '$MT_subtypeMatching__'
  40. MT_SUBTYPES = '$MT_subtypes__'
  41. MT_DIRTY = '$MT_dirty__'
  42. MT_PIVOT_IN = '$MT_pivotIn__'
  43. MT_PIVOT_OUT = '$MT_pivotOut__'
  44. class Himesis:
  45. """
  46. Creates a typed, attributed, directed, hierarchical, multi-graph.
  47. Args:
  48. name (str): The name of this graph.
  49. mvs (State): The backend to use for the graph representations.
  50. """
  51. Constants = HConstants
  52. EDGE_LIST_THRESHOLD = 10**3
  53. def __init__(self, name, mvs):
  54. if not name:
  55. name = self.__class__.__name__
  56. self.name = name
  57. self.state = mvs
  58. self.attrib = {
  59. Himesis.Constants.GUID: self.state.new_id(),
  60. Himesis.Constants.METAMODELS: [],
  61. Himesis.Constants.MISSING_METAMODELS: lambda: []
  62. }
  63. self.vcount = 0
  64. self.attrs = set()
  65. self.match_sets = []
  66. # mmTypeData: enables add_node() to properly initialize to-be nodes s.t. they reflect the default values specified by their metamodels
  67. # _index2guid: a fast lookup of the node's guid by its index
  68. # session: area which provides a clean and efficient way to remember information across rules
  69. self.mmTypeData = {}
  70. self._index2guid = {}
  71. self.session = {}
  72. @staticmethod
  73. def is_RAM_attribute(attr_name):
  74. return not attr_name.startswith('$')
  75. def copy(self):
  76. mvs = copy.deepcopy(self.state)
  77. cpy = Himesis(self.name, mvs)
  78. cpy._index2guid = copy.deepcopy(self._index2guid)
  79. ''' hergin :: motif-integration FIX for mmTypeData bug '''
  80. cpy.mmTypeData = copy.deepcopy(self.mmTypeData)
  81. cpy.session = copy.deepcopy(self.session)
  82. cpy.name = copy.deepcopy(self.name)
  83. return cpy
  84. def __copy__(self):
  85. return self.copy()
  86. def __deepcopy__(self, memo):
  87. return self.__copy__()
  88. def __getitem__(self, item):
  89. return self.attrib[item]
  90. def __setitem__(self, key, value):
  91. self.attrib[key] = value
  92. # def __str__(self):
  93. # s = super(Himesis, self).__str__()
  94. # return self.name + ' ' + s[s.index('('):] + ' ' + str(self[Himesis.Constants.GUID])
  95. def get_id(self):
  96. """
  97. Returns the unique identifier of the graph
  98. """
  99. return self[Himesis.Constants.GUID]
  100. def vertex_count(self):
  101. return len(self._index2guid)
  102. def edge_count(self):
  103. return len(self.edge_iter())
  104. def node_iter(self):
  105. """
  106. Iterates over the nodes in the graph, by index
  107. """
  108. return range(self.vertex_count())
  109. def node_guid_iter(self):
  110. """
  111. Iterates over the nodes in the graph, by guid index
  112. """
  113. return (self.get_node(ix) for ix in self.node_iter())
  114. def edge_iter(self):
  115. """
  116. Iterates over the edges in the graph, by index
  117. """
  118. res = []
  119. for node in self.node_guid_iter():
  120. res.extend(self.state.read_outgoing(node))
  121. res.extend(self.state.read_incoming(node))
  122. return list(set([e for e in res if self.edge_get_label(e) != self.Constants.ATTRIBUTES]))
  123. def attr_iter(self):
  124. return self.attrs
  125. def follow_edge(self, node, label):
  126. return self.state.read_dict(node, label)
  127. def node_set_attribute(self, node, key, value):
  128. attrs = [self.state.read_value(v) for v in self.state.read_dict_keys(node)]
  129. if Himesis.Constants.ATTRIBUTES not in attrs:
  130. attr = self.state.create_node()
  131. self.state.create_dict(node, Himesis.Constants.ATTRIBUTES, attr)
  132. else:
  133. attr = self.follow_edge(node, Himesis.Constants.ATTRIBUTES)
  134. attrs = [self.state.read_value(v) for v in self.state.read_dict_keys(attr)]
  135. if key in attrs:
  136. target = self.follow_edge(attr, key)
  137. self.state.delete_node(target)
  138. target = self.state.create_nodevalue(value)
  139. self.state.create_dict(attr, key, target)
  140. self.attrs.add(key)
  141. def node_get_attribute(self, node, key):
  142. attrs = [self.state.read_value(v) for v in self.state.read_dict_keys(node)]
  143. if Himesis.Constants.ATTRIBUTES not in attrs:
  144. return None
  145. attr = self.follow_edge(node, Himesis.Constants.ATTRIBUTES)
  146. attrs = [self.state.read_value(v) for v in self.state.read_dict_keys(attr)]
  147. if key in attrs:
  148. target = self.follow_edge(attr, key)
  149. return self.state.read_value(target)
  150. return None
  151. def node_get_attributes(self, node):
  152. attrs = [self.state.read_value(v) for v in self.state.read_dict_keys(node)]
  153. if Himesis.Constants.ATTRIBUTES not in attrs:
  154. return {}
  155. attr = self.follow_edge(node, Himesis.Constants.ATTRIBUTES)
  156. res = {}
  157. attrs = [self.state.read_value(v) for v in self.state.read_dict_keys(attr)]
  158. for key in attrs:
  159. target = self.follow_edge(attr, key)
  160. res[key] = self.state.read_value(target)
  161. return res
  162. def node_has_attribute(self, node, key):
  163. attr = self.node_get_attribute(node, key)
  164. return attr is not None
  165. def get_first_node_with_attribute_equals(self, key, value):
  166. for node in self.node_guid_iter():
  167. attr = self.node_get_attribute(node, key)
  168. if attr == value:
  169. return node
  170. return None
  171. def add_node(self, fulltype=None, isConnector=None):
  172. # ALL NODES ARE NOW IDENTIFIED WITH A UUID!
  173. # newNodeIndex = self.vertex_count()
  174. # if newNodeGuid is None:
  175. # newNodeGuid = uuid.uuid4()
  176. nid = self.state.create_node()
  177. # self.node_set_attribute(nid, Himesis.Constants.GUID, newNodeGuid)
  178. self.node_set_attribute(nid, Himesis.Constants.FULLTYPE, fulltype)
  179. self.node_set_attribute(nid, Himesis.Constants.CONNECTOR_TYPE, isConnector)
  180. # self.add_vertices(1)
  181. # self.vs[newNodeIndex][Himesis.Constants.GUID] = newNodeGuid
  182. # self.vs[newNodeIndex][Himesis.Constants.FULLTYPE] = fulltype
  183. # self.vs[newNodeIndex][Himesis.Constants.CONNECTOR_TYPE] = isConnector
  184. if fulltype in self.mmTypeData :
  185. for attr, val in self.mmTypeData[fulltype].items():
  186. self.node_set_attribute(nid, str(attr), val)
  187. # self.vs[newNodeIndex][str(attr)] = val
  188. self._index2guid[self.vcount] = nid
  189. self.vcount += 1
  190. return nid
  191. def delete_nodes(self, nodes):
  192. td = []
  193. for n in nodes:
  194. self.state.delete_node(n)
  195. td += [k for k, v in self._index2guid.items() if v == n]
  196. # self.delete_vertices(nodes)
  197. # Regenerate the lookup because node indices have changed
  198. for t in td:
  199. del self._index2guid[t]
  200. # self._guid2index = dict((self.vs[node][Himesis.Constants.GUID], node) for node in self.node_iter())
  201. def get_node(self, index):
  202. if index in self._index2guid:
  203. return self._index2guid[index]
  204. raise KeyError('Node not found with specified id. Make sure to only create nodes via Himesis.add_node().')
  205. def edge_get_source(self, edge):
  206. return self.state.read_edge(edge)[0]
  207. def edge_get_target(self, edge):
  208. return self.state.read_edge(edge)[1]
  209. def edge_get_label(self, edge):
  210. outs = (self.state.read_edge(e) for e in self.state.read_outgoing(edge))
  211. res = [self.state.read_value(t) for _, t in outs]
  212. if len(res) == 0:
  213. return None
  214. return res[0]
  215. def get_edge(self, edge):
  216. return self.state.read_edge(edge)
  217. def link_nodes(self, A, B, label=None):
  218. if label is None:
  219. self.state.create_edge(A, B)
  220. else:
  221. self.state.create_dict(A, label, B)
  222. def unlink_nodes(self, A, B, label=""):
  223. if self.state.read_reverse_dict(B, label) != A:
  224. raise ValueError("No connection with label '%s' found between nodes %s and %s" % (label, A, B))
  225. edge = self.state.read_dict_edge(A, label)
  226. self.state.delete_edge(edge)
  227. def predecessors(self, node):
  228. return [self.state.read_edge(e)[0] for e in self.state.read_incoming(node)]
  229. def successors(self, node):
  230. return [self.state.read_edge(e)[1] for e in self.state.read_outgoing(node)]
  231. # def get_node(self, guid):
  232. # """
  233. # Retrieves the node instance with the specified guid
  234. # @param guid: The guid of the node.
  235. # """
  236. # if guid in self._guid2index:
  237. # if self._guid2index[guid] >= self.vcount() or \
  238. # self.vs[self._guid2index[guid]][Himesis.Constants.GUID] != guid :
  239. # self._guid2index = dict((self.vs[node][Himesis.Constants.GUID], node) for node in self.node_iter())
  240. # try:
  241. # return self._guid2index[guid]
  242. # except KeyError:
  243. # #TODO: This should be a TransformationLanguageSpecificException
  244. # raise KeyError('Invalid node id. Make sure to only delete nodes via Himesis.delete_nodes(): ' + str(guid))
  245. # else :
  246. # #TODO: This should be a TransformationLanguageSpecificException
  247. # raise KeyError('Node not found with specified id. Make sure to only create nodes via Himesis.add_node(): ' + str(guid))
  248. # def draw(self, visual_style={}, label=None, show_guid=False, show_id=False, debug=False, width=600, height=900):
  249. # """
  250. # Visual graphic rendering of the graph.
  251. #
  252. # Args:
  253. # @param label: The attribute to use as node label in the figure.
  254. # If not provided, the index of the node is used.
  255. # @param visual_style: More drawing options
  256. # (see http://igraph.sourceforge.net/doc/python/igraph.Graph-class.html#__plot__ for more details).
  257. # """
  258. # if 'layout' not in visual_style:
  259. # visual_style["layout"] = 'fr'
  260. # if 'margin' not in visual_style:
  261. # visual_style["margin"] = 10
  262. #
  263. # # Set the labels
  264. # if not label:
  265. # if show_guid:
  266. # visual_style["vertex_label"] = [str(self.vs[i][Himesis.Constants.GUID])[:4] for i in self.node_iter()]
  267. # elif show_id:
  268. # visual_style["vertex_label"] = [str(i) for i in self.node_iter()]
  269. # else:
  270. # visual_style["vertex_label"] = [''] * self.vcount()
  271. # else:
  272. # try:
  273. # visual_style["vertex_label"] = self.vs[label]
  274. # for n in self.node_iter():
  275. # if not visual_style["vertex_label"][n]:
  276. # visual_style["vertex_label"][n] = self.vs[n][Himesis.Constants.FULLTYPE]
  277. # if debug:
  278. # visual_style["vertex_label"][n] = str(n) + ':' + visual_style["vertex_label"][n]
  279. # elif debug:
  280. # visual_style["vertex_label"][n] = str(n) + ':' + visual_style["vertex_label"][n]
  281. # except:
  282. # raise Exception('%s is not a valid attribute' % label)
  283. #
  284. # return ig.plot(self, bbox=(0, 0, width, height), **visual_style)
  285. def execute(self, *args):
  286. raise AttributeError('This method is not implemented')
  287. class HimesisPattern(Himesis):
  288. def __init__(self, name, mvs):
  289. super(HimesisPattern, self).__init__(name, mvs)
  290. # Caches
  291. self.nodes_label = {}
  292. self.nodes_pivot_out = {}
  293. def get_node_with_label(self, label):
  294. """
  295. Retrieves the index of the node with the specified label.
  296. Args:
  297. label: The label of the node.
  298. """
  299. if not self.nodes_label:
  300. self.nodes_label = {}
  301. self.nodes_label = { self.node_get_attribute(n, Himesis.Constants.MT_LABEL): n \
  302. for n in self.node_guid_iter() \
  303. if self.node_has_attribute(n, Himesis.Constants.MT_LABEL) }
  304. # self.nodes_label = dict([(self.vs[i][Himesis.Constants.MT_LABEL], i) for i in self.node_iter()])
  305. if label in self.nodes_label:
  306. return self.nodes_label[label]
  307. def get_pivot_out(self, pivot):
  308. """
  309. Retrieves the index of the pivot node.
  310. Args:
  311. pivot: The label of the pivot.
  312. """
  313. if not self.nodes_pivot_out:
  314. self.nodes_pivot_out = { self.node_get_attribute(n, Himesis.Constants.MT_PIVOT_OUT): n \
  315. for n in self.node_guid_iter() \
  316. if self.node_has_attribute(n, Himesis.Constants.MT_PIVOT_OUT) }
  317. # self.nodes_pivot_out = dict([(i, self.vs[i][Himesis.Constants.MT_PIVOT_OUT]) for i in self.node_iter()])
  318. if pivot in self.nodes_pivot_out:
  319. return self.nodes_pivot_out[pivot]
  320. class HimesisPreConditionPattern(HimesisPattern):
  321. def __init__(self, name, mvs):
  322. super(HimesisPreConditionPattern, self).__init__(name, mvs)
  323. self.nodes_pivot_in = {}
  324. def get_pivot_in(self, pivot):
  325. """
  326. Retrieves the index of the pivot node.
  327. Args:
  328. pivot: The label of the pivot.
  329. """
  330. if not self.nodes_pivot_in:
  331. self.nodes_pivot_in = { self.node_get_attribute(n, Himesis.Constants.MT_PIVOT_IN): n \
  332. for n in self.node_guid_iter() \
  333. if self.node_has_attribute(n, Himesis.Constants.MT_PIVOT_IN) }
  334. # self.nodes_pivot_in = dict([(self.vs[i][Himesis.Constants.MT_PIVOT_IN], i) for i in self.node_iter()])
  335. if pivot in self.nodes_pivot_in:
  336. return self.nodes_pivot_in[pivot]
  337. def constraint(self, mtLabel2graphIndexMap, graph):
  338. """
  339. If a constraint shall be specified, the corresponding Himesis graph must override this method.
  340. The condition must be specified in the pattern graph and not the input graph.
  341. By default, the constraint evaluates to True.
  342. @param PreMatch: The current match, before the rewriting.
  343. @param graph: The whole input graph.
  344. """
  345. raise NotImplementedError('Use graph[Himesis.Constants.MT_CONSTRAINT]() instead')
  346. class HimesisPreConditionPatternLHS(HimesisPreConditionPattern):
  347. def __init__(self, name, mvs):
  348. super(HimesisPreConditionPatternLHS, self).__init__(name, mvs)
  349. self.NACs = []
  350. self.bound_start_index = 0 # index of first bound NAC in NACs list
  351. def addNAC(self, nac):
  352. """
  353. Appends the NAC to this LHS pattern
  354. """
  355. if nac.LHS != self:
  356. nac.LHS = self
  357. if nac.bridge is None:
  358. nac.bridge = nac.compute_bridge()
  359. self.NACs.append(nac)
  360. def addNACs(self, NACs):
  361. """
  362. Stores the list of NACs in decreasing order of their size
  363. @param nacs: list of NACs
  364. @postcondition: the NACs will be stored in decreasing order of their bridge sizes
  365. """
  366. bound = []
  367. unbound = []
  368. for nac in NACs:
  369. nac.LHS = self
  370. nac.bridge_size = nac.compute_bridge().vertex_count()
  371. if nac.bridge_size > 0:
  372. bound.append(nac)
  373. else:
  374. unbound.append(nac)
  375. bound.sort(key=lambda nac: (nac.bridge_size, nac.vertex_count()), reverse=True)
  376. unbound.sort(key=lambda nac: nac.vertex_count(), reverse=True)
  377. self.NACs = unbound + bound
  378. self.bound_start_index = len(unbound)
  379. def getUnboundNACs(self):
  380. return self.NACs[:self.bound_start_index]
  381. def getBoundNACs(self):
  382. return self.NACs[self.bound_start_index:]
  383. def hasBoundNACs(self):
  384. return self.bound_start_index < len(self.NACs)
  385. class HimesisPreConditionPatternNAC(HimesisPreConditionPattern):
  386. def __init__(self, LHS, name, mvs):
  387. super(HimesisPreConditionPatternNAC, self).__init__(name, mvs)
  388. self.LHS = LHS
  389. self.bridge = None
  390. self.bridge_size = 0
  391. def set_bridge_size(self):
  392. """
  393. Computes the bridge and stores the number of its nodes.
  394. """
  395. if self.LHS is None:
  396. raise Exception('Missing LHS to compute bridge')
  397. self.bridge_size = self.compute_bridge().vertex_count()
  398. def compute_bridge(self):
  399. """
  400. Creates a HimesisPreConditionPattern defined as the intersection of graph with this instance.
  401. This is called the 'bridge'.
  402. From a topological point of view, this method computes the largest common subgraph of these two graphs.
  403. However, the similarity of nodes of the bridge relies on the meta-model type of the nodes.
  404. Furthermore, every attribute value is the conjunction of the constraints defined in each graph.
  405. """
  406. # G1 is the smallest graph and G2 is the bigger graph
  407. G1 = self
  408. G2 = self.LHS
  409. if G1.vertex_count() > G2.vertex_count():
  410. # Swap
  411. G1, G2 = G2, G1
  412. # The bridge
  413. G = HimesisPreConditionPattern('', self.state) # TODO: Maybe create new state instead?
  414. G[Himesis.Constants.GUID] = uuid.uuid4()
  415. # We don't need to actually solve the largest common subgraph (LCS) problem
  416. # because we assume that the nodes are labelled uniquely in each graph
  417. # and that if a label is in G1 and in G2, then it will be in G
  418. if G1.vertex_count() == 0:
  419. return G
  420. for v1 in G1.node_guid_iter():
  421. label = G1.node_get_attribute(v1, Himesis.Constants.MT_LABEL)
  422. v2 = G2.get_first_node_with_attribute_equals(Himesis.Constants.MT_LABEL, label)
  423. if v2 is None: continue
  424. newNodeIndex = G.add_node()
  425. # Now do a conjunction of the attributes
  426. for attr, val in G1.node_get_attributes(v1).items():
  427. G.node_set_attribute(newNodeIndex, attr, val)
  428. for attr, val in G2.node_get_attributes(v2).items():
  429. if not G.node_has_attribute(newNodeIndex, attr):
  430. G.node_set_attribute(newNodeIndex, attr, val)
  431. # Ignore non-RAM attributes ('special' and HConstants attributes)
  432. elif not Himesis.is_RAM_attribute(attr): continue
  433. # Handle normal attribute
  434. else:
  435. if not val:
  436. # There is no constraint for this attribute
  437. continue
  438. # The attribute constraint code is the conjunction of the LHS constraint
  439. # with the NAC constraint for this attribute
  440. def get_evalAttrConditions(_attr, _v1, _v2):
  441. def evalAttrConditions(mtLabel2graphIndexMap, graph):
  442. return G1.node_get_attribute(_v1, _attr)(mtLabel2graphIndexMap, graph) and \
  443. G2.node_get_attribute(_v2, _attr)(mtLabel2graphIndexMap, graph)
  444. return evalAttrConditions
  445. G.node_set_attribute(newNodeIndex, attr, get_evalAttrConditions(attr, v1, v2))
  446. # G.vs[newNodeIndex][attr] = get_evalAttrConditions(attr, v1.index, v2.index)
  447. # Now add the edges
  448. # We only need to go through the edges of the smaller graph
  449. for e in G1.edge_iter():
  450. src, tgt = self.state.read_edge(e)
  451. src_label = self.node_get_attribute(src, Himesis.Constants.MT_LABEL)
  452. tgt_label = self.node_get_attribute(tgt, Himesis.Constants.MT_LABEL)
  453. src = G.get_first_node_with_attribute_equals(Himesis.Constants.MT_LABEL, src_label)
  454. tgt = G.get_first_node_with_attribute_equals(Himesis.Constants.MT_LABEL, tgt_label)
  455. G.link_nodes(src, tgt)
  456. # Labels2 = G2.vs[Himesis.Constants.MT_LABEL]
  457. # for label in G1.vs[Himesis.Constants.MT_LABEL]:
  458. # if label in Labels2:
  459. # # Get the corresponding node from G1
  460. # v1 = G1.vs.select(lambda v : v[Himesis.Constants.MT_LABEL] == label)
  461. # if len(v1) == 1:
  462. # v1 = v1[0]
  463. # elif len(v1) == 0:
  464. # #unreachable line...
  465. # raise Exception('Label does not exist :: ' + str(label))
  466. # else:
  467. # raise Exception('Label is not unique :: ' + str(label))
  468. # # Get the corresponding node from G2
  469. # v2 = G2.vs.select(lambda v : v[Himesis.Constants.MT_LABEL] == label)
  470. # if len(v2) == 1:
  471. # v2 = v2[0]
  472. # elif len(v2) == 0:
  473. # # Unreachable line...
  474. # raise Exception('Label does not exist :: ' + str(label))
  475. # else:
  476. # raise Exception('Label is not unique :: ' + str(label))
  477. # newNodeIndex = G.add_node()
  478. # # Now do a conjunction of the attributes
  479. # for attr in v1.attribute_names():
  480. # G.vs[newNodeIndex][attr] = v1[attr]
  481. # for attr in v2.attribute_names():
  482. # # The attribute is not in v1
  483. # if attr not in G.vs[newNodeIndex].attribute_names():
  484. # G.vs[newNodeIndex][attr] = v2[attr]
  485. # # Give this node its own GUID attribute
  486. # elif attr == Himesis.Constants.GUID:
  487. # G.vs[newNodeIndex][Himesis.Constants.GUID] = uuid.uuid4()
  488. # continue
  489. # # Ignore non-RAM attributes ('special' and HConstants attributes)
  490. # elif not Himesis.is_RAM_attribute(attr):
  491. # continue
  492. # # Handle normal attribute
  493. # else :
  494. # if not v2[attr]:
  495. # # There is no constraint for this attribute
  496. # continue
  497. #
  498. # # The attribute constraint code is the conjunction of the LHS constraint
  499. # # with the NAC constraint for this attribute
  500. # def get_evalAttrConditions(_attr,_v1,_v2) :
  501. # def evalAttrConditions(mtLabel2graphIndexMap,graph):
  502. # return G1.vs[_v1][_attr](mtLabel2graphIndexMap, graph) and \
  503. # G2.vs[_v2][_attr](mtLabel2graphIndexMap, graph)
  504. # return evalAttrConditions
  505. # G.vs[newNodeIndex][attr] = get_evalAttrConditions(attr,v1.index,v2.index)
  506. # #else: v1[attr] == v2[attr], so we don't need to do anything more
  507. # # Now add the edges
  508. # # We only need to go through the edges of the smaller graph
  509. # for e in G1.edge_iter():
  510. # src_label = G1.vs[G1.es[e].source][Himesis.Constants.MT_LABEL]
  511. # tgt_label = G1.vs[G1.es[e].target][Himesis.Constants.MT_LABEL]
  512. # src = G.vs.select(lambda v : v[Himesis.Constants.MT_LABEL] == src_label)
  513. # tgt = G.vs.select(lambda v : v[Himesis.Constants.MT_LABEL] == tgt_label)
  514. # if len(src) == len(tgt) == 1:
  515. # src = src[0]
  516. # tgt = tgt[0]
  517. # G.add_edges([(src.index, tgt.index)])
  518. # elif len(src) == 0 :
  519. # # raise Exception('Label does not exist :: '+str(src_label))
  520. # pass
  521. # elif len(tgt) == 0 :
  522. # # raise Exception('Label does not exist :: '+str(tgt_label))
  523. # pass
  524. # elif len(src) > 1 :
  525. # raise Exception('Label is not unique :: ' + str(src_label))
  526. # elif len(tgt) > 1 :
  527. # raise Exception('Label is not unique :: ' + str(tgt_label))
  528. return G
  529. class HimesisPostConditionPattern(HimesisPattern):
  530. def __init__(self, name, mvs):
  531. super(HimesisPostConditionPattern, self).__init__(name, mvs)
  532. self.pre = None
  533. def action(self, mtLabel2graphIndexMap, graph):
  534. """
  535. If an action shall be specified, the corresponding Himesis graph must override this method.
  536. The action must be specified in the pattern graph and not the input graph.
  537. """
  538. raise NotImplementedError('Use graph[Himesis.Constants.MT_ACTION]() instead')
  539. # This method implements the rewriting part of the rule.
  540. '''
  541. NOTE
  542. certain rule applications may have side-effects that aren't caused by
  543. the rewriting per se... at present, the only instance of this is when a
  544. rule produces entities of a formalism not loaded on the asworker... in
  545. this case, we prepend appropriate {'op':'LOADMM','name':...} entries to
  546. packet.deltas
  547. NOTE
  548. when creating new nodes, information about the match is bundled so that
  549. the said new nodes' icons get created near the icons of nodes matched
  550. in the LHS
  551. NOTE
  552. deletes must be performed last because they alter igraph indices and
  553. which we use to map __pLabels to source graph nodes... however, to
  554. avoid violating maximum association multiplicities, deletes in the
  555. source model must be performed first... thus, RM* operations, if any,
  556. are placed at the start of packet.deltas
  557. '''
  558. def execute(self, packet, match):
  559. graph = packet.graph
  560. # Changes to packet.graph are logged in packet.deltas
  561. packet.deltas = []
  562. # Init deltas with rule side-effects (see NOTE)
  563. for mm in self[Himesis.Constants.MISSING_METAMODELS]() :
  564. packet.deltas.append({'op':'LOADMM','name':mm})
  565. # Set the attributes of graph.vs[graphNodeIndex] to match those of self.vs[rhsNodeIndex]
  566. def set_attributes(rhsNodeIndex, graphNodeIndex, newNode, pLabel2graphIndexMap) :
  567. changedSomething = False
  568. for attrName, attrVal in self.node_get_attributes(rhsNodeIndex).items():
  569. # for attrName in self.vs[rhsNodeIndex].attribute_names() :
  570. if Himesis.is_RAM_attribute(attrName) :
  571. # attrVal = self.vs[rhsNodeIndex][attrName]
  572. if attrVal is None :
  573. # Not 'really' an attribute
  574. continue
  575. oldVal = None
  576. try :
  577. if not newNode:
  578. # oldVal = graph.vs[graphNodeIndex][attrName]
  579. oldVal = graph.node_get_attribute(graphNodeIndex, attrName)
  580. # newVal = self.vs[rhsNodeIndex][attrName](pLabel2graphIndexMap, graph)
  581. newVal = self.node_get_attribute(rhsNodeIndex, attrName)(pLabel2graphIndexMap, graph)
  582. if oldVal != newVal:
  583. graph.node_set_attribute(graphNodeIndex, attrName, newVal)
  584. # graph.vs[graphNodeIndex][attrName] = newVal
  585. packet.deltas.append(
  586. {'op':'CHATTR',
  587. 'guid':graphNodeIndex,
  588. 'attr':attrName,
  589. 'old_val':oldVal,
  590. 'new_val':newVal})
  591. changedSomething = True
  592. except Exception as e :
  593. raise Exception("An error has occurred while computing the value of the attribute '%s' :: %s" % (attrName, e))
  594. return changedSomething
  595. # Build a dictionary {label: node index} mapping each label of the pattern to a node in the graph to rewrite.
  596. # Because of the uniqueness property of labels in a rule, we can store all LHS labels
  597. # and subsequently add the labels corresponding to the nodes to be created.
  598. labels = match.copy()
  599. # Update attribute values
  600. LHS_labels = self.pre_labels
  601. for label in LHS_labels:
  602. rhsNodeIndex = self.get_node_with_label(label)
  603. if rhsNodeIndex is None:
  604. continue # not in the interface graph (LHS n RHS)
  605. if set_attributes(rhsNodeIndex, labels[label], False, labels):
  606. graph.node_set_attribute(labels[label], Himesis.Constants.MT_DIRTY, True)
  607. # graph.vs[labels[label]][Himesis.Constants.MT_DIRTY] = True
  608. # Create new nodes (non-connectors first)
  609. if self.vertex_count() == 0 :
  610. RHS_labels = []
  611. else:
  612. RHS_labels = []
  613. for node in self.node_guid_iter():
  614. RHS_labels.append(self.node_get_attribute(node, Himesis.Constants.MT_LABEL))
  615. # RHS_labels = self.vs[Himesis.Constants.MT_LABEL]
  616. # sort non-connectors first
  617. RHS_labels.sort(key=lambda x: self.node_get_attribute(self.get_node_with_label(x), Himesis.Constants.CONNECTOR_TYPE) or False)
  618. # RHS_labels.sort(key=lambda x: self.vs[ self.get_node_with_label(x) ][Himesis.Constants.CONNECTOR_TYPE] or False)
  619. neighborhood = [graph.node_get_attributes(labels[l]) for l in LHS_labels]
  620. new_labels = []
  621. for label in RHS_labels:
  622. rhsNodeIndex = self.get_node_with_label(label)
  623. if label not in LHS_labels:
  624. new_labels += [label]
  625. newNodeIndex = graph.add_node(
  626. self.node_get_attribute(rhsNodeIndex, Himesis.Constants.FULLTYPE),
  627. self.node_get_attribute(rhsNodeIndex, Himesis.Constants.CONNECTOR_TYPE))
  628. packet.deltas.append(
  629. {'op':'MKNODE',
  630. 'neighborhood':neighborhood,
  631. 'guid':graph.node_get_attribute(newNodeIndex, Himesis.Constants.GUID)})
  632. labels[label] = newNodeIndex
  633. set_attributes(rhsNodeIndex, newNodeIndex, True, labels)
  634. # Link new nodes (Create new edges)
  635. visited_edges = []
  636. for label in sorted(new_labels):
  637. edges = [e for e in self.edge_iter() if (e not in visited_edges and
  638. (label == self.node_get_attribute(self.edge_get_source(e), Himesis.Constants.MT_LABEL) or
  639. label == self.node_get_attribute(self.edge_get_target(e), Himesis.Constants.MT_LABEL)))]
  640. for edge in edges:
  641. # src_label = self.node_get_attribute(self.edge_get_source(edge), Himesis.Constants.MT_LABEL)
  642. # tgt_label = self.node_get_attribute(self.edge_get_target(edge), Himesis.Constants.MT_LABEL)
  643. sl = self.node_get_attribute(self.edge_get_source(edge), Himesis.Constants.MT_LABEL)
  644. tl = self.node_get_attribute(self.edge_get_target(edge), Himesis.Constants.MT_LABEL)
  645. graph.link_nodes(labels[sl], labels[tl], self.edge_get_label(edge))
  646. # graph.add_edges([(labels[src_label], labels[tgt_label])])
  647. packet.deltas.append(
  648. {'op':'MKEDGE',
  649. 'guid1':self.edge_get_source(edge),
  650. 'guid2':self.edge_get_target(edge)})
  651. visited_edges.append(edge)
  652. # Set the output pivots
  653. for node in self.node_guid_iter():
  654. pivot_out = self.node_get_attribute(node, Himesis.Constants.MT_PIVOT_OUT)
  655. if pivot_out:
  656. label = self.node_get_attribute(node, Himesis.Constants.MT_LABEL)
  657. packet.global_pivots[pivot_out] = labels[label]
  658. # Perform the post-action
  659. try:
  660. packet.deltas.extend(self[Himesis.Constants.MT_ACTION](labels, graph))
  661. except Exception as e:
  662. raise Exception('An error has occurred while applying the post-action', e)
  663. # Delete nodes (automatically deletes adjacent edges)
  664. labels_to_delete = []
  665. rmnodes = []
  666. rmedges = []
  667. for label in LHS_labels:
  668. if label not in RHS_labels:
  669. labels_to_delete.append(labels[label])
  670. rmnodes.append({'op':'RMNODE','attrs': graph.node_get_attributes(labels[label]),'guid': labels[label]})
  671. edges = [e for e in graph.edge_iter() if labels[label] == graph.edge_get_source(e) or labels[label] == graph.edge_get_target(e)]
  672. for edge in edges:
  673. # for edge in graph.es.select(lambda e: (labels[label] == e.source or labels[label] == e.target)) :
  674. # found = False
  675. for rmedge in rmedges :
  676. if rmedge['guid1'] == graph.edge_get_source(edge) and \
  677. rmedge['guid2'] == graph.edge_get_target(edge):
  678. # found = True
  679. break
  680. else:
  681. rmedges.append({'op':'RMEDGE',
  682. 'guid1':graph.edge_get_source(edge),
  683. 'guid2':graph.edge_get_target(edge)})
  684. if len(labels_to_delete) > 0 :
  685. packet.deltas = rmedges + rmnodes + packet.deltas
  686. graph.delete_nodes(labels_to_delete)
  687. ''' hergin :: motif-integration start :: remove the deleted nodes from pivots list '''
  688. for uuid in packet.global_pivots:
  689. deleted=False
  690. for toBeDeleted in rmnodes:
  691. if toBeDeleted['guid'] == packet.global_pivots[uuid]:
  692. del packet.global_pivots[uuid]
  693. deleted=True
  694. continue
  695. if deleted:
  696. continue
  697. ''' hergin :: motif-integration end '''