Debian Codegraph @

doc/source/guides/how_to_configure_solvers.rst

raw
1 How to configure a solver in PuLP
2 ======================================
3
4 A typical problem PuLP users have is trying to connect to a solver that is installed in their pc. Here, we show the main concepts and ways to be sure PuLP can talk to the solver in question.
5
6 Checking which solvers PuLP has access to
7 ------------------------------------------------
8
9 PuLP has some helper functions that permit a user to query which solvers are available and initialize a solver from its name.
10
11 .. code-block:: python
12
13 import pulp as pl
14 solver_list = pl.listSolvers()
15 # ['GLPK_CMD', 'PYGLPK', 'CPLEX_CMD', 'CPLEX_PY', 'CPLEX_DLL', 'GUROBI', 'GUROBI_CMD', 'MOSEK', 'XPRESS', 'PULP_CBC_CMD', 'COIN_CMD', 'COINMP_DLL', 'CHOCO_CMD', 'MIPCL_CMD', 'SCIP_CMD']
16
17 If passed the `only_available=True` argument, PuLP lists the solvers that are currently available::
18
19 import pulp as pl
20 solver_list = pl.listSolvers(onlyAvailable=True)
21 # ['GLPK_CMD', 'CPLEX_CMD', 'CPLEX_PY', 'GUROBI', 'GUROBI_CMD', 'PULP_CBC_CMD', 'COIN_CMD']
22
23 Also, it's possible to get a solver object by using the name of the solver. Any arguments passed to this function are passed to the constructor:
24
25 .. code-block:: python
26
27 import pulp as pl
28 solver = pl.getSolver('CPLEX_CMD')
29 solver = pl.getSolver('CPLEX_CMD', timeLimit=10)
30
31 In the next sections, we will explain how to configure a solver to be accessible by PuLP.
32
33 What is an environment variable
34 --------------------------------------
35
36 An environment variable is probably better explained `somewhere else <https://en.wikipedia.org/wiki/Environment_variable>`_. For the sake of this document, it is a text value stored during your session that allows you to configure some applications that make use of them. For example, when you write:
37
38 python
39
40 in your command line, it usually opens a python console. But how did your computer know where to find python? It knew because there is an environment variable call "PATH" that stores a list of locations in your hard-drive where your pc looks for executables that match the thing you write.
41
42 It has many advantages such as not leaving any trace in the pc and being fairly cross-platform, among many others.
43
44 Types of PuLP integrations (API) to solvers
45 --------------------------------------------------------
46
47 API means "Application Programming Interface". PuLP has usually several ways to connect to solvers. Depending on the way it connects to the solver, configuring the connection may vary. We can summarize the integrations in two big groups:
48
49 * Using the command line interface of the solver.
50 * Using the python library of the solver.
51
52 Not all solvers have a python library, but most have a command line interface. If you want to know which one are you using it's easy. If the name of the solver API ends with ``CMD`` (such as ``PULP_CBC_CMD``, ``CPLEX_CMD``, ``GUROBI_CMD``, etc.) it's the former. Otherwise, it is the latter.
53
54 Configuring the path to the solver
55 --------------------------------------------
56
57 In order for PuLP to be able to use a solver via the CMD API, the solver needs to be executed by PuLP via the command line. For this to happen one of two things is needed:
58
59 1. The user passes the path to the solver to the solver initialization.
60 2. The user has configured the PATH environment variable to the directory where the solver is.
61
62 **We will do the example for CPLEX in Windows, but the idea is the same for other solvers and other Operating Systems**.
63
64 Both options imply knowing where the solver is. So first we have to go look for it in the pc. Mine is in ``C:\Program Files\IBM\ILOG\CPLEX_Studio128\cplex\bin\x64_win64\cplex.exe``.
65
66 Imagine using the ``CPLEX_CMD`` solver, the first one is really simple:
67
68 .. code-block:: python
69
70 path_to_cplex = r'C:\Program Files\IBM\ILOG\CPLEX_Studio128\cplex\bin\x64_win64\cplex.exe'
71 import pulp as pl
72 model = pl.LpProblem("Example", pl.LpMinimize)
73 solver = pl.CPLEX_CMD(path=path_to_cplex)
74 _var = pl.LpVariable('a')
75 _var2 = pl.LpVariable('a2')
76 model += _var + _var2 == 1
77 result = model.solve(solver)
78
79 The only to do was to look for the 'cplex.exe' file (in Windows, although in Linux and Mac is something similar but with 'cplex') and pass the absolute path to the solver.
80
81 The second one is a little more cumbersome but you only do it once per machine. You need to configure the ``PATH`` environment variable to include the path to the ``C:\Program Files\IBM\ILOG\CPLEX_Studio128\cplex\bin\x64_win64`` directory.
82
83 Here is one random guide to editing environment variables in: `Windows <https://opentechguides.com/how-to/article/windows-10/113/windows-10-set-path.html>`_ or `Linux or Mac <https://askubuntu.com/questions/730/how-do-i-set-environment-variables>`_. The idea is that once it is correctly configured you can forget about it (until you change pc or solver version).
84
85 Once we have done that, we just do something very similar to the previous example:
86
87 .. code-block:: python
88
89 import pulp as pl
90 model = pl.LpProblem("Example", pl.LpMinimize)
91 solver = pl.CPLEX_CMD()
92 _var = pl.LpVariable('a')
93 _var2 = pl.LpVariable('a2')
94 model += _var + _var2 == 1
95 result = model.solve(solver)
96
97 The only difference is that we do not need to tell PuLP where the solver is. The system will find it using the ``PATH`` environment variable just as the ``python`` example above. Magic!
98
99 Additional environment variables per solver
100 ------------------------------------------------
101
102 Sometimes, giving the path to the solver is not enough. This can be because the solver needs to know where other files are found (dynamic libraries it will use when running) or the PuLP API needs to import some specific python packages that are deployed with the solver (in case of the solvers that do not have a ``_CMD`` at the end).
103
104 Whatever the reason, it's better to be safe than sorry and this means knowing what variables are usually used by which solver. Here are the necessary environment variables that are needed for each solver. The procedure is very similar to what we did with the ``PATH`` variable: sometimes you need to edit an existing environment variable and sometimes you need to create a new environment variable. So it looks explicit, I will be using my own paths to variables, but you will have to adapt them to your actual paths (e.g., if the version of the solver is not the same). I will be using my **Linux paths, since it just implies copying the last lines of my ~.bashrc file**. I've adapted them to the Windows command line but, preferably, you would like to edit them via the GUI in windows.
105
106
107 CPLEX
108 *******
109
110 **Linux / Mac: add the following lines to the ~.bashrc (or ~.profile or /etc/profile or /etc/bash.bashrc) file**::
111
112 export CPLEX_HOME="/opt/ibm/ILOG/CPLEX_Studio128/cplex"
113 export CPO_HOME="/opt/ibm/ILOG/CPLEX_Studio128/cpoptimizer"
114 export PATH="${PATH}:${CPLEX_HOME}/bin/x86-64_linux:${CPO_HOME}/bin/x86-64_linux"
115 export LD_LIBRARY_PATH="${LD_LIBRARY_PATH}:${CPLEX_HOME}/bin/x86-64_linux:${CPO_HOME}/bin/x86-64_linux"
116 export PYTHONPATH="${PYTHONPATH}:/opt/ibm/ILOG/CPLEX_Studio128/cplex/python/3.5/x86-64_linux"
117
118 **Windows: add the following environment variables (via the command line or the graphical user interface)**::
119
120 set CPLEX_HOME=C:/Program Files/IBM/ILOG/CPLEX_Studio128/cplex
121 set CPO_HOME=C:/Program Files/IBM/ILOG/CPLEX_Studio128/cpoptimizer
122 set PATH=%PATH%;%CPLEX_HOME%/bin/x64_win64;%CPO_HOME%/bin/x64_win64
123 set LD_LIBRARY_PATH=%LD_LIBRARY_PATH%;%CPLEX_HOME%/bin/x64_win64;%CPO_HOME%/bin/x64_win64
124 set PYTHONPATH=%PYTHONPATH%;/opt/ibm/ILOG/CPLEX_Studio128/cplex/python/3.5/x64_win64
125
126 GUROBI
127 *******
128
129 **Linux / Mac: add the following lines to the ~.bashrc (or ~.profile or /etc/profile or /etc/bash.bashrc) file**::
130
131 export GUROBI_HOME="/opt/gurobi801/linux64"
132 export PATH="${PATH}:${GUROBI_HOME}/bin"
133 export LD_LIBRARY_PATH="${GUROBI_HOME}/lib"
134
135 **Windows: add the following environment variables (via the command line or graphical user interface)**::
136
137 set GUROBI_HOME=/opt/gurobi801/linux64
138 set PATH=%PATH%;%GUROBI_HOME%/bin
139 set LD_LIBRARY_PATH=%LD_LIBRARY_PATH%;%GUROBI_HOME%/lib
140
141
142 Configuring where the CMD solvers write their temporary files
143 ---------------------------------------------------------------------------
144
145 In the case of solver APIs that use the command line (again, those that end in ``CMD``, sometimes a user wants to control where the files are written. There are plenty of options.
146
147 By default, PuLP does not keep the intermediary files (the \*.mps, \*.lp, \*.mst, \*.sol) and they are written in a temporary directory of the operating system. PuLP looks for the TEMP, TMP and TMPDIR environment variables to write the file (in that order). After using them, PuLP deletes them. If you change any of these environment variables before solving, you should be able to choose where you want PuLP to write the results.
148
149 .. code-block:: python
150
151 import pulp as pl
152 model = pl.LpProblem("Example", pl.LpMinimize)
153 _var = pl.LpVariable('a')
154 _var2 = pl.LpVariable('a2')
155 model += _var + _var2 == 1
156 solver = pl.PULP_CBC_CMD()
157 result = model.solve(solver)
158
159 Another option, is passing the argument `keepFiles=True` to the solver. With this, the solver creates the files in the current directory and they are not deleted (although they will be overwritten if you re-execute).
160
161 .. code-block:: python
162
163 import pulp as pl
164 model = pl.LpProblem("Example", pl.LpMinimize)
165 _var = pl.LpVariable('a')
166 _var2 = pl.LpVariable('a2')
167 model += _var + _var2 == 1
168 solver = pl.PULP_CBC_CMD(keepFiles=True)
169 result = model.solve(solver)
170
171 Finally, one can manually edit the tmpDir attribute of the solver object before actually solving.
172
173 .. code-block:: python
174
175 import pulp as pl
176 model = pl.LpProblem("Example", pl.LpMinimize)
177 _var = pl.LpVariable('a')
178 _var2 = pl.LpVariable('a2')
179 model += _var + _var2 == 1
180 solver = pl.PULP_CBC_CMD()
181 solver.tmpDir = 'PUT_SOME_ALTERNATIVE_PATH_HERE'
182 result = model.solve(solver)
183
184
185 Using the official solver API
186 -----------------------------------------
187
188 PuLP has the integrations with the official python API solvers for the following solvers:
189
190 * Mosek (MOSEK)
191 * Gurobi (GUROBI)
192 * Cplex (CPLEX_PY)
193
194 These API offer a series of advantages over using the command line option:
195
196 * They are usually faster to initialize a problem (they do not involve writing files to disk).
197 * They offer a lot more functionality and information (extreme rays, dual prices, reduced costs).
198
199 Installing CPLEX_PY
200 ***********************
201
202 For this solver to work there are two options:
203
204 1. Installing the python package that comes with the CPLEX installation (it is not installed automatically).
205 2. (**recomended**) Adding the path to the package to the ``PYTHON_PATH`` environment variable.
206
207 The second step is already shown in the example above. The first one requires admin rights, the second one does not.
208
209 Installing GUROBI
210 ***********************
211
212 For this solver to work, the only option is to install the python package that comes with the gurobi installation.
213
214 Following my installation paths it would be (Linux):
215
216 cd /opt/gurobi801/linux64/
217 sudo python3 setup.py install
218
219 As you can see, it is necessary to have admin rights to install it.
220
221 Using solver-specific functionality
222 **********************************************
223
224 In order to access this functionality, the user needs to use the solver object included inside the PuLP problem. PuLP uses the ``solverModel`` attribute on the problem object. This attribute is created and filled when the method ``buildSolverModel()`` is executed.
225
226 For example, using the ``CPLEX_PY`` API we can access the api object after the solving is done:
227
228 .. code-block:: python
229
230 import pulp
231
232 x = pulp.LpVariable('x', lowBound=0)
233 prob = pulp.LpProblem('name', pulp.LpMinimize)
234 prob += x
235
236 solver = pulp.CPLEX_PY()
237 status = prob.solve(solver)
238 # you can now access the information from the cplex API python object
239 prob.solverModel
240
241 Also, you can access the python api object before solving by using the lower-level methods:
242
243 .. code-block:: python
244
245 import pulp
246
247 x = pulp.LpVariable('x', lowBound=0)
248 prob = pulp.LpProblem('name', pulp.LpMinimize)
249 prob += x
250
251 solver = pulp.CPLEX_PY()
252 solver.buildSolverModel(prob)
253 # you can now edit the object or do something with it before solving
254 # for example, load a MIP_START file for CPLEX_PY:
255 solver.solverModel.MIP_starts.read(SOME_MST_FILE)
256 # the, you can call the solver to solve the problem
257 solver.callSolver(prob)
258 # finally, you fill the PuLP variables with the solution
259 status = solver.findSolutionValues(prob)
260
261 For more information on how to use the `solverModel`, one needs to check the official documentation depending on the solver.
262
263
264 Importing and exporting a solver
265 -----------------------------------
266
267 Exporting a solver can be useful to backup the configuration that was used to solve a model.
268
269 In order to export it one needs can export it to a dictionary or a json file::
270
271 import pulp
272 solver = pulp.PULP_CBC_CMD()
273 solver_dict = solver.toDict()
274
275 The structure of the returned dictionary is quite simple::
276
277 {'keepFiles': 0,
278 'mip': True,
279 'msg': True,
280 'options': [],
281 'solver': 'PULP_CBC_CMD',
282 'timeLimit': None,
283 'warmStart': False}
284
285 It's also possible to export it directly to a json file::
286
287 solver.toJson("some_file_name.json")
288
289 In order to import it, one needs to do::
290
291 import pulp
292 solver = pulp.getSolverFromDict(solver_dict)
293
294 Or from a file::
295
296 import pulp
297 solver = pulp.getSolverFromJson("some_file_name.json")
298
299 For json, we use the base `json` package. But if `ujson` is available, we use that so the import / export can be really fast.