You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

197 lines
7.1 KiB

  1. from enum import Enum
  2. import stormpy.core
  3. class SimulatorObservationMode(Enum):
  4. STATE_LEVEL = 0,
  5. PROGRAM_LEVEL = 1
  6. class SimulatorActionMode(Enum):
  7. INDEX_LEVEL = 0,
  8. GLOBAL_NAMES = 1
  9. class Simulator:
  10. """
  11. Base class for simulators.
  12. """
  13. def __init__(self, seed=None):
  14. self._seed = seed
  15. self._observation_mode = SimulatorObservationMode.STATE_LEVEL
  16. self._action_mode = SimulatorActionMode.INDEX_LEVEL
  17. self._full_observe = False
  18. def available_actions(self):
  19. """
  20. Returns an iterable over the available actions. The action mode may be used to select how actions are referred to.
  21. TODO: Support multiple action modes
  22. :return:
  23. """
  24. raise NotImplementedError("Abstract Superclass")
  25. def step(self, action=None):
  26. """
  27. Do a step taking the passed action.
  28. :param action: The index of the action, for deterministic actions, action may be None.
  29. :return: The observation (on state or program level).
  30. """
  31. raise NotImplementedError("Abstract superclass")
  32. def restart(self):
  33. """
  34. Reset the simulator to the initial state
  35. """
  36. raise NotImplementedError("Abstract superclass")
  37. def is_done(self):
  38. """
  39. Is the simulator in a sink state?
  40. :return: Yes, if the simulator is in a sink state.
  41. """
  42. return False
  43. def set_observation_mode(self, mode):
  44. """
  45. :param mode: STATE_LEVEL or PROGRAM_LEVEL
  46. :type mode:
  47. """
  48. if not isinstance(mode, SimulatorObservationMode):
  49. raise RuntimeError("Observation mode must be a SimulatorObservationMode")
  50. self._observation_mode = mode
  51. def set_action_mode(self, mode):
  52. if not isinstance(mode, SimulatorActionMode):
  53. raise RuntimeError("Action mode must be a SimulatorActionMode")
  54. self._action_mode = mode
  55. def set_full_observability(self, value):
  56. """
  57. Sets whether the full state space is observable.
  58. Default inherited from the model, but this method overrides the setting.
  59. :param value:
  60. """
  61. self._full_observe = value
  62. class SparseSimulator(Simulator):
  63. """
  64. Simulator on top of sparse models.
  65. """
  66. def __init__(self, model, seed=None):
  67. super().__init__(seed)
  68. self._model = model
  69. self._engine = stormpy.core._DiscreteTimeSparseModelSimulatorDouble(model)
  70. if seed is not None:
  71. self._engine.set_seed(seed)
  72. self._state_valuations = None
  73. self.set_full_observability(self._model.model_type != stormpy.storage.ModelType.POMDP)
  74. def available_actions(self):
  75. if self._action_mode == SimulatorActionMode.INDEX_LEVEL:
  76. return range(self.nr_available_actions())
  77. else:
  78. assert self._model.has_choice_labeling(), "Global names require choice labeling"
  79. av_actions = []
  80. current_state = self._engine.get_current_state()
  81. for action_offset in range(self.nr_available_actions()):
  82. choice_label = self._model.choice_labeling.get_labels_of_choice(self._model.get_choice_index(current_state, action_offset))
  83. if len(choice_label) == 0:
  84. av_actions.append(f"_act_{action_offset}")
  85. elif len(choice_label) == 1:
  86. av_actions.append(list(choice_label)[0])
  87. else:
  88. assert False, "Unknown type of choice label, support not implemented"
  89. return av_actions
  90. def nr_available_actions(self):
  91. return self._model.get_nr_available_actions(self._engine.get_current_state())
  92. def _report_state(self):
  93. if self._observation_mode == SimulatorObservationMode.STATE_LEVEL:
  94. return self._engine.get_current_state()
  95. elif self._observation_mode == SimulatorObservationMode.PROGRAM_LEVEL:
  96. return self._state_valuations.get_json(self._engine.get_current_state())
  97. assert False, "The observation mode is unexpected"
  98. def _report_observation(self):
  99. """
  100. :return:
  101. """
  102. #TODO this should be ensured earlier
  103. assert self._model.model_type == stormpy.storage.ModelType.POMDP
  104. if self._observation_mode == SimulatorObservationMode.STATE_LEVEL:
  105. return self._model.get_observation(self._engine.get_current_state())
  106. elif self._observation_mode == SimulatorObservationMode.PROGRAM_LEVEL:
  107. raise NotImplementedError("Program level observations are not implemented in storm")
  108. assert False, "The observation mode is unexpected"
  109. def _report_result(self):
  110. if self._full_observe:
  111. return self._report_state()
  112. else:
  113. return self._report_observation()
  114. def step(self, action=None):
  115. if action is None:
  116. if self._model.is_nondeterministic_model and self.nr_available_actions() > 1:
  117. raise RuntimeError("Must specify an action in nondeterministic models.")
  118. check = self._engine.step(0)
  119. assert check
  120. elif type(action) == int and self._action_mode == SimulatorActionMode.INDEX_LEVEL:
  121. if action >= self.nr_available_actions():
  122. raise RuntimeError(f"Only {self.nr_available_actions()} actions available")
  123. check = self._engine.step(action)
  124. assert check
  125. elif self._action_mode == SimulatorActionMode.GLOBAL_NAMES:
  126. current_state = self._engine.get_current_state()
  127. action_index = None
  128. av_actions = self.available_actions()
  129. for offset, label in enumerate(av_actions):
  130. if action == label:
  131. action_index = offset
  132. break
  133. if action_index is None:
  134. raise ValueError("Could not find action: ")
  135. check = self._engine.step(action_index)
  136. assert check
  137. else:
  138. raise ValueError("Unrecognized type of action %s" % action)
  139. return self._report_result()
  140. def restart(self):
  141. self._engine.reset_to_initial_state()
  142. return self._report_result()
  143. def is_done(self):
  144. return self._model.is_sink_state(self._engine.get_current_state())
  145. def set_observation_mode(self, mode):
  146. super().set_observation_mode(mode)
  147. if self._observation_mode == SimulatorObservationMode.PROGRAM_LEVEL:
  148. if not self._model.has_state_valuations():
  149. raise RuntimeError("Program level observations require model with state valuations")
  150. self._state_valuations = self._model.state_valuations
  151. def create_simulator(model, seed = None):
  152. """
  153. Factory method for creating a simulator.
  154. :param model: Some form of model
  155. :param seed: A seed for reproducibility. If None (default), the seed is internally generated.
  156. :return: A simulator that can simulate on top of this model
  157. """
  158. if isinstance(model, stormpy.storage._ModelBase):
  159. if model.is_sparse_model:
  160. return SparseSimulator(model, seed)
  161. else:
  162. raise NotImplementedError("Currently, we only support simulators for sparse models.")