Skip to content

Classes and methods

Anders Reenberg Andersen edited this page Nov 12, 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.csv",
        tranMatWithZeros=list(),
        tranMatElementwise=list(),
        tranMatProbs=list(),
        tranMatColumns=list(),
        tranMatFromFile="transitions.csv")
  • 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).
  • list rewards: A 2D-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]. Note that states do not need to contain the same number of actions.
  • list rewardsElementwise: Alternative reward format. A 2D-list where each row corresponds to a combination of a state and an action. The 2D-list 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 comma-separated (,) file, e.g. rewardsFromFile = "rewards.csv". 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. We assume the file follows the elementwise format, described above, and contains a header on the first line, e.g. state,action,reward.
  • list tranMatWithZeros: A 3D-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.
  • list tranMatElementwise: Sparse transition probabilities (option 1). A 2D-list where each row corresponds to a combination of a current state, an action, and a next state. The 2D-list 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.
  • list tranMatProbs: Sparse transition probabilities (option 2, part 1). A 3D-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]. See the example in our Quick start guide.
  • list tranMatColumns: Sparse transition probabilities (option 2, part 2). A 3D-list containing the columns of the non-zero transition probabilities defined in the list tranMatProbs (see above). 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 = tranMatProbs[sidx][aidx][i]. See the example in our Quick start guide.
  • string tranMatFromFile: Load the transition probabilities from a comma-separated (,) file, e.g. tranMatFromFile = "transitions.csv". 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. We assume the file follows the elementwise format (see tranMatElementwise), and contains a header on the first line, e.g. from_state,action,to_state,probability.

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 no 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 files are skipped). 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, 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 malformed, 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$.
  • list initPolicy: A 1D-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.
  • list initValueVector: A 1D-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.

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.

list getPolicy()

getValueVector()

Return the entire value vector.

list 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