simulator.py 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. import abc
  2. import random
  3. import math
  4. import functools
  5. import sys
  6. from typing import Callable, Generator
  7. from framework.conformance import Conformance, render_conformance_check_result
  8. from concrete_syntax.common import indent
  9. from concrete_syntax.textual_od.renderer import render_od
  10. from transformation.cloner import clone_od
  11. from api.od import ODAPI
  12. class DecisionMaker:
  13. @abc.abstractmethod
  14. def __call__(self, actions):
  15. pass
  16. class RandomDecisionMaker(DecisionMaker):
  17. def __init__(self, seed=0, verbose=True):
  18. self.seed = seed
  19. self.r = random.Random(seed)
  20. def __str__(self):
  21. return f"RandomDecisionMaker(seed={self.seed})"
  22. def __call__(self, actions):
  23. arr = [action for descr, action in actions]
  24. i = math.floor(self.r.random()*len(arr))
  25. return arr[i]
  26. class InteractiveDecisionMaker(DecisionMaker):
  27. # auto_proceed: whether to prompt if there is only one enabled action
  28. def __init__(self, msg="Select action:", auto_proceed=False):
  29. self.msg = msg
  30. self.auto_proceed = auto_proceed
  31. def __str__(self):
  32. return f"InteractiveDecisionMaker()"
  33. def __call__(self, actions):
  34. arr = []
  35. for i, (key, result) in enumerate(actions):
  36. print(f" {chr(97+i)}. {key}")
  37. arr.append(result)
  38. if len(arr) == 0:
  39. return
  40. if len(arr) == 1 and self.auto_proceed:
  41. return arr[0]
  42. def __choose():
  43. sys.stdout.write(f"{self.msg} ")
  44. try:
  45. raw = input()
  46. choice = ord(raw)-97 # may raise ValueError
  47. if choice >= 0 and choice < len(arr):
  48. return arr[choice]
  49. except (ValueError, TypeError):
  50. pass
  51. print("Invalid option")
  52. return __choose()
  53. return __choose()
  54. class MinimalSimulator:
  55. def __init__(self,
  56. action_generator: Callable[[any], Generator[any, None, None]],
  57. decision_maker: DecisionMaker = RandomDecisionMaker(seed=0),
  58. # Returns 'None' to keep running, or a string to end simulation
  59. # Can also have side effects, such as rendering the model, and performing a conformance check.
  60. # BTW, Simulation will always end when there are no more enabled actions.
  61. termination_condition=lambda model: None,
  62. verbose=True,
  63. ):
  64. self.action_generator = action_generator
  65. self.decision_maker = decision_maker
  66. self.termination_condition = termination_condition
  67. self.verbose = verbose
  68. def _print(self, *args):
  69. if self.verbose:
  70. print(*args)
  71. # Run simulation until termination condition satisfied
  72. def run(self, model):
  73. self._print("Start simulation")
  74. self._print(f"Decision maker: {self.decision_maker}")
  75. step_counter = 0
  76. while True:
  77. termination_reason = self.termination_condition(model)
  78. if termination_reason != None:
  79. self._print(f"Termination condition satisfied.\nReason: {termination_reason}.")
  80. break
  81. chosen_action = self.decision_maker(self.action_generator(model))
  82. if chosen_action == None:
  83. self._print(f"No enabled actions.")
  84. break
  85. (model, msgs) = chosen_action()
  86. self._print(indent('\n'.join(f"▸ {msg}" for msg in msgs), 4))
  87. step_counter += 1
  88. self._print(f"Executed {step_counter} steps.")
  89. return model