Storm 2.0.0.3
A Modern Probabilistic Model Checker
Loading...
Searching...
No Matches
PolicyExtractor.cpp
Go to the documentation of this file.
1#include "PolicyExtractor.h"
2
11
12#include <algorithm>
13#include <charconv>
14#include <queue>
15#include <string_view>
16#include <unordered_set>
17
18namespace storm::pomdp::policy {
19
20template<typename PomdpModelType, typename BeliefValueType, typename BeliefMdpValueType, typename PolicyValueType>
22 PomdpModelType const& pomdp, BeliefMdpType const& beliefMdp, std::unordered_map<uint64_t, uint32_t> const& beliefStateToObservationMap,
23 storm::storage::Scheduler<BeliefMdpValueType> const& beliefMdpScheduler,
24 std::optional<std::vector<storm::storage::Scheduler<typename PomdpModelType::ValueType>>> const& pomdpApproximationSchedulers)
25 : pomdp(pomdp),
26 beliefMdp(beliefMdp),
27 beliefMdpScheduler(beliefMdpScheduler),
28 beliefStateToObservationMap(beliefStateToObservationMap),
29 pomdpApproximationSchedulers(pomdpApproximationSchedulers) {
30 // Intentionally left empty
31}
32
33template<typename PomdpModelType, typename BeliefValueType, typename BeliefMdpValueType, typename PolicyValueType>
36 std::optional<std::unordered_map<uint64_t, ObservationSignature>> optionalIdToObservationSignature = std::nullopt;
37 std::optional<std::unordered_map<uint64_t, std::unordered_map<uint64_t, std::string>>> optionalIdToActionNameMap = std::nullopt;
38 // Target splitting can introduce observations without extending their valuations.
39 if (pomdp.hasObservationValuations() && pomdp.getObservationValuations().getNumberOfEntities() >= pomdp.getNrObservations()) {
40 auto const& obsValuations = pomdp.getObservationValuations();
41 std::unordered_map<uint64_t, ObservationSignature> idToObservationSignatureMap;
42 std::vector<ObservationSignature> usedObservationSignatures;
43 bool observationSignaturesAreUnique = true;
44 for (uint64_t i = 0; i < pomdp.getNrObservations(); ++i) {
45 auto observationSignature = ObservationSignature::fromValuations(obsValuations, i);
46 if (observationSignature.values.empty() || std::ranges::find(usedObservationSignatures, observationSignature) != usedObservationSignatures.end()) {
47 observationSignaturesAreUnique = false;
48 break;
49 }
50 usedObservationSignatures.push_back(observationSignature);
51 idToObservationSignatureMap[i] = std::move(observationSignature);
52 }
53 if (observationSignaturesAreUnique) {
54 optionalIdToObservationSignature = std::move(idToObservationSignatureMap);
55 }
56 } else if (pomdp.hasObservationValuations()) {
57 STORM_LOG_WARN("Omitting observation signatures from the exported FSC because observation valuations cover only "
58 << pomdp.getObservationValuations().getNumberOfEntities() << " of " << pomdp.getNrObservations()
59 << " observations. Observation matching will use numeric IDs.");
60 }
61 if (pomdp.hasChoiceLabeling()) {
62 auto const& choiceLabeling = pomdp.getChoiceLabeling();
63 std::unordered_map<uint64_t, std::unordered_map<uint64_t, std::string>> idToActionNameMap;
64 auto const nrStates = pomdp.getNumberOfStates();
65 std::vector<uint64_t> representativeStates(pomdp.getNrObservations(), nrStates);
66 for (uint64_t state = 0; state < nrStates; ++state) {
67 auto& representativeState = representativeStates[pomdp.getObservation(state)];
68 if (representativeState == nrStates) {
69 representativeState = state;
70 }
71 }
72 for (uint64_t obs = 0; obs < pomdp.getNrObservations(); ++obs) {
73 auto const representativeState = representativeStates[obs];
74 if (representativeState == nrStates) {
75 continue;
76 }
77 auto const rowGroupIndex = pomdp.getTransitionMatrix().getRowGroupIndices()[representativeState];
78 auto const rowGroupSize = pomdp.getTransitionMatrix().getRowGroupSize(representativeState);
79 for (uint64_t localChoice = 0; localChoice < rowGroupSize; ++localChoice) {
80 auto const globalChoiceIndex = rowGroupIndex + localChoice;
81 STORM_LOG_ASSERT(choiceLabeling.getLabelsOfChoice(globalChoiceIndex).size() <= 1,
82 "Expected choice labeling to have at most one label per choice, but choice ID "
83 << globalChoiceIndex << " has " << choiceLabeling.getLabelsOfChoice(globalChoiceIndex).size() << " labels.");
84 if (choiceLabeling.getLabelsOfChoice(globalChoiceIndex).empty()) {
85 idToActionNameMap[obs][localChoice] = "";
86 } else {
87 idToActionNameMap[obs][localChoice] = *choiceLabeling.getLabelsOfChoice(globalChoiceIndex).begin();
88 }
89 }
90 }
91 optionalIdToActionNameMap = idToActionNameMap;
92 }
93 ObservationBasedFiniteStateController<PolicyValueType> fsc(0ul, optionalIdToObservationSignature, optionalIdToActionNameMap);
94
95 std::unordered_map<uint64_t, uint64_t> beliefStateToFscNodeMap;
96 std::unordered_map<uint64_t, uint64_t> cutoffPolicyToFscNodeMap;
97 using ObservationToActionMap = std::unordered_map<uint64_t, storm::storage::Distribution<PolicyValueType, uint64_t>>;
98 std::unordered_map<uint64_t, ObservationToActionMap> cutoffPolicyToObservationMap;
99 std::queue<uint64_t> statesToProcess;
100 uint64_t nextId = 1ul;
101 auto const addCutoffTransition = [&](uint64_t originNode, uint64_t cutoffBeliefState) {
102 // State has been cut off. Add transition to self-looping cut-off policy node.
103 auto const localCutoffChoice = beliefMdpScheduler.getChoice(cutoffBeliefState).getDeterministicChoice();
104 auto const globalCutoffChoice = beliefMdp.getTransitionMatrix().getRowGroupIndices()[cutoffBeliefState] + localCutoffChoice;
105 auto const& cutoffChoiceLabels = beliefMdp.getChoiceLabeling().getLabelsOfChoice(globalCutoffChoice);
106 STORM_LOG_THROW(cutoffChoiceLabels.size() == 1, storm::exceptions::UnexpectedException,
107 "Expected the selected cutoff choice to have exactly one scheduler label.");
108 std::string const& cutoffChoiceLabel = *cutoffChoiceLabels.begin();
109 constexpr std::string_view schedulerLabelPrefix = "__sched_";
110 STORM_LOG_THROW(cutoffChoiceLabel.starts_with(schedulerLabelPrefix), storm::exceptions::UnexpectedException,
111 "Expected cutoff scheduler label, but found '" << cutoffChoiceLabel << "'.");
112 uint64_t chosenCutoffPolicy = 0;
113 auto const schedulerIndex = std::string_view(cutoffChoiceLabel).substr(schedulerLabelPrefix.size());
114 auto const [parseEnd, parseError] = std::from_chars(schedulerIndex.begin(), schedulerIndex.end(), chosenCutoffPolicy);
115 STORM_LOG_THROW(parseError == std::errc() && parseEnd == schedulerIndex.end(), storm::exceptions::UnexpectedException,
116 "Could not parse cutoff scheduler label '" << cutoffChoiceLabel << "'.");
117 STORM_LOG_THROW(pomdpApproximationSchedulers.has_value() && chosenCutoffPolicy < pomdpApproximationSchedulers->size(),
118 storm::exceptions::UnexpectedException,
119 "Cutoff scheduler label '" << cutoffChoiceLabel << "' does not refer to an available approximation scheduler.");
120 if (!cutoffPolicyToFscNodeMap.contains(chosenCutoffPolicy)) {
121 // TODO For finite-memory policies, create a node per scheduler memory state and preserve its memory updates.
122 cutoffPolicyToFscNodeMap[chosenCutoffPolicy] = nextId;
123 cutoffPolicyToObservationMap.emplace(chosenCutoffPolicy,
124 pomdpSchedulerToObservationBasedMap(pomdpApproximationSchedulers->at(chosenCutoffPolicy), 0));
125 ++nextId;
126 }
127 auto const& dist = cutoffPolicyToObservationMap.at(chosenCutoffPolicy).at(beliefStateToObservationMap.at(cutoffBeliefState));
128 if (dist.size() == 1) {
129 fsc.addDeterministicActionTransition(originNode, beliefStateToObservationMap.at(cutoffBeliefState), dist.begin()->first,
130 cutoffPolicyToFscNodeMap[chosenCutoffPolicy]);
131 } else {
132 fsc.addRandomisedActionTransition(originNode, beliefStateToObservationMap.at(cutoffBeliefState), dist,
133 cutoffPolicyToFscNodeMap[chosenCutoffPolicy]);
134 }
135 };
136
137 // Add initial transition, using a continuation scheduler if the initial belief was cut off.
138 auto const initialBeliefState = beliefMdp.getInitialStates().getNextSetIndex(0);
139 if (beliefMdp.getStateLabeling().getStateHasLabel("truncated", initialBeliefState)) {
140 addCutoffTransition(0ul, initialBeliefState);
141 } else {
142 auto const initialChoice = beliefMdpScheduler.getChoice(initialBeliefState).getDeterministicChoice();
143 fsc.addDeterministicActionTransition(0ul, beliefStateToObservationMap.at(initialBeliefState), initialChoice, nextId);
144 beliefStateToFscNodeMap[initialBeliefState] = nextId++;
145 statesToProcess.push(initialBeliefState);
146 }
147
148 while (!statesToProcess.empty()) {
149 uint64_t currentState = statesToProcess.front();
150 statesToProcess.pop();
151 auto const currentChoice = beliefMdpScheduler.getChoice(currentState).getDeterministicChoice();
152 for (auto const& entry : beliefMdp.getTransitionMatrix().getRow(currentState, currentChoice)) {
153 auto successorBeliefStateId = entry.getColumn();
154 if (beliefMdp.getStateLabeling().getStateHasLabel("truncated", successorBeliefStateId)) {
155 addCutoffTransition(beliefStateToFscNodeMap.at(currentState), successorBeliefStateId);
156 } else {
157 if (!beliefStateToFscNodeMap.contains(successorBeliefStateId)) {
158 beliefStateToFscNodeMap[successorBeliefStateId] = nextId;
159 ++nextId;
160 statesToProcess.push(successorBeliefStateId);
161 }
162 if (beliefStateToObservationMap.contains(successorBeliefStateId)) {
163 auto const successorChoice = beliefMdpScheduler.getChoice(successorBeliefStateId).getDeterministicChoice();
164 fsc.addDeterministicActionTransition(beliefStateToFscNodeMap[currentState], beliefStateToObservationMap.at(successorBeliefStateId),
165 successorChoice, beliefStateToFscNodeMap[successorBeliefStateId]);
166 } // else, the state does not actually correspond to a belief, and we don't care what to do afterwards
167 }
168 }
169 }
170
171 if (pomdpApproximationSchedulers.has_value()) {
172 for (uint64_t i = 0; i < pomdpApproximationSchedulers->size(); ++i) {
173 // TODO extend for fm-policies
174 if (cutoffPolicyToFscNodeMap.contains(i)) {
175 for (auto const& [observationId, actionDist] : cutoffPolicyToObservationMap.at(i)) {
176 if (actionDist.size() == 1) {
177 fsc.addDeterministicActionTransition(cutoffPolicyToFscNodeMap[i], observationId, actionDist.begin()->first,
178 cutoffPolicyToFscNodeMap[i]);
179 } else {
180 fsc.addRandomisedActionTransition(cutoffPolicyToFscNodeMap[i], observationId, actionDist, cutoffPolicyToFscNodeMap[i]);
181 }
182 }
183 }
184 }
185 }
186 return fsc;
187}
188
189template<typename PomdpModelType, typename BeliefValueType, typename BeliefMdpValueType, typename PolicyValueType>
190std::shared_ptr<storm::models::sparse::Model<BeliefMdpValueType>>
192 storm::models::sparse::StateLabeling newLabeling(beliefMdp.getStateLabeling());
193 if (pomdpApproximationSchedulers.has_value()) {
194 for (uint64_t i = 0; i < pomdpApproximationSchedulers->size(); ++i) {
195 newLabeling.addLabel("sched_" + std::to_string(i));
196 }
197 }
198 for (uint64_t i = 0; i < pomdp.getNrObservations(); ++i) {
199 newLabeling.addLabel("obs_" + std::to_string(i));
200 }
201 newLabeling.addLabel("cutoff");
202 newLabeling.addLabel("clipping");
203 newLabeling.addLabel("finite_mem");
204
205 storm::storage::SparseMatrix<BeliefMdpValueType> transMatrix = beliefMdp.getTransitionMatrix();
206 for (uint64_t i = 0; i < beliefMdp.getNumberOfStates(); ++i) {
207 if (beliefStateToObservationMap.contains(i)) {
208 newLabeling.addLabelToState("obs_" + std::to_string(beliefStateToObservationMap.at(i)), i);
209 }
210 if (newLabeling.getStateHasLabel("truncated", i)) {
211 uint64_t localChosenActionIndex = beliefMdpScheduler.getChoice(i).getDeterministicChoice();
212 auto const chosenRowIndex = transMatrix.getRowGroupIndices()[i] + localChosenActionIndex;
213 if (beliefMdp.getChoiceLabeling().getLabelsOfChoice(chosenRowIndex).size() > 0) {
214 if (auto label = *(beliefMdp.getChoiceLabeling().getLabelsOfChoice(chosenRowIndex).begin()); label.rfind("clip", 0) == 0) {
215 newLabeling.addLabelToState("clipping", i);
216 auto chosenRow = transMatrix.getRow(chosenRowIndex);
217 auto candidateIndex = (chosenRow.end() - 1)->getColumn();
218 transMatrix.makeRowDirac(chosenRowIndex, candidateIndex);
219 } else if (label.rfind("__mem_node", 0) == 0) {
220 newLabeling.addLabelToState("finite_mem", i);
221 newLabeling.addLabelToState("cutoff", i);
222 } else if (pomdpApproximationSchedulers.has_value()) {
223 // Label has form "__sched_X"
224 newLabeling.addLabelToState(label.substr(2), i);
225 newLabeling.addLabelToState("cutoff", i);
226 }
227 }
228 }
229 }
230 newLabeling.removeLabel("truncated");
231
232 transMatrix.dropZeroEntries();
233 storm::storage::sparse::ModelComponents<BeliefMdpValueType> modelComponents(transMatrix, newLabeling, beliefMdp.getRewardModels());
234 if (beliefMdp.hasChoiceLabeling()) {
235 // Add empty string as label of all choices without labels
236 storm::models::sparse::ChoiceLabeling extendedChoiceLabeling(beliefMdp.getChoiceLabeling());
237 extendedChoiceLabeling.addLabel("");
238 for (uint64_t i = 0; i < beliefMdp.getNumberOfChoices(); ++i) {
239 if (beliefMdp.getChoiceLabeling().getLabelsOfChoice(i).empty()) {
240 extendedChoiceLabeling.addLabelToChoice("", i);
241 }
242 }
243 modelComponents.choiceLabeling = extendedChoiceLabeling;
244 }
246 auto inducedMC = newMDP.applyScheduler(beliefMdpScheduler, true);
247 return std::static_pointer_cast<storm::models::sparse::Model<BeliefMdpValueType>>(inducedMC);
248}
249
250template<typename PomdpModelType, typename BeliefValueType, typename BeliefMdpValueType, typename PolicyValueType>
251std::unordered_map<uint64_t, storm::storage::Distribution<PolicyValueType, uint64_t>>
252PolicyExtractor<PomdpModelType, BeliefValueType, BeliefMdpValueType, PolicyValueType>::pomdpSchedulerToObservationBasedMap(
253 storm::storage::Scheduler<typename PomdpModelType::ValueType> const& scheduler, uint64_t memoryState) const {
254 std::unordered_map<uint64_t, storm::storage::Distribution<PolicyValueType, uint64_t>> result;
255
256 // Iterate all POMDP states and group by observation id.
257 const uint64_t numStates = pomdp.getNumberOfStates();
258 std::vector<uint64_t> representativeStates(pomdp.getNrObservations(), numStates);
259 for (uint64_t state = 0; state < numStates; ++state) {
260 // Get the observation id for this state.
261 uint64_t obs = pomdp.getObservation(state);
262
263 // Within a fixed scheduler memory state, a single FSC output must represent all states of this observation.
264 auto& representativeState = representativeStates[obs];
265 if (representativeState != numStates) {
266 STORM_LOG_THROW(std::ranges::equal(scheduler.getChoice(state, memoryState).getChoiceAsDistribution(),
267 scheduler.getChoice(representativeState, memoryState).getChoiceAsDistribution()),
268 storm::exceptions::IllegalArgumentException,
269 "Cut-off approximation schedulers must be observation-based, but states "
270 << representativeState << " and " << state << " have different action distributions for observation " << obs
271 << " in memory state " << memoryState << ".");
272 continue;
273 }
274 representativeState = state;
275
276 // Build distribution from the scheduler choice for this state.
277 auto choice = scheduler.getChoice(state, memoryState).template toValueType<PolicyValueType>();
278 storm::storage::Distribution<PolicyValueType, uint64_t> dist = choice.getChoiceAsDistribution();
279
280 result.emplace(obs, std::move(dist));
281 }
282
283 return result;
284}
285
286template class PolicyExtractor<models::sparse::Pomdp<double>, double, double>;
287template class PolicyExtractor<storm::models::sparse::Pomdp<double>, storm::RationalNumber, double>;
288template class PolicyExtractor<storm::models::sparse::Pomdp<storm::RationalNumber>, storm::RationalNumber, storm::RationalNumber>;
289template class PolicyExtractor<storm::models::sparse::Pomdp<storm::RationalNumber>, storm::RationalNumber, double>;
290template class PolicyExtractor<storm::models::sparse::Pomdp<double>, double, storm::RationalNumber>;
291template class PolicyExtractor<storm::models::sparse::Pomdp<double>, double, double, storm::RationalNumber>;
292
293} // namespace storm::pomdp::policy
This class manages the labeling of the choice space with a number of (atomic) labels.
void addLabelToChoice(std::string const &label, uint64_t choice)
Adds a label to a given choice.
void addLabel(std::string const &label)
Adds a new label to the labelings.
void removeLabel(std::string const &label)
Removes a label from the labelings.
This class represents a (discrete-time) Markov decision process.
Definition Mdp.h:16
std::shared_ptr< storm::models::sparse::Model< ValueType, RewardModelType > > applyScheduler(storm::storage::Scheduler< ValueType > const &scheduler, bool dropUnreachableStates=true, bool preserveModelType=false) const
Applies the given scheduler to this model.
This class manages the labeling of the state space with a number of (atomic) labels.
bool getStateHasLabel(std::string const &label, storm::storage::sparse::state_type state) const
Checks whether a given state is labeled with the given label.
void addLabelToState(std::string const &label, storm::storage::sparse::state_type state)
Adds a label to a given state.
A finite-state controller (FSC) for POMDPs that bases its decisions on observations.
void addDeterministicActionTransition(uint64_t originId, uint64_t observationId, uint64_t actionId, uint64_t targetId)
Adds a deterministic output for an observation in a memory node.
void addRandomisedActionTransition(uint64_t originId, uint64_t observationId, storm::storage::Distribution< ValueType, uint64_t > actionDistribution, uint64_t targetId)
Adds a randomised output for an observation in a memory node.
PolicyExtractor(PomdpModelType const &pomdp, BeliefMdpType const &beliefMdp, std::unordered_map< uint64_t, uint32_t > const &beliefStateToObservationMap, storm::storage::Scheduler< BeliefMdpValueType > const &beliefMdpScheduler, std::optional< std::vector< storm::storage::Scheduler< typename PomdpModelType::ValueType > > > const &pomdpApproximationSchedulers=std::nullopt)
Creates an extractor for a scheduler on a belief MDP.
ObservationBasedFiniteStateController< PolicyValueType > exportPolicyAsFiniteStateController() const
Constructs an observation-based finite-state controller from the belief-MDP scheduler.
std::shared_ptr< ModelType > exportPolicyAsInducedMarkovChain() const
Constructs the Markov chain induced by the belief-MDP scheduler.
This class defines which action is chosen in a particular state of a non-deterministic model.
Definition Scheduler.h:18
SchedulerChoice< ValueType > const & getChoice(uint_fast64_t modelState, uint_fast64_t memoryState=0) const
Gets the choice defined by the scheduler for the given model and memory state.
Definition Scheduler.cpp:94
A class that holds a possibly non-square matrix in the compressed row storage format.
const_rows getRow(index_type row) const
Returns an object representing the given row.
void dropZeroEntries()
Removes all zero entries from this.
void makeRowDirac(index_type row, index_type column, bool dropZeroEntries=false)
This function makes the given row Dirac.
std::vector< index_type > const & getRowGroupIndices() const
Returns the grouping of rows of this matrix.
#define STORM_LOG_WARN(message)
Definition logging.h:35
#define STORM_LOG_ASSERT(cond, message)
Definition macros.h:9
#define STORM_LOG_THROW(cond, exception, message)
Definition macros.h:39
static ObservationSignature fromValuations(storm::storage::sparse::Valuations const &observationValuations, uint64_t observationId)
Builds a signature from a POMDP observation valuation.
std::optional< storm::models::sparse::ChoiceLabeling > choiceLabeling