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.

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