selector.py 2.6 KB

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