Python MIP
Python-MIP (Mixed-Integer Programming) is a Python library for modeling and solving Mixed-Integer Linear Programs (MIPs). It provides a high-level, intuitive API inspired by Pulp, offering access to advanced solver features like cut generation, lazy constraints, and solution pools. The library integrates with popular open-source solvers like COIN-OR CBC and HiGHS, as well as the commercial Gurobi solver. It is actively maintained, with version 1.17.6 being the latest, and aims for high performance and extensibility, supporting Python 3.10+ and PyPy for faster model generation.
Common errors
-
OptimizationStatus.ERROR
cause The solver encountered an unrecoverable error at a low level, often without a specific Python exception. This could be due to memory issues, inconsistent model data, or solver bugs.fixInspect the model for inconsistencies (e.g., conflicting constraints, incorrect bounds). Try a simpler version of the model to isolate the issue. Ensure `mip` and its solver dependencies are up to date. Check for solver-specific log files if enabled. -
RuntimeError: maximum recursion depth exceeded while calling a Python object
cause This typically occurs when constructing very large, deeply nested expressions or lists of variables/constraints in a recursive manner, exceeding Python's default recursion limit.fixRefactor model construction to use iterative loops instead of recursion where possible. For expressions, leverage `mip.xsum()` for summations. If necessary, `sys.setrecursionlimit()` can be increased, but this is generally not recommended as a primary fix. -
Model construction is very slow for large problems.
cause Python-MIP's overhead for creating variables and expressions, particularly due to internal object instance checks and Python's dynamic nature, can be a bottleneck for extremely large models.fixProfile your code to pinpoint exact bottlenecks. Ensure you're using efficient methods like `m.add_var_tensor()` for blocks of variables and `xsum()` for summations. Consider generating model data using NumPy/Pandas and then efficiently transferring it to the MIP model. For extremely large models, sometimes other modeling tools or direct solver APIs might offer faster model construction if that is the primary bottleneck. -
Crashes on Windows with 'Faulting module name: msvcrt.dll' or similar DLL errors.
cause Older versions of `python-mip` sometimes shipped with outdated or incompatible CBC solver binaries, leading to instability on certain Windows systems.fixUpdate `python-mip` to the latest version (`pip install --upgrade mip`). Version 1.13.0 and newer include updated CBC binaries which improved stability. If the problem persists, ensure your C++ redistributables are up to date.
Warnings
- gotcha For large-scale models, problem setup (defining variables and constraints) in Python-MIP can be noticeably slower compared to other modeling libraries like CVXPY due to internal object instance checks.
- gotcha When `model.optimize()` returns `OptimizationStatus.ERROR`, it indicates a problem at a deeper system level (e.g., within the solver's C library) which often doesn't raise a Python exception. This makes debugging difficult.
- gotcha Older versions of `python-mip` (pre-1.13.0) on Windows could experience silent crashes (e.g., 'Faulting module name: msvcrt.dll') when solving complex models, often related to older CBC binaries.
- deprecated Python-MIP officially supports Python 3.10 and newer. While older versions might work with Python 3.7-3.9, compatibility may not be guaranteed, and new features (like HiGHS solver support) might require newer Python versions.
- breaking Version 1.17.x introduced full, first-class support for the HiGHS solver, replacing any prior experimental or pre-release integrations. While a major improvement, users who were relying on specific (potentially undocumented) HiGHS configurations in older pre-release versions might need to adjust their code.
Install
-
pip install mip -
pip install mip gurobipy
Imports
- Model
from mip import Model
- xsum
from mip import xsum
- maximize
from mip import maximize
- MINIMIZE
from mip import MINIMIZE
- BINARY
from mip import BINARY
Quickstart
from mip import Model, xsum, maximize, BINARY, OptimizationStatus
# 0/1 Knapsack Problem example
p = [10, 13, 18, 31, 7, 15] # profits
w = [11, 15, 20, 35, 10, 33] # weights
c, I = 47, range(len(w)) # capacity, items index
m = Model("knapsack")
x = [m.add_var(var_type=BINARY, name=f'x_{i}') for i in I]
m.objective = maximize(xsum(p[i] * x[i] for i in I))
m += xsum(w[i] * x[i] for i in I) <= c
status = m.optimize()
if status == OptimizationStatus.OPTIMAL:
selected_items = [i for i in I if x[i].x >= 0.99]
print(f"Selected items: {selected_items}")
print(f"Total profit: {m.objective_value}")
print(f"Total weight: {sum(w[i] for i in selected_items)}")
elif status == OptimizationStatus.FEASIBLE:
print("Solution found, but not necessarily optimal.")
elif status == OptimizationStatus.INFEASIBLE:
print("Model is infeasible.")
elif status == OptimizationStatus.UNBOUNDED:
print("Model is unbounded.")
else:
print(f"Optimization status: {status}")