Scheduler
transitionMatrix.cpp
Go to the documentation of this file.
1 
10 #include "transitionMatrix.h"
11 
12 #include <iomanip>
13 #include <ostream>
14 #include <stdexcept>
15 #include <utils/randomGenerator.h>
16 
17 
18 
19 using namespace Mdp;
20 
21 
22 TransitionMatrix::TransitionMatrix(int S, int A) : nbOfStates(S), nbOfActions(A)
23 {
24 }
25 
27 {
28  if (matrix != nullptr)
29  delete[] matrix;
30 }
31 
32 
33 
35 {
36  if (from >= nbOfStates || to >= nbOfStates || action >= nbOfStates)
37  throw std::runtime_error("invalid value for matrix parameters");
38  return getArray()[from*nbOfStates*nbOfActions + action*nbOfStates + to];
39 }
40 
41 double TransitionMatrix::get(size_t stateAndAction, state_t to)
42 {
43  if (stateAndAction >= nbOfStates*nbOfActions || to >= nbOfStates)
44  throw std::runtime_error("invalid value for matrix parameters");
45  return getArray()[stateAndAction * nbOfStates + to];
46 }
47 
48 
49 void TransitionMatrix::set(state_t from, state_t to, action_t action, double proba)
50 {
51  if (from >= nbOfStates || to >= nbOfStates || action >= nbOfActions)
52  throw std::runtime_error("invalid value for matrix parameters");
53  getArray()[from*nbOfStates*nbOfActions + action*nbOfStates + to] = proba;
54 }
55 
56 
57 void TransitionMatrix::initializeRandomly(std::shared_ptr<Utils::RandomGenerator> gen)
58 {
59  for (state_t i = 0; i < nbOfStates; i++)
60  {
61  for (action_t j = 0; j < nbOfActions; j++)
62  {
63  std::vector<double> vector = gen->drawDistribution(nbOfStates);
64  for (state_t k = 0; k < nbOfStates; k++)
65  {
66  set(i, k, j, vector[k]);
67  }
68  }
69  }
70 }
71 
72 
73 void TransitionMatrix::print(std::ostream& stream)
74 {
75  if (matrix == nullptr)
76  {
77  stream << "(Transition matrix was not created)\n";
78  return;
79  }
80  stream << "Transition Matrix:\n";
81  for (state_t i = 0; i < nbOfStates; i++)
82  {
83  stream << "From state " << i <<"\n";
84  for (action_t j = 0; j < nbOfActions; j++)
85  {
86  stream << " With action " << j << ": ";
87  for (state_t k = 0; k < nbOfStates; k++)
88  {
89  stream << std::fixed << std::setfill(' ') << getArray()[i*nbOfActions*nbOfStates + j*nbOfStates + k] <<" ";
90  }
91  stream << "\n";
92  }
93  }
94 }
95 
96 
97 
98 
99 double *TransitionMatrix::getArray()
100 {
101  if (matrix == nullptr)
102  {
103  matrix = new double[nbOfStates*nbOfStates*nbOfActions];
104  }
105  return matrix;
106 }
107 
108 
109 
110 
111 
112 
113 
114 
void print(std::ostream &stream)
const size_t A
const size_t S
void set(state_t from, state_t to, action_t action, double proba)
TransitionMatrix(int nbOfStates, int nbOfActions)
double get(state_t from, state_t to, action_t action)
size_t action_t
Definition: action_impl.h:18
void initializeRandomly(std::shared_ptr< Utils::RandomGenerator > gen)
Definition: action.h:18
size_t state_t
Definition: state.h:19