Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 22 additions & 6 deletions .github/workflows/build-wheels.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,12 @@ jobs:
strategy:
fail-fast: false
matrix:
# macos-14 = Apple Silicon (arm64) only. Intel macOS (macos-13) is
# macos-15 = Apple Silicon (arm64) only. Intel macOS is
# intentionally not built - a deliberate scope decision, not a
# limitation we hit. Users on Intel Macs get the sdist and need a
# C++ toolchain + CMake to install.
os: [ubuntu-latest, windows-latest, macos-14]
# C++ toolchain + CMake to install. (macos-14 was used until GitHub
# retired it on 2026-11-02.)
os: [ubuntu-latest, windows-latest, macos-15]
steps:
- uses: actions/checkout@v4

Expand All @@ -45,13 +46,28 @@ jobs:
# which covers essentially every machine still updated today.
CIBW_MANYLINUX_X86_64_IMAGE: manylinux_2_28
CIBW_BEFORE_ALL_MACOS: brew install libomp
# Homebrew's libomp is built for the macOS version of the runner,
# and the wheel bundles it, so the deployment target must be that
# version (delocate refuses a lower one). The macOS wheels
# therefore need macOS 15 or newer.
CIBW_ENVIRONMENT_MACOS: >
CMAKE_PREFIX_PATH=/opt/homebrew/opt/libomp
MACOSX_DEPLOYMENT_TARGET=14.0
MACOSX_DEPLOYMENT_TARGET=15.0
CIBW_TEST_REQUIRES: numpy
# cibuildwheel copies Python/tests into the temporary folder the
# tests run in. With no Python/src next to them there, the tests
# import the installed wheel as a whole (see
# Python/tests/loadmdpsolver.py), and each one ends with a line
# saying so.
CIBW_TEST_SOURCES: Python/tests
CIBW_TEST_COMMAND: >
python {project}/Python/tests/test1_pip.py &&
python {project}/Python/tests/test2_pip.py
python Python/tests/test_imports.py &&
python Python/tests/test_vi.py &&
python Python/tests/test_pi.py &&
python Python/tests/test_mpi.py &&
python Python/tests/test_random.py &&
python Python/tests/test_large.py &&
python Python/tests/test_reuse.py

- uses: actions/upload-artifact@v4
with:
Expand Down
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
/.vs
/VisualStudioProject
.vscode/
.claude/
.DS_Store
Python/.DS_Store


__pycache__/
Expand Down
22 changes: 11 additions & 11 deletions CPP_Source_Code/ModifiedPolicyIteration.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -251,8 +251,10 @@ void ModifiedPolicyIteration::mainLoopModifiedPolicyIteration(){

void ModifiedPolicyIteration::mainLoopValueIteration(){
//main loop for value iteration

if (parallel && !useSOR && genMDP) {
//(parallel computing is only available with standard updates,
//so Gauss-Seidel always uses the serial in-place routine)

if (parallel && !useSOR && !useGS && genMDP) {
parValueIterationGenMDP();
}else if(!useSOR && genMDP){
valueIterationGenMDP();
Expand Down Expand Up @@ -987,10 +989,10 @@ void ModifiedPolicyIteration::checkFinalValue() {
maxRew = 1e6; // some large positive value
}

//smallest possible value in value vector
minRew *= 1 / (1 - model->getDiscount());
//largest possible value in value vector
maxRew *= 1 / (1 - model->getDiscount());
//smallest and largest possible values in the value vector
//are widened by the tolerance
minRew = minRew / (1 - model->getDiscount()) - epsilon;
maxRew = maxRew / (1 - model->getDiscount()) + epsilon;

for (s = 0; s < model->getNumberOfStates(); ++s) {
if (isnan(valueVector->valueVector[s]) || valueVector->valueVector[s] < minRew || valueVector->valueVector[s] > maxRew){
Expand Down Expand Up @@ -1049,9 +1051,7 @@ void ModifiedPolicyIteration::computeNorm() {
diffMin=localDiffMin;
if (useStd) { //span norm
norm = diffMax - diffMin;
} else { //supremum norm
if (fabs(diff) > norm) {
norm = fabs(diff);
}
} else { //supremum norm: the largest absolute difference
norm = (diffMax > -diffMin) ? diffMax : -diffMin;
}
}
}
24 changes: 24 additions & 0 deletions CPP_Source_Code/ModuleInterface.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,8 @@ void ModuleInterface::solve(string algorithm,

//save duration (runtime) in milliseconds
results.duration=solver.duration;
//save the number of iterations (policy improvement steps)
results.iterations=solver.iter;

}

Expand Down Expand Up @@ -290,6 +292,28 @@ double ModuleInterface::getRuntime(){
return(results.duration);
}

int ModuleInterface::getIterations(){
return(results.iterations);
}

int ModuleInterface::getNumberOfStates(){
//the number of states of the general MDP model
if (problem.problemType.compare("mdp")==0){
return(problem.tranMat.numberOfRows());
}else{
return(-1);
}
}

int ModuleInterface::getNumberOfActions(int sidx){
//the number of actions of a state
if (problem.problemType.compare("mdp")==0 && sidx>=0 && sidx<problem.tranMat.numberOfRows()){
return(problem.tranMat.numberOfActions(sidx));
}else{
return(-1);
}
}

void ModuleInterface::loadTranMatWithZeros(py::list tranMatWithZeros){
vector<vector<vector<double>>> tempMat = tranMatWithZeros.cast<vector<vector<vector<double>>>>();
int cidx;
Expand Down
5 changes: 5 additions & 0 deletions CPP_Source_Code/ModuleInterface.h
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,8 @@ class ModuleInterface {
struct Results{
//duration (runtime) in milliseconds
double duration=0;
//number of iterations (policy improvement steps; every update is one with VI)
int iterations=0;
} results;


Expand Down Expand Up @@ -174,6 +176,9 @@ class ModuleInterface {
int getAction(int sidx); //returns the action index (from the optimized policy) associated with the current state
double getValue(int sidx); //returns the value (from the optimized policy) associated with the current state
double getRuntime(); //returns the runtime in milliseconds
int getIterations(); //returns the number of iterations (policy improvement steps)
int getNumberOfStates(); //returns the number of states of the general MDP model (-1 for the built-in models)
int getNumberOfActions(int sidx); //returns the number of actions of a state of the general MDP model (-1 for the built-in models or a state outside the model)
py::list getPolicy(); //returns the entire policy
py::list getValueVector(); //returns the entire value vector
void saveToFile(string fileName, string type); //save the policy or value vector to a file
Expand Down
3 changes: 3 additions & 0 deletions CPP_Source_Code/PythonModule.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,9 @@ PYBIND11_MODULE(solvermodule, m) {
py::arg("makeFinalCheck")=true,
py::arg("parallel")=true)
.def("getRuntime",&ModuleInterface::getRuntime,"Returns the runtime in milliseconds.") //OUTPUT
.def("getIterations",&ModuleInterface::getIterations,"Returns the number of iterations (policy improvement steps) of the last solve.")
.def("getNumberOfStates",&ModuleInterface::getNumberOfStates,"Returns the number of states of the general MDP model (-1 for the built-in models).")
.def("getNumberOfActions",&ModuleInterface::getNumberOfActions,"Returns the number of actions of a state of the general MDP model (-1 for the built-in models or a state outside the model).",py::arg("stateIndex")=0)
.def("printPolicy", &ModuleInterface::printPolicy,"Prints the entire policy.")
.def("printValueVector", &ModuleInterface::printValueVector,"Prints the entire value vector.")
.def("getAction", &ModuleInterface::getAction,"Returns an action index from the optimized policy.",py::arg("stateIndex")=0)
Expand Down
2 changes: 1 addition & 1 deletion Python/LICENSE
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
MIT License

Copyright (c) 2025 Anders Reenberg Andersen and Jesper Fink Andersen
Copyright (c) 2026 Anders Reenberg Andersen and Jesper Fink Andersen

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
Expand Down
2 changes: 1 addition & 1 deletion Python/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ MDPSolver is a Python package for large Markov Decision Processes (MDPs) with in

# Installation

Prebuilt wheels are available for **Linux**, **Windows**, and **macOS (14+)** across Python 3.10–3.14. Install directly from PyPI with:
Install directly from PyPI with:

```
pip install mdpsolver
Expand Down
4 changes: 2 additions & 2 deletions Python/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,12 @@ CMAKE_BUILD_TYPE = "Release"

[project]
name = "mdpsolver"
version = "0.10.2"
version = "0.10.3"
authors = [
{ name="Anders Reenberg Andersen", email="andersra@live.dk" },
{ name="Jesper Fink Andersen", email="jesperfinkandersen@gmail.com" },
]
description = "A fast solver for Markov Decision Processes"
description = "A fast Python solver for Markov Decision Processes"
readme = "README.md"
requires-python = ">=3.10"
classifiers = [
Expand Down
64 changes: 57 additions & 7 deletions Python/src/mdpsolver/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@ def __init__(self):
def initialize(self):
"""Create and initialize the solver module object."""
self.mdl = solvermodule.Model()
# A model object contains only one model
self._modelDefined = False
self._solved = False

def solve(
self,
Expand All @@ -45,35 +48,63 @@ def solve(

Args:
algorithm (str): Algorithm to use.
tolerance (float): Convergence threshold for the algorithm.
update (str): The value-update method.
tolerance (float): Convergence threshold for the algorithm (0 < tolerance < 1).
update (str): The value-update method ('standard', 'gs' or 'sor'; only 'standard' with the average reward criterion).
criterion (str): The optimality criterion.
parIterLim (int): The partial evaluation limit employed in the modified policy iteration algorithm.
SORrelaxation (float): Relaxation parameter for the Successive Over-Relaxation method.
initPolicy (list): A 1D-list defining the initial policy. This option can be used for "warm starting" the optimization procedure.
initValueVector (list): A 1D-list defining the initial value vector. This option can be used for "warm starting" the optimization procedure.
initPolicy (list): A 1D-list defining the initial policy, one valid action index per state. This option can be used for "warm starting" the optimization procedure.
initValueVector (list): A 1D-list defining the initial value vector, one value per state. This option can be used for "warm starting" the optimization procedure.
verbose (bool): If True, prints solver progress to console.
postProcessing (bool): If True, performs post-processing after solving.
makeFinalCheck (bool): If True, makes a final check of the value vector. This process checks if the resulting values are reasonable.
parallel (bool): If True, enables parallel computation for faster solving. This option is only available for the custom MDP model with standard updates.

Solving the same model object again starts from the policy and the
value vector of the previous run, unless initPolicy or initValueVector
replace them. Create a new model object to start over.

Returns:
None
"""

if not (algorithm == "mpi" or algorithm == "pi" or algorithm == "vi"):
sys.exit("Error: Algorithm type not recognized. Select either: 'mpi', 'pi', or 'vi'.")
if tolerance <= 0.0:
sys.exit("Error: The tolerance needs to be a positive number.")
if tolerance <= 0.0 or tolerance >= 1.0:
sys.exit("Error: The tolerance needs to be between 0.0 and 1.0 (i.e. 0 < tolerance < 1).")
if not (update == "standard" or update == "gs" or update == "sor"):
sys.exit("Error: Update method not recognized. Select either: 'standard', 'gs', or 'sor'.")
if not (criterion == "discounted" or criterion == "average"):
sys.exit("Error: Optimality criterion not recognized. Select either: 'discounted' or 'average'.")
if criterion == "average" and (update == "gs" or update == "sor"):
sys.exit("Error: Gauss-Seidel and SOR updates are not available with the average reward criterion. Select update='standard'.")
if parIterLim <= 0 and algorithm == "mpi":
sys.exit("Error: The partial evaluation limit needs to be a positive number.")
if (SORrelaxation <= 0.0 or SORrelaxation >= 2.0) and update == "sor":
sys.exit("Error: The relaxation parameter needs to be between 0.0 and 2.0 (i.e. 0 < SORrelaxation < 2).")

if len(initPolicy) > 0 or len(initValueVector) > 0:
numberOfStates = self.mdl.getNumberOfStates()
if numberOfStates >= 0 and len(initPolicy) > 0 and len(initPolicy) != numberOfStates:
sys.exit("Error: The initial policy needs one action index per state (the model has %d states, initPolicy has %d elements)." % (numberOfStates, len(initPolicy)))
if numberOfStates >= 0 and len(initValueVector) > 0 and len(initValueVector) != numberOfStates:
sys.exit("Error: The initial value vector needs one value per state (the model has %d states, initValueVector has %d elements)." % (numberOfStates, len(initValueVector)))
if numberOfStates >= 0 and len(initPolicy) > 0:
for stateIndex, action in enumerate(initPolicy):
numberOfActions = self.mdl.getNumberOfActions(stateIndex=stateIndex)
if not 0 <= action < numberOfActions:
sys.exit("Error: The initial policy assigns action %s to state %d, which has %d actions (indices 0 to %d)." % (action, stateIndex, numberOfActions, numberOfActions - 1))

# The solver keeps the policy and the value vector of the previous run,
# unless initPolicy or initValueVector replace them.

if self._solved:
# Value iteration never uses the policy it starts from
reusesPolicy = len(initPolicy) == 0 and algorithm != "vi"
reusesValueVector = len(initValueVector) == 0
if reusesPolicy or reusesValueVector:
print("Note: This model has been solved before. Create a new model object to run solver with initial values.", flush=True)
self._solved = True

self.mdl.solve(
algorithm=algorithm,
tolerance=tolerance,
Expand All @@ -98,6 +129,17 @@ def getRuntime(self) -> float:
"""
return self.mdl.getRuntime()

def getIterations(self) -> int:
"""
Get the number of iterations of the last solver execution.
An iteration is one policy improvement step, i.e. one update that
chooses the best action in every state.

Returns:
int: Number of iterations.
"""
return self.mdl.getIterations()

def printPolicy(self) -> None:
"""Print the entire policy to the terminal."""
self.mdl.printPolicy()
Expand Down Expand Up @@ -191,13 +233,21 @@ def mdp(
tranMatColumns (list): Sparse transition probabilities (option 2, part 2). A 3D-list containing the columns of the non-zero transition probabilities.
tranMatFromFile (str): Load the transition probabilities from a comma-separated (,) file.

A model object holds one model, so mdp() can be called only once per
model object. Create a new model object to define another model.

Returns:
None
"""

if self._modelDefined:
sys.exit("Error: A model has already been defined for this model object, and mdp() can only be called once per model object. Create a new model object (e.g. mdl = mdpsolver.model()) to define another model.")
if discount <= 0.0 or discount >= 1.0:
sys.exit("Error: The discount needs to be in the interval between 0.0 and 1.0 (i.e. 0 < discount < 1).")

# Set before loading, so that a load that fails halfway cannot be
# followed by another into the same object
self._modelDefined = True
self.mdl.mdp(
discount=discount,
rewards=rewards,
Expand Down
Loading
Loading