Repository navigation
Classes and methods
MDPSolver runs on Python but contains a solver developed in C++. This makes the package ideal for large MDPs.
The MDPSolver workflow:
- Create a model object (
model()). - Select your MDP model (
mdp()). - Derive an
$\epsilon$ -optimal policy (solve()), or evaluate a given policy (evaluate()). - Get the results (see options below).
Use model() to create a model object. This object is used for defining your MDP model and deriving its policy.
mdl = mdpsolver.model()A model object holds one MDP model. Create a new model object for each model you want to solve.
Select a custom MDP model with user-specified parameters.
void mdp(discount=0.99,
rewards=list(),
rewardsElementwise=list(),
rewardsFromFile="rewards.npy",
tranMatWithZeros=list(),
tranMatElementwise=list(),
tranMatProbs=list(),
tranMatColumns=list(),
tranMatFromFile="transitions.npy")-
float discount: The discount (often denoted$\lambda$ ). Must be chosen such that$0 < \lambda < 1$ . Note that it only applies to the discounted reward optimality criterion (see thesolvemethod below). -
array rewards: A 2D NumPy array or list containing the reward (float) of a particular action in a particular state. The first index (rows) define the state, and the second index (columns) defines the action, e.g.r = rewards[sidx][aidx]. As a list, states do not need to contain the same number of actions. -
array rewardsElementwise: Alternative reward format. A 2D NumPy array or list where each row corresponds to a combination of a state and an action. It always contains three columns. Column 1: State indices (int), Column 2: Action indices (int), Column 3: Rewards (float). For instance,r = rewardsElementwise[i][2], where if all states contain the same number of actionsi = sidx*nActions + aidx. -
string rewardsFromFile: Load the rewards from a file in the elementwise format, described above, e.g.rewardsFromFile = "rewards.npy". A file name ending in.npyis read as a NumPy.npyfile holding a 2D array (see Loading models from NPY files), and any other name as a comma-separated (,) file with a header on the first line, e.g.state,action,reward. The file is read straight into the solver, so the rewards are not held in Python. This can be useful for several reasons: (1) If you want to generate the reward structure in a different software, (2) if you want to store your reward structure for later use, and (3) if your MDP model is large. -
array tranMatWithZeros: A 3D NumPy array or list containing the transition probabilities. The first index defines the current state, the second index defines the selected action, and the third index defines the next state, e.g.p = tranMatWithZeros[sidx][aidx][jidx]. Note that this format includes elements that are 0. -
array tranMatElementwise: Sparse transition probabilities (option 1). A 2D NumPy array or list where each row corresponds to a combination of a current state, an action, and a next state. It always contains four columns. Column 1: Current state indices (int), Column 2: Action indices (int), Column 3: Next state indices (int), Column 4: The (non-zero) transition probability (float). See the example in our Quick start guide. -
array tranMatProbs: Sparse transition probabilities (option 2, part 1). A 3D NumPy array or list containing the non-zero transition probabilities. Corresponds to the optiontranMatWithZeros, but excludes all elements that are zero. The first index defines the current state, the second index defines the selected action, and the third index is a sequence-index, e.g.p = tranMatProbs[sidx][aidx][i]. As an array, every state-action pair has the same number of entries: pad with the probability 0 and any state (e.g. 0) as the column. As a list, the pairs may have different numbers of entries. See the example in our Quick start guide. -
array tranMatColumns: Sparse transition probabilities (option 2, part 2). A 3D NumPy array or list of the same shape astranMatProbs, containing the columns of its transition probabilities. The first index defines the current state, the second index defines the selected action, and the third index is a sequence-index, e.g.c = tranMatColumns[sidx][aidx][i]. See the example in our Quick start guide. -
string tranMatFromFile: Load the transition probabilities from a file in the elementwise format (seetranMatElementwise), e.g.tranMatFromFile = "transitions.npy". A file name ending in.npyis read as a NumPy.npyfile holding a 2D array (see Loading models from NPY files), and any other name as a comma-separated (,) file with a header on the first line, e.g.from_state,action,to_state,probability. The file is read straight into the solver, so the transition probabilities are not held in Python. This can be useful for several reasons: (1) If you want to generate the transition probabilities in a different software, (2) if you want to store your transition probabilities, and (3) if your MDP model is large.
An array with the wrong number of dimensions, tranMatProbs and tranMatColumns of different shapes, or column indices that are not whole numbers stop with an error.
Transition probabilities given as a float32 array, or in a float32 .npy file, are kept as float32, which takes 8 instead of 12 bytes per non-zero probability. Rounded to float32, the probabilities of a state and action sum to 1 only to within about
Give the rewards in one format and the transition probabilities in one format. Two formats for the same input, or tranMatProbs without tranMatColumns, stop with an error. If neither an array nor a list is given for the rewards, they are read from the file rewardsFromFile (by default rewards.csv in the working directory), and likewise the transition probabilities from tranMatFromFile (by default transitions.csv). If such a file cannot be opened, mdp() stops with an error.
mdp() does not check the model, since that would cost time on every model. It only stops with an error on input that would crash it: A negative index, or a row with too few entries or an entry that cannot be read (blank lines in comma-separated files are skipped), or an .npy file that does not hold a 2D array of numbers with enough columns. To check a model, use checkModel() (below).
mdp() can only be called once per model object. A second call stops with an error. Create a new model object (mdl = mdpsolver.model()) to define another model.
Check the model for errors.
list checkModel(tolerance=1e-9)-
float tolerance: How far the transition probabilities of a state-action pair may sum from 1.
checkModel() returns one message per kind of problem found, with a count and the first examples, or an empty list if it finds none. It finds rewards and transition probabilities that cover different numbers of states or actions, states without actions, state-action pairs without transition probabilities, tranMatProbs and tranMatColumns of different shapes, next states outside the model, probabilities outside float32 probabilities their rounding), and rewards that are missing or not finite. A malformed model can crash solve() or give wrong results.
checkModel() is never called by mdp() or solve(). Call it after mdp() if you suspect that the model is incorrect, e.g. print(mdl.checkModel()).
Derive an
void solve(algorithm="mpi",
tolerance=1e-3,
update="standard",
criterion="discounted",
parIterLim=100,
SORrelaxation=1.0,
initPolicy=list(),
initValueVector=list(),
verbose=False,
postProcessing=True,
makeFinalCheck=True,
parallel=True)-
string algorithm: The optimization algorithm. Choose between"mpi"(modified policy iteration),"pi"(policy iteration), and"vi"(value iteration). -
float tolerance: The tolerance (often denoted$\epsilon$ ) employed in the optimization of the policy. Must be chosen such that$0 < \epsilon < 1$ . -
string update: The value-update method. Choose between"standard","gs"(Gauss-Seidel), and"sor"(successive over-relaxation). Choosing"standard"employs the span norm optimality criterion, whereas"gs"and"sor"employ the supremum norm optimality criterion. Only"standard"is available with the average reward criterion. -
string criterion: The optimality criterion. Choose between"discounted"and"average"reward. The average reward criterion is only available with"standard"updates. -
int parIterLim: The partial evaluation limit employed in the modified policy iteration algorithm. Must be a positive integer. -
float SORrelaxation: The relaxation parameter (often denoted$\omega$ ) employed in the successive over-relaxation value-update method. Should be chosen such that$0 < \omega < 2$ . -
array initPolicy: A 1D NumPy array or list defining the initial policy, with one element per state. Each element contains the action index (int) of the state, i.e.aidx = initPolicy[sidx], and must be a valid action of that state. This option can be used for "warm starting" the optimization procedure. Value iteration does not use the initial policy. -
array initValueVector: A 1D NumPy array or list defining the initial value vector, with one element per state. Each element contains the value (float) of the state, i.e.val = initValueVector[sidx]. This option can be used for "warm starting" the optimization procedure. -
bool verbose: Turn on/off verbose. -
bool postProcessing: Turn on/off a post processing of the value vector. If the span norm was employed, then to obtain correct estimates of the values, a post processing of the value vector is required. This process does not affect the policy and can, therefore, be turned off if the user is only interested in the resulting policy. -
bool makeFinalCheck: Turn on/off a final check of the value vector feasibility. This process is only used if the discounted reward criterion has been selected. -
bool parallel: Turn on/off parallel computing. This option is only available for the custom MDP model with"standard"updates. With"gs"and"sor"updates, the solver always runs serially.
Call mdp() before solve(). Otherwise, solve() stops with an error.
If a run does not converge, solve() issues a mdpsolver.ConvergenceWarning that says why: It stopped at the limit of 1,000,000 iterations, the values became infinite, or the final check (makeFinalCheck) found values outside the possible range. The results can still be read.
solve() can be called several times on the same model object, e.g. with another algorithm or tolerance. Every run after the first starts from the policy and the value vector of the previous run (a warm start), unless initPolicy or initValueVector replace them. Whenever a run starts from the previous one, solve() prints a note that the model has been solved before. Create a new model object to start from the initial values.
Evaluate a policy (without optimization).
void evaluate(policy=list(),
tolerance=1e-3,
update="standard",
criterion="discounted",
SORrelaxation=1.0,
initValueVector=list(),
verbose=False,
postProcessing=True,
makeFinalCheck=True,
parallel=True)-
array policy: A 1D NumPy array or list with the action index (int) of each state, i.e.aidx = policy[sidx]. Each element must be a valid action of its state. By default, the policy of the last run ofsolve()orevaluate(). -
string criterion: The optimality criterion the policy is evaluated under. Choose between"discounted"(with the discount given tomdp()) and"average"reward. -
array initValueVector: A 1D NumPy array or list with the initial value (float) of each state. By default, the evaluation starts from the values that a first run ofsolve()starts from, not from the values of an earlier run.
The remaining arguments are the same as in solve().
The output methods below can be used once solve() or evaluate() has run. Before that, they stop with an error.
Return an action from the optimized policy.
int getAction(stateIndex=0)-
int stateIndex: State index of the requested action. A state outside the model stops with an error.
Return a value from the optimized value vector.
float getValue(stateIndex=0)-
int stateIndex: State index of the requested value. A state outside the model stops with an error.
Return the entire optimized policy, as a NumPy array with the action index (int64) of each state.
array getPolicy()Return the entire value vector, as a NumPy array with the value (float64) of each state.
array getValueVector()Return the gain (the long-run average reward per period) after solve() or evaluate() with criterion="average". After a run with the discounted reward criterion, it stops with an error.
float getGain(bound=None)-
string bound:Nonereturns the midpoint between a lower and an upper bound on the gain, and"lower"or"upper"returns the bound itself. The gain of the optimized policy and the optimal gain both lie between the bounds (afterevaluate(), the gain of the evaluated policy), which are less than the tolerance apart when the run has converged.
Return the bias (the relative value) of a state after solve() or evaluate() with criterion="average". Under the average reward criterion, only the differences between the values are meaningful, so the bias of a reference state is set to 0. After a run with the discounted reward criterion, it stops with an error.
float getBias(stateIndex,referenceIndex=0)-
int stateIndex: State index of the requested bias. -
int referenceIndex: State index of the reference state, whose bias is 0.
A state outside the model stops with an error.
Print the entire policy in the terminal.
void printPolicy()Print the entire value vector in the terminal.
void printValueVector()Save the optimized policy or value vector in a NumPy .npy file or a comma-separated file.
void saveToFile(fileName=None,type="policy",filetype="npy")-
string fileName: The name of the file. By defaultresult.npy, orresult.csvwhenfiletype="csv". -
string type: Use"policy"to save the policy and"value"to save the value vector. -
string filetype: Use"npy"to save a NumPy.npyfile, whichnp.loadreads as the array thatgetPolicy()orgetValueVector()returns, and"csv"to save a comma-separated file with a header line and one row per state (the state index, then the action index or the value). Upper case, e.g."NPY", works too.
A file name ending in .csv with filetype="npy", or in .npy with filetype="csv", stops with an error.
Return the runtime in milliseconds.
float getRuntime()Return the number of iterations (i.e. policy improvement steps). After evaluate(), it is 0.
int getIterations()Return whether the last run of solve() or evaluate() converged.
bool hasConverged()