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.

215 lines
7.8 KiB

4 years ago
  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. if not self._model.is_nondeterministic_model:
  100. return 1
  101. return self._model.get_nr_available_actions(self._engine.get_current_state())
  102. def _report_state(self):
  103. if self._observation_mode == SimulatorObservationMode.STATE_LEVEL:
  104. return self._engine.get_current_state()
  105. elif self._observation_mode == SimulatorObservationMode.PROGRAM_LEVEL:
  106. return self._state_valuations.get_json(self._engine.get_current_state())
  107. assert False, "The observation mode is unexpected"
  108. def _report_observation(self):
  109. """
  110. :return:
  111. """
  112. #TODO this should be ensured earlier
  113. assert self._model.model_type == stormpy.storage.ModelType.POMDP
  114. if self._observation_mode == SimulatorObservationMode.STATE_LEVEL:
  115. return self._model.get_observation(self._engine.get_current_state())
  116. elif self._observation_mode == SimulatorObservationMode.PROGRAM_LEVEL:
  117. raise NotImplementedError("Program level observations are not implemented in storm")
  118. assert False, "The observation mode is unexpected"
  119. def _report_result(self):
  120. if self._full_observe:
  121. return self._report_state(), self._report_rewards()
  122. else:
  123. return self._report_observation(), self._report_rewards()
  124. def _report_rewards(self):
  125. return self._engine.get_last_reward()
  126. def random_step(self):
  127. check = self._engine.random_step()
  128. assert check
  129. return self._report_result()
  130. def step(self, action=None):
  131. if action is None:
  132. if self._model.is_nondeterministic_model and self.nr_available_actions() > 1:
  133. raise RuntimeError("Must specify an action in nondeterministic models.")
  134. check = self._engine.step(0)
  135. assert check
  136. elif type(action) == int and self._action_mode == SimulatorActionMode.INDEX_LEVEL:
  137. if action >= self.nr_available_actions():
  138. raise RuntimeError(f"Only {self.nr_available_actions()} actions available")
  139. check = self._engine.step(action)
  140. assert check
  141. elif self._action_mode == SimulatorActionMode.GLOBAL_NAMES:
  142. action_index = None
  143. av_actions = self.available_actions()
  144. for offset, label in enumerate(av_actions):
  145. if action == label:
  146. action_index = offset
  147. break
  148. if action_index is None:
  149. raise ValueError(f"Could not find action: {action}")
  150. check = self._engine.step(action_index)
  151. assert check
  152. else:
  153. raise ValueError(f"Unrecognized type of action {action}")
  154. return self._report_result()
  155. def restart(self):
  156. self._engine.reset_to_initial_state()
  157. return self._report_result()
  158. def is_done(self):
  159. return self._model.is_sink_state(self._engine.get_current_state())
  160. def set_observation_mode(self, mode):
  161. super().set_observation_mode(mode)
  162. if self._observation_mode == SimulatorObservationMode.PROGRAM_LEVEL:
  163. if not self._model.has_state_valuations():
  164. raise RuntimeError("Program level observations require model with state valuations")
  165. self._state_valuations = self._model.state_valuations
  166. def create_simulator(model, seed = None):
  167. """
  168. Factory method for creating a simulator.
  169. :param model: Some form of model
  170. :param seed: A seed for reproducibility. If None (default), the seed is internally generated.
  171. :return: A simulator that can simulate on top of this model
  172. """
  173. if isinstance(model, stormpy.storage._ModelBase):
  174. if model.is_sparse_model:
  175. return SparseSimulator(model, seed)
  176. else:
  177. raise NotImplementedError("Currently, we only support simulators for sparse models.")