LocalSolver logo
is now
Hexaly logo

We're excited to share that we are moving forward. We're leaving behind the LocalSolver brand and transitioning to our new identity: Hexaly. This represents a leap forward in our mission to enable every organization to make better decisions faster when faced with operational and strategic challenges.

This page is for an old version of Hexaly Optimizer. We recommend that you update your version and read the documentation for the latest stable release.

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]
    knapsack_bound = 102

    #
    # Declares the optimization model
    # 
    model = ls.model

    # 0-1 decisions
    x = [model.bool() for i in range(8)]

    # weight constraint
    knapsack_weight = model.sum(weights[i]*x[i] for i in range(8))
    model.constraint(knapsack_weight <= knapsack_bound)

    # maximize value
    knapsack_value = model.sum(values[i]*x[i] for i in range(8))
    model.maximize(knapsack_value)

    model.close()

    #
    # Parameterizes the solver
    #
    ls.create_phase().time_limit = 1

    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.