Solving your first model in Python¶
LocalSolver is implemented in C++ language. Nevertheless, object-oriented APIs are provided for Python 2.7, 3.2 or 3.4, allowing a full integration of LocalSolver in your Python business applications. LocalSolver’s APIs are lightweight, with only a few classes to manipulate. Remind that LocalSolver is a black-box math programming solver: having instantiated the model, no additional code has to be written in order to run the solver.
Below is given the Python code for solving the knapsack toy instance introduced
during the Quick tour of LocalSolver’s modeler.
The corresponding source file can be retrieved in /examples/toy
.
A small example¶
########## toy.py ##########
import localsolver
import sys
with localsolver.LocalSolver() as ls:
weights = [10, 60, 30, 40, 30, 20, 20, 2]
values = [1, 10, 15, 40, 60, 90, 100, 15]
knapsackBound = 102
#
# Declares the optimization model
#
m = ls.model
# 0-1 decisions
x = [m.bool() for i in range(0,8)]
# weight constraint
knapsackWeight = m.sum(weights[i]*x[i] for i in range(0,8))
m.constraint(knapsackWeight <= knapsackBound)
# maximize value
knapsackValue = m.sum(values[i]*x[i] for i in range(0,8))
m.maximize(knapsackValue)
m.close()
# Parameterizes the solver
ls.param.nb_threads = 2
if len(sys.argv) >= 2: ls.create_phase().time_limit = int(sys.argv[1])
else: ls.create_phase().time_limit = 10
ls.solve()
You can observe that the structure of the Python program follows the structure of corresponding LSP. First, we read input data. Then, we declare the knapsack model by creating some expressions. Once the model is closed, we can parameterize the search before launching the solver.
Compiling and running the Python program¶
A Python distribution must be installed on your computer. LocalSolver is compatible with Python 2.7, 3.2 and 3.4.
On Windows, the above program is launched using the following lines:
set PYTHONPATH=%LS_HOME%\bin\python27\
python toy.py
On Linux or Mac OS, the above program is compiled and launched using the following lines:
export PYTHONPATH=/opt/localsolver_XXX/bin/python27/
python toy.py
If you have some troubles in compiling or launching the program, please have a look to the Installation & licensing instructions. We invite users willing to go further with APIs to consult the Python API Reference.