matcher.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  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. import sys
  16. from copy import deepcopy
  17. from pytcore.util.infinity import INFINITY
  18. from pytcore.core.match_algo import HimesisMatcher
  19. from pytcore.core.himesis import HConstants as HC
  20. from pytcore.tcore.rule_primitive import RulePrimitive
  21. from pytcore.tcore.messages import MatchSet, Match, TransformationException
  22. if sys.version_info[0] >= 3:
  23. from functools import reduce
  24. class Matcher(RulePrimitive):
  25. '''
  26. Binds the source graph according to the pre-condition pattern.
  27. '''
  28. def __init__(self, condition, max=INFINITY):
  29. '''
  30. Binds the source graph according to the pre-condition pattern.
  31. @param condition: The pre-condition pattern.
  32. @param max: The maximum number of matches.
  33. '''
  34. super(Matcher, self).__init__()
  35. self.max = max
  36. self.condition = condition
  37. def __str__(self):
  38. s = super(Matcher, self).__str__()
  39. s = s.split(' ')
  40. s.insert(1, '[%s]' % self.condition.name)
  41. return reduce(lambda x, y: '%s %s' % (x,y), s)
  42. def packet_in(self, packet):
  43. self.exception = None
  44. self.is_success = False
  45. if self.condition[HC.GUID] in packet.match_sets:
  46. matchSet = packet.match_sets[self.condition[HC.GUID]]
  47. else:
  48. matchSet = MatchSet()
  49. # Find the matches
  50. try:
  51. i = 1
  52. if i <= self.max:
  53. for mapping in self._match(packet.graph, packet.global_pivots):
  54. # Convert the mapping to a Match object
  55. match = Match()
  56. match.from_mapping(mapping, packet.graph, self.condition)
  57. matchSet.matches.append(match)
  58. i += 1
  59. if i > self.max:
  60. # We don't need any more matches
  61. break
  62. except Exception as e:
  63. self.is_success = False
  64. self.exception = TransformationException(e)
  65. self.exception.packet = packet
  66. self.exception.transformation_unit = self
  67. return packet
  68. # Don't forget to add the match set to the packet, even if no matches were found
  69. if len(matchSet.matches) > 0:
  70. packet.match_sets[self.condition[HC.GUID]] = matchSet
  71. # Identify that this is the condition we are currently processing
  72. packet.current = self.condition[HC.GUID]
  73. # Success only if matches were found
  74. self.is_success = len(matchSet.matches) > 0
  75. return packet
  76. def _match(self, graph, pivots) :
  77. '''
  78. Matcher with pivots and (possibly) multiple NACs
  79. 1. Verify that no unbound NAC has a match
  80. 2. Let the "bridge" denote the biggest graph that is the intersection of the LHS and a NAC, among all NACs
  81. 3. Match the common part between the LHS & the NAC, i.e., the "bridge"
  82. 3.1 Continue the matching ensuring no occurrence of the NAC
  83. 3.2. If a NAC is found, ignore the current bridge mapping
  84. 3.3. Continue to find complete matches of the LHS,
  85. given each partial match found in 3.1.
  86. 3.4. For each valid match, verify that no occurrence of any remaining bound NAC is found,
  87. given the mapping found in 3.3.
  88. '''
  89. pred1 = {} # To optimize the matcher, since otherwise matcher will compute the predecessors of the source graph many times
  90. succ1 = {} # To optimize the matcher, since otherwise matcher will compute the successors of the source graph many times
  91. # Cache the pivot nodes of the source graph
  92. pivots = deepcopy(pivots)
  93. pivots.to_source_node_indices(graph)
  94. #===================================================================
  95. # First process the NACs that are not bound to the LHS
  96. #===================================================================
  97. for NAC in self.condition.getUnboundNACs():
  98. # Look for a NAC match
  99. nacMatcher = HimesisMatcher(source_graph=graph, pattern_graph=NAC)
  100. # Convert the pivots
  101. nac_pivots = pivots.to_mapping(graph, NAC)
  102. try:
  103. for mapping in nacMatcher.match_iter(context=nac_pivots):
  104. # Make the mapping into {...,NAClabel:graphIndex,...}
  105. match = Match()
  106. match.from_mapping(mapping, graph, self.condition)
  107. if NAC[HC.MT_CONSTRAINT](match.to_label_mapping(graph), graph):
  108. # An unbound NAC has been found: this pattern can never match
  109. return
  110. except: raise
  111. finally: nacMatcher.reset_recursion_limit()
  112. # For further matching optimizations
  113. pred1 = nacMatcher.pred1
  114. succ1 = nacMatcher.succ1
  115. # Either there are no NACs, or there were only unbound NACs that do not match, so match the LHS now
  116. if not self.condition.hasBoundNACs():
  117. lhsMatcher = HimesisMatcher(source_graph=graph, pattern_graph=self.condition, pred1=pred1, succ1=succ1)
  118. # Convert the pivots
  119. lhs_pivots = pivots.to_mapping(graph, self.condition)
  120. try:
  121. for mapping in lhsMatcher.match_iter(context=lhs_pivots):
  122. # Make the mapping into {...,LHSlabel:graphIndex,...}
  123. match = Match()
  124. match.from_mapping(mapping, graph, self.condition)
  125. if self.condition[HC.MT_CONSTRAINT](match.to_label_mapping(graph), graph):
  126. yield mapping
  127. except: raise
  128. finally: lhsMatcher.reset_recursion_limit()
  129. # The matching is complete
  130. return
  131. #===================================================================
  132. # Now process the NACs that have some nodes bound to the LHS
  133. #===================================================================
  134. # Continue the matching looking for the LHS now
  135. lhsMatcher = HimesisMatcher(source_graph=graph, pattern_graph=self.condition, pred1=pred1, succ1=succ1)
  136. # Augment the bridge mapping with the pivot mappings
  137. lhs_pivots = pivots.to_mapping(graph, self.condition)
  138. try:
  139. for mapping in lhsMatcher.match_iter(context=lhs_pivots):
  140. # Make the mapping into {...,LHSlabel:graphIndex,...}
  141. match = Match()
  142. match.from_mapping(mapping, graph, self.condition)
  143. if self.condition[HC.MT_CONSTRAINT](match.to_label_mapping(graph), graph):
  144. # A match of the LHS is found: ensure that no remaining NAC do match
  145. invalid = False
  146. for NAC in self.condition.getBoundNACs():
  147. # This mapping represents the mapping of the bridge of this NAC with the LHS
  148. bridgeMapping = match.to_mapping(graph, NAC)
  149. # Now continue the matching looking for a match of the corresponding NAC
  150. nacMatcher = HimesisMatcher(source_graph=graph, pattern_graph=NAC, pred1=pred1, succ1=succ1)
  151. for nac_mapping in nacMatcher.match_iter(context=bridgeMapping):
  152. # Make the mapping into {...,NAClabel:graphIndex,...}
  153. match = Match()
  154. match.from_mapping(nac_mapping, graph, NAC)
  155. if NAC[HC.MT_CONSTRAINT](match.to_label_mapping(graph), graph):
  156. # An occurrence of the NAC is found: current mapping is not valid
  157. invalid = True
  158. break
  159. if invalid:
  160. # An occurrence of the NAC was found: current mapping is not valid
  161. break
  162. else:
  163. # Either there are no bound NACs or no occurrence of any bound NAC was found: current mapping is valid
  164. yield mapping
  165. except: raise
  166. finally: lhsMatcher.reset_recursion_limit()