selector.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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 .control_primitive import ControlPrimitive
  6. from .messages import Cancel, TransformationException, NIL_PACKET
  7. class Selector(ControlPrimitive):
  8. '''
  9. Selects a packet randomly.
  10. '''
  11. def __init__(self):
  12. '''
  13. Selects a packet randomly.
  14. '''
  15. super(Selector, self).__init__()
  16. self.exclusions = []
  17. def success_in(self, packet):
  18. '''
  19. Receives a successful packet
  20. '''
  21. self.exception = None
  22. self.is_success = False
  23. self.success.append(packet)
  24. def fail_in(self, packet):
  25. '''
  26. Receives a failed packet
  27. '''
  28. self.exception = None
  29. self.is_success = False
  30. self.fail.append(packet)
  31. def reset(self):
  32. super(Selector, self).reset()
  33. self.exclusions = []
  34. def select(self):
  35. '''
  36. Selects a packet randomly from the success list.
  37. If the success list is empty, then from the fail list.
  38. '''
  39. self.exception = None
  40. self.is_success = False
  41. if len(self.success) > 0:
  42. self.is_success = True
  43. packet = Random.choice(self.success)
  44. self.exclusions.append(packet.current)
  45. return packet
  46. elif len(self.fail) > 0:
  47. self.is_success = False
  48. return Random.choice(self.fail)
  49. else:
  50. self.is_success = False
  51. #TODO: This should be a TransformationLanguageSpecificException
  52. self.exception = TransformationException('No packet was received')
  53. self.exception.packet = NIL_PACKET
  54. return NIL_PACKET
  55. def cancel(self):
  56. '''
  57. Produces a cancel event and resets its state
  58. '''
  59. c = Cancel()
  60. c.exclusions = self.exclusions
  61. self.reset()
  62. return c