himesis.py 34 KB

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