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.

208 lines
7.6 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.
  21. The action mode may be used to select how actions are referred to.
  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. Select the observation mode, that is, how the states are represented
  46. :param mode: STATE_LEVEL or PROGRAM_LEVEL
  47. :type mode:
  48. """
  49. if not isinstance(mode, SimulatorObservationMode):
  50. raise RuntimeError("Observation mode must be a SimulatorObservationMode")
  51. self._observation_mode = mode
  52. def set_action_mode(self, mode):
  53. """
  54. Select the action mode, that is, how the actions are represented
  55. :param mode: SimulatorActionMode.INDEX_LEVEL or SimulatorActionMode.GLOBAL_NAMES
  56. :return:
  57. """
  58. if not isinstance(mode, SimulatorActionMode):
  59. raise RuntimeError("Action mode must be a SimulatorActionMode")
  60. self._action_mode = mode
  61. def set_full_observability(self, value):
  62. """
  63. Sets whether the full state space is observable.
  64. Default inherited from the model, but this method overrides the setting.
  65. :param value:
  66. """
  67. self._full_observe = value
  68. class SparseSimulator(Simulator):
  69. """
  70. Simulator on top of sparse models.
  71. """
  72. def __init__(self, model, seed=None):
  73. super().__init__(seed)
  74. self._model = model
  75. self._engine = stormpy.core._DiscreteTimeSparseModelSimulatorDouble(model)
  76. if seed is not None:
  77. self._engine.set_seed(seed)
  78. self._state_valuations = None
  79. self.set_full_observability(self._model.model_type != stormpy.storage.ModelType.POMDP)
  80. def available_actions(self):
  81. if self._action_mode == SimulatorActionMode.INDEX_LEVEL:
  82. return range(self.nr_available_actions())
  83. else:
  84. assert self._action_mode == SimulatorActionMode.GLOBAL_NAMES, "Unknown type of simulator action mode"
  85. if not self._model.has_choice_labeling():
  86. raise RuntimeError("Global names action mode requires model with choice labeling")
  87. av_actions = []
  88. current_state = self._engine.get_current_state()
  89. for action_offset in range(self.nr_available_actions()):
  90. choice_label = self._model.choice_labeling.get_labels_of_choice(self._model.get_choice_index(current_state, action_offset))
  91. if len(choice_label) == 0:
  92. av_actions.append(f"_act_{action_offset}")
  93. elif len(choice_label) == 1:
  94. av_actions.append(list(choice_label)[0])
  95. else:
  96. assert False, "Unknown type of choice label, support not implemented"
  97. return av_actions
  98. def nr_available_actions(self):
  99. return self._model.get_nr_available_actions(self._engine.get_current_state())
  100. def _report_state(self):
  101. if self._observation_mode == SimulatorObservationMode.STATE_LEVEL:
  102. return self._engine.get_current_state()
  103. elif self._observation_mode == SimulatorObservationMode.PROGRAM_LEVEL:
  104. return self._state_valuations.get_json(self._engine.get_current_state())
  105. assert False, "The observation mode is unexpected"
  106. def _report_observation(self):
  107. """
  108. :return:
  109. """
  110. #TODO this should be ensured earlier
  111. assert self._model.model_type == stormpy.storage.ModelType.POMDP
  112. if self._observation_mode == SimulatorObservationMode.STATE_LEVEL:
  113. return self._model.get_observation(self._engine.get_current_state())
  114. elif self._observation_mode == SimulatorObservationMode.PROGRAM_LEVEL:
  115. raise NotImplementedError("Program level observations are not implemented in storm")
  116. assert False, "The observation mode is unexpected"
  117. def _report_result(self):
  118. if self._full_observe:
  119. return self._report_state(), self._report_rewards()
  120. else:
  121. return self._report_observation(), self._report_rewards()
  122. def _report_rewards(self):
  123. return self._engine.get_last_reward()
  124. def step(self, action=None):
  125. if action is None:
  126. if self._model.is_nondeterministic_model and self.nr_available_actions() > 1:
  127. raise RuntimeError("Must specify an action in nondeterministic models.")
  128. check = self._engine.step(0)
  129. assert check
  130. elif type(action) == int and self._action_mode == SimulatorActionMode.INDEX_LEVEL:
  131. if action >= self.nr_available_actions():
  132. raise RuntimeError(f"Only {self.nr_available_actions()} actions available")
  133. check = self._engine.step(action)
  134. assert check
  135. elif self._action_mode == SimulatorActionMode.GLOBAL_NAMES:
  136. action_index = None
  137. av_actions = self.available_actions()
  138. for offset, label in enumerate(av_actions):
  139. if action == label:
  140. action_index = offset
  141. break
  142. if action_index is None:
  143. raise ValueError(f"Could not find action: {action}")
  144. check = self._engine.step(action_index)
  145. assert check
  146. else:
  147. raise ValueError(f"Unrecognized type of action {action}")
  148. return self._report_result()
  149. def restart(self):
  150. self._engine.reset_to_initial_state()
  151. return self._report_result()
  152. def is_done(self):
  153. return self._model.is_sink_state(self._engine.get_current_state())
  154. def set_observation_mode(self, mode):
  155. super().set_observation_mode(mode)
  156. if self._observation_mode == SimulatorObservationMode.PROGRAM_LEVEL:
  157. if not self._model.has_state_valuations():
  158. raise RuntimeError("Program level observations require model with state valuations")
  159. self._state_valuations = self._model.state_valuations
  160. def create_simulator(model, seed = None):
  161. """
  162. Factory method for creating a simulator.
  163. :param model: Some form of model
  164. :param seed: A seed for reproducibility. If None (default), the seed is internally generated.
  165. :return: A simulator that can simulate on top of this model
  166. """
  167. if isinstance(model, stormpy.storage._ModelBase):
  168. if model.is_sparse_model:
  169. return SparseSimulator(model, seed)
  170. else:
  171. raise NotImplementedError("Currently, we only support simulators for sparse models.")