Solving your first model in Python

LocalSolver is implemented in C++ language. Nevertheless, object-oriented APIs are provided for Python, allowing a full integration of LocalSolver in your Python business applications. LocalSolver’s APIs are lightweight, with only a few classes to manipulate. Note that LocalSolver is a model-and-run math programming solver: having instantiated the model, no additional code has to be written in order to run the solver.

Note

Once you have installed LocalSolver on your computer, the recommended way to link LocalSolver to your Python installation, is to type the following command in a command prompt or in the prompt of your Python environment (Anaconda for instance):

pip install localsolver -i https://pip.localsolver.com

Note that it only configures the integration of LocalSolver in Python. It is not a substitute for a proper installation of LocalSolver with a LocalSolver license. This command must be executed each time you install a new version of LocalSolver.

In this section, we show you how to model and solve your first problem in Python: the optimization of the shape of a bucket. With a limited surface of material (S=π), we try to build a bucket that holds the largest volume.

This small example is more precisely described in our example tour. Here our main goal is to learn how to write and launch a model.

Writing the model

Below is the Python program which models this non linear problem (see examples/optimal_bucket).

########## optimal_bucket.py ##########

import localsolver
import sys

with localsolver.LocalSolver() as ls:

    PI = 3.14159265359

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

    # Numerical decisions
    R = m.float(0, 1)
    r = m.float(0, 1)
    h = m.float(0, 1)
    
    # Surface must not exceed the surface of the plain disc
    surface = PI*r**2 + PI*(R+r)*m.sqrt((R - r)**2 + h**2)
    m.constraint(surface <= PI)

    # Maximize the volume
    volume = PI*h/3*(R**2 + R*r + r**2)
    m.maximize(volume)

    m.close()

    #
    # Param
    #
    if len(sys.argv) >= 3: ls.param.time_limit = int(sys.argv[2])
    else: ls.param.time_limit = 2

    ls.solve()

    #
    # Writes the solution in a file with the following format:
    #  - surface and volume of the bucket
    #  - values of R, r and h
    #
    if len(sys.argv) >= 2:
        with open(sys.argv[1], 'w') as f:
            f.write("%f %f\n" % (surface.value, volume.value))
            f.write("%f %f %f\n" % (R.value, r.value, h.value))

After creating the LocalSolver environment LocalSolver(), all the decision variables of the model, are declared with function float() (or also bool(), int(), set(), list()). Intermediate expressions can be built upon these decision variables by using other operators or functions. For example, in the model above: power (pow), square root (sqrt), less than or equal to (<=). Many other mathematical operators are available, allowing you to model and solve highly-nonlinear combinatorial optimization problems. The functions constraint or maximize are used for tagging expressions as constrained or maximized.

Running the Python program

A Python distribution must be installed on your computer. LocalSolver is compatible with Python 2.7 and Python >= 3.3.

On any system, if you applied the recommended pip install procedure described above, your Python program is direclty launched with:

python optimal_bucket.py

Then, the following trace will appear in your console:

LocalSolver 9.5.20200409-Win64. All rights reserved.
Load .\optimal_bucket.lsp...
Run model...
Run param...
Run solver...

Model:  expressions = 26, decisions = 3, constraints = 1, objectives = 1
Param:  time limit = 2 sec, no iteration limit

[objective direction ]:     maximize

[  0 sec,       0 itr]:            0
[ optimality gap     ]:         100%
[  0 sec,   42898 itr]:      0.68709
[ optimality gap     ]:      < 0.01%

42898 iterations performed in 0 seconds

Optimal solution:
  obj    =      0.68709
  gap    =      < 0.01%
  bounds =     0.687189

If no time limit is set, the search will continue until optimality is proven (Optimal solution message) or until you force the stop of the program by pressing Ctrl+C. The trace in console starts with the key figures of the model: number of expressions, decisions, constraints and objectives.

Once the search is finished, the total number of iterations and the elapsed time are displayed, as well as the status and the value of the best solution found. The solution status can be Inconsistent, Infeasible, Feasible or Optimal.

If you have trouble compiling or launching the program, please have a look at the Installation & licensing instructions. We invite users willing to go further with APIs to consult the Python API Reference.

Running LocalSolver without pip

If you don’t have pip or if you don’t want to use pip, executing your program will require setting the PYTHONPATH environment variable beforehand, and the lauching lines will depend on your system. If you are using a Python development environment, its settings page allows configuring the PYTHONPATH environment variable. Otherwise you can proceed as follows:

  • In a Windows command prompt you will type
    set PYTHONPATH=%LS_HOME%\bin\python
  • In a Windows PowerShell console you will type
    $env:PYTHONPATH=”$env:LS_HOME\bin\python”
  • On linux of MacOS, the command is
    export PYTHONPATH=/opt/localsolver_10_5/bin/python