iterator.py 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. '''This file is part of AToMPM - A Tool for Multi-Paradigm Modelling
  2. Copyright 2011 by the AToMPM team and licensed under the LGPL
  3. See COPYING.lesser and README.md in the root of this project for full details'''
  4. from ..util.seeded_random import Random
  5. from ..util.infinity import INFINITY
  6. from .rule_primitive import RulePrimitive
  7. #from messages import TransformationException
  8. class Iterator(RulePrimitive):
  9. '''
  10. Chooses randomly one match from the packet.
  11. '''
  12. def __init__(self, condition=None, max_iterations=INFINITY, rng=None):
  13. '''
  14. Selects one match from the packet.
  15. @param condition: The pre-condition pattern.
  16. @param max_iterations: The maximum number of times to select.
  17. By default, this is +INFINITY.
  18. '''
  19. super(Iterator, self).__init__()
  20. self.max_iterations = max_iterations
  21. self.iterations = 0
  22. self.rng = rng
  23. if condition:
  24. self.condition = condition.get_id()
  25. def cancelIn(self, cancel):
  26. if self.condition not in cancel.exclusions:
  27. super(Iterator, self).cancelIn(cancel)
  28. self.iterations = 0
  29. def packet_in(self, packet):
  30. self.exception = None
  31. self.is_success = False
  32. if packet.current in packet.match_sets:
  33. self.condition = packet.current
  34. # Promote the selected match to be the match to rewrite
  35. packet.match_sets[packet.current].match2rewrite = self._choose(packet)
  36. self._globalize_pivots(packet)
  37. self.iterations = 1
  38. self.is_success = True
  39. return packet
  40. def next_in(self, packet):
  41. self.exception = None
  42. self.is_success = False
  43. packet.current = self.condition
  44. if self.iterations < self.max_iterations and packet.current in packet.match_sets:
  45. if len(packet.match_sets[self.condition].matches) == 0:
  46. del packet.match_sets[self.condition]
  47. return packet
  48. # Promote the selected match to be the match to rewrite
  49. packet.match_sets[packet.current].match2rewrite = self._choose(packet)
  50. self._globalize_pivots(packet)
  51. self.iterations += 1
  52. self.is_success = True
  53. return packet
  54. def _choose(self, packet):
  55. # Choose a match form the current match set and remove it from the list of matches
  56. return packet.match_sets[packet.current].matches.pop((self.rng if self.rng != None else Random).randint(0, len(packet.match_sets[packet.current].matches) - 1))
  57. def _globalize_pivots(self, packet):
  58. """
  59. Puts all local pivots of the current match in the global pivots of the packet.
  60. Of course, local pivots have priority over global pivots.
  61. """
  62. local_pivots = packet.match_sets[packet.current].match2rewrite.local_pivots
  63. for p in local_pivots:
  64. packet.global_pivots[p] = local_pivots[p]