Skip to content

Classes and methods

Anders Reenberg Andersen edited this page Nov 13, 2026 · 20 revisions

MDPSolver runs on Python but contains a solver developed in C++. This makes the package ideal for large MDPs.

The MDPSolver workflow:

  1. Create a model object (model()).
  2. Select your MDP model (mdp()).
  3. Derive an $\epsilon$-optimal policy (solve()).
  4. Get the results (see options below).

Call the methods in this order; otherwise MDPSolver stops with an error.

Model class

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.

Selecting your MDP model

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 the solve method 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 actions i = 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 .npy is read as a NumPy .npy file 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 option tranMatWithZeros, 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 as tranMatProbs, 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 (see tranMatElementwise), e.g. tranMatFromFile = "transitions.npy". A file name ending in .npy is read as a NumPy .npy file 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 $10^{-7}$, which can take the solver more iterations, and limits the tolerance it can reach under the average reward criterion.

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.

Checking the 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 $[0,1]$ or that do not sum to 1 (allowing 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()).

Solve

Derive an $\epsilon$-optimal policy for the selected MDP model.

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.

Other Python threads keep running while solve() computes, so models in several threads are solved at the same time. The calls on one model object run one at a time.

Output

The output methods below can be used once solve() has run. Before that, they stop with an error.

getAction()

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.

getValue()

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.

getPolicy()

Return the entire optimized policy, as a NumPy array with the action index (int64) of each state.

array getPolicy()

getValueVector()

Return the entire value vector, as a NumPy array with the value (float64) of each state.

array getValueVector()

printPolicy()

Print the entire policy in the terminal.

void printPolicy()

printValueVector()

Print the entire value vector in the terminal.

void printValueVector()

saveToFile()

Save the optimized policy or value vector in a comma-separated file.

void saveToFile(fileName="result.csv",type="policy")
  • string fileName: The name of the file.
  • string type: Use "policy" to save the policy and "value" to save the value vector.

getRuntime()

Return the runtime in milliseconds.

float getRuntime()

getIterations()

Return the number of iterations (i.e. policy improvement steps).

int getIterations()

hasConverged()

Return whether the last run of solve() converged.

bool hasConverged()

Clone this wiki locally