Debian Codegraph @

doc/KPyCon2009/PulpForPythonProgrammers.tex

raw
1 % Document History:
2 %
3 %-----------------------------------------------------------------------
4 \documentclass[a4paper,oneside]{arlimsTPPM}
5 %-------------------------------------------------------------------------
6
7 %--- Settings for the ARLIMS document class ---
8 %\setcounter{page}{8} % The starting page
9
10 %--- This part of the preamble can be fiddled with according to our needs ---
11
12 % Some packages that we like and want to use:
13 \usepackage{cite}
14 \usepackage{url}
15 \usepackage{graphicx}
16 \usepackage{color}
17 \usepackage[T1]{fontenc}
18 \usepackage[scaled]{beramono}
19
20 % For typesetting listings.
21 \usepackage{listings}
22 \lstset{% Set some listing parameters.
23 numbers=left,
24 numberstyle=\sffamily\scriptsize,
25 numberblanklines=false,
26 basicstyle=\ttfamily\footnotesize,
27 showstringspaces=false,
28 backgroundcolor=\color[rgb]{0.9,0.9,0.9},
29 %frame=tb,
30 %xleftmargin=4.3ex,
31 language=Python
32 }
33 \usepackage{hyperref}
34
35 % The path(s) to the graphics files:
36 \graphicspath{{eps/}{pdf/}}
37
38 % correct bad hyphenation here
39 %\hyphenation{cor-res-pon-ding net-works}
40
41 % This makes line breaks look prettier
42 \sloppy
43
44 % Conventions for typesetting vectors and matrices.
45 \renewcommand{\vec}[1]{\boldsymbol{#1}}
46 \newcommand{\mat}[1]{\boldsymbol{#1}}
47 % If \boldsymbol doesn't work, try \pmb (poor man's bold, which
48 % "multistrikes" every letter with small offsets.
49
50 %--- Preamble definitions for actual content ---
51
52 \title{An Introduction to pulp for Python Programmers}
53 \author{Stuart Mitchell}
54
55 \institute{
56 \begin{minipage}[t]{.45\textwidth}\centering
57 Light Metals Research Centre\\
58 University of Auckland\\
59 Auckland, New Zealand\\
60 \textnormal{\texttt{\small [email protected]}}
61 \end{minipage}}
62
63
64
65 %-------------------------------------------------------------------------
66 \begin{document}
67
68 % Put a proper title on the first page:
69 \maketitle
70
71 %-------------------------------------------------------------------------
72 \begin{abstract}
73 Pulp-or (referred to as pulp for the rest of this paper) is a linear programming framework in Python. Pulp is licensed under a modified BSD license. The aim of pulp is to allow an Operations Research (OR) practitioner or programmer to express Linear Programming (LP), and Integer Programming (IP) models in python in a way similar to the conventional mathematical notation. Pulp
74 will also solve these problems using a variety of free and non-free LP solvers. Pulp models an LP in a natural and pythonic manner.
75 This paper is aimed at the python programmer who may wish to use pulp in their code. As such this paper contains a short introduction to LP models and their uses.
76
77 % ARLIMS style
78 \paragraph{Keywords:} Linear programming; Operations Research; pulp-or.
79 \end{abstract}
80
81 %-------------------------------------------------------------------------
82 \section{Introduction}
83
84 Operations Research is known by the catch phrase ``The science of better''. From the website \cite{scienceofbetter} we find this brief description
85
86 \begin{quote}
87 In a nutshell, operations research (O.R.) is the discipline of applying advanced analytical methods to help make better decisions.
88 \end{quote}
89
90 The particular area of operations research where pulp is useful is the development and modelling of Linear Programming (LP) and Integer Programming (IP) problems. Mathematically, an LP problem is to find a point in a n-dimensional linearly constrained region that maximises a given linear objective function. IP is an LP where the solution must contain discrete variables which take an integer value at the solution, a common special case of an integer variable is a binary variable which must be either 0 or 1 at the solution.
91
92 In general terms, an LP can describe a problem were decisions must be made (for example, the quantity of each ingredient in a can of cat food, detailed in section \ref{sec:whiskas}). These decisions are constrained by the properties of the problem that they model (the total weight of ingredients must be 100 grams and dietary requirements must be met). The quality of a solution is determined by some sort of cost (the total dollar cost to produce the can) and you seek to minimise or maximise the cost subject to the constraints.
93
94
95
96 \section{A Brief introduction to Linear Programming}
97 \label{sect:LP}
98
99 In this section we will introduce the reader to the structure of an LP problem and show the syntax used to formulate these models in pulp. The following is a example LP motivated by a real-world case-study. In general, problems of this sort are called `diet' or `blending' problems. An extensive set of case studies (including those below) can be found in \cite{pulpwiki}.
100
101 \subsection{The Whiskas Cat Food Problem (whiskas.py)}
102 \label{sec:whiskas}
103
104 \begin{figure}[h]
105 \centering
106 \includegraphics{images/whiskas_label.jpg}
107 \caption{A Whiskas cat food label.}
108 \end{figure}
109 Whiskas cat food, shown above, is manufactured by Uncle Ben's. Uncle Ben's want to produce their cat food products as cheaply as possible while ensuring they meet the stated nutritional analysis requirements shown on the cans. Thus they want to vary the quantities of each ingredient used (the main ingredients being chicken, beef, mutton, rice, wheat and gel) while still meeting their nutritional standards.
110
111 \begin{figure}[h]
112 \centering
113 \includegraphics[scale=0.5]{images/whiskas_ingredients.jpg}\includegraphics[scale=0.5]{images/whiskas_nutrition.jpg}
114 \caption{Detail of ingredients and nutritional requirements.}
115 \end{figure}
116
117 \begin{figure}[h]
118 \centering
119 \includegraphics[scale=0.6]{images/whiskas_blend.jpg}
120 \caption{The quantity of each ingredient must be determined.}
121 \end{figure}
122 The costs of the chicken, beef, and mutton are \$0.013, \$0.008 and \$0.010 respectively, while the costs of the rice, wheat and gel are \$0.002, \$0.005 and \$0.001 respectively. (All costs are per gram.) For this exercise we will ignore the vitamin and mineral ingredients. (Any costs for these are likely to be very small anyway.)
123 Each ingredient contributes to the total weight of protein, fat, fibre and salt in the final product which must be 100g (very convenient). The contributions (in grams) per gram of ingredient are given in the table below.
124
125 \begin{table}
126 \centering
127 \begin{tabular}{|l|l|l|l|l|}\hline
128 & Protein & Fat & Fibre & Salt\\\hline
129 Chicken & 0.100 & 0.080 & 0.001 & 0.002\\
130 Beef & 0.200 & 0.100 & 0.005 & 0.005\\
131 Rice & 0.000 & 0.010 & 0.100 & 0.008\\
132 Wheat bran & 0.040 & 0.010 & 0.150 & 0.000\\\hline
133 \end{tabular}
134 \caption{Table of ingredient compositions.}
135 \end{table}
136
137 A Linear Program consists of three main parts. These are the variable definitions, the objective function and the constraints.
138
139 \subsubsection{Variable definition}
140 In this problem the variables will be defined as the quantity (in grams) of each ingredient to include in the can. These variables will be continuous and will be able to take any non-negative value. Mathematically, we define set $I$ as the set of ingredients then create an $x$ variable indexed by $I$
141
142 \begin{eqnarray*}
143 I &=& \{chicken, beef, mutton, rice, wheat, gel\}\\
144 x_i &\ge& 0 \quad \quad i \in I.
145 \end{eqnarray*}
146
147 \lstinputlisting[linerange={4-12}]{code/whiskas.py}
148
149 \subsubsection{Objective Function}
150 The objective function is to minimise the cost of production for each can.
151 \[
152 \min \sum_i c_i x_i.
153 \]
154 Where:
155 \begin{itemize}
156 \item $c_i$ is the cost per gram of ingredient $i$.
157 \end{itemize}
158
159 \lstinputlisting[linerange={14-17}]{code/whiskas.py}
160
161 \subsubsection{Constraints}
162 Constraints serve to control the total mass of the ingredients and to model the protein, fat, salt and fibre requirements.
163
164 \begin{align*}
165 \sum_i x_i &= 100 \; \text{\hspace{19 mm}can mass} \\
166 \sum_i p_i x_i &\ge 8.0 \; \text{\hspace{20 mm}protein} \\
167 \sum_i f_i x_i &\ge 6.0 \; \text{\hspace{20 mm}fat} \\
168 \sum_i b_i x_i &\le 2.0 \; \text{\hspace{20 mm}fibre} \\
169 \sum_i s_i x_i &\le 0.4 \; \text{\hspace{20 mm}salt}.
170 \end{align*}
171 Where:
172 \begin{itemize}
173 \item $p_i$ is the protein per gram of ingredient $i$;
174 \item $f_i$ is the fat per gram of ingredient $i$;
175 \item $b_i$ is the fibre per gram of ingredient $i$;
176 \item $s_i$ is the salt per gram of ingredient $i$.
177 \end{itemize}
178
179 \lstinputlisting[linerange={18-29}]{code/whiskas.py}
180
181 The pulp model must now be solved with some third party optimisation software.
182 Pulp currently supports solving with coin-or \cite{coin-or}, glpk \cite{glpk},
183 CPLEX \cite{cplex} and Gurobi \cite{gurobi}.
184 The pulp download includes compiled versions of the coin-or solver for ubuntu and windows computers.
185
186 \lstinputlisting[linerange={31-37}]{code/whiskas.py}
187
188 \section{Other Example LP models}
189
190 Modelling the diet problem is not the only application of linear programming. Other examples include:
191 \begin{itemize}
192 \item the transportation problem,
193 \item the set partitioning problem,
194 \item the assignment problem,
195 \item the knapsack problem.
196 \end{itemize}
197 In this section we will give short examples of the first two problems modelled in pulp together with a brief description.
198
199 \subsection{The Transportation Problem (beerdistribution.py)}
200 A transportation problem involves that shipment of items from a set of sources
201 to a set of sinks (the sources and sinks must be disjoint sets), the problem seeks
202 to minimise the cost of shipping. In this case-study
203 crates of beer must be shipped from two breweries to five bars.
204
205 \begin{figure}[h]
206 \centering
207 \includegraphics[scale = 0.3]{images/beerdistribution.png}
208 \caption{The brewery and bar capacities and possible routes.}
209 \end{figure}
210
211
212 The problem is created.
213 \lstinputlisting[linerange={37-38}]{code/beerdistribution.py}
214
215 A list of possible routes for transportation is created:
216 \lstinputlisting[linerange={40-41}]{code/beerdistribution.py}
217
218 The variables created determine the amount shipped on each route. The variables
219 are defined as \lstinline{pulp.LpInteger} therefore solutions must not
220 ship fractional numbers of crates.
221 \lstinputlisting[linerange={43-47}]{code/beerdistribution.py}
222
223 The objective is to minimise the total shipping cost of the solution.
224 \lstinputlisting[linerange={48-50}]{code/beerdistribution.py}
225
226 These constraints ensure that amount shipped from each brewery is less
227 than the supply available. The names given to the constraints will be preserved
228 when an `.lp' file is created.
229 \lstinputlisting[linerange={52-55}]{code/beerdistribution.py}
230
231 These constraints ensure that amount shipped to each bar is greater
232 than the demand of the bar. These could also be equality constraints, depending
233 on how the problem is modelled.
234 \lstinputlisting[linerange={57-60}]{code/beerdistribution.py}
235
236 \subsection{The Set Partitioning Problem (wedding.py)}
237 A set partitioning problem determines how the items in one set (S) can be partitioned into smaller
238 subsets. All items in S must be contained in one and only one partition. Related problems are:
239 \begin{itemize}
240 \item set packing - all items must be contained in zero or one partitions;
241 \item set covering - all items must be contained in at least one partition.
242 \end{itemize}
243 In this case study a wedding planner must determine guest seating
244 allocations for
245 a wedding. To model this problem the tables are modelled as the partitions and the guests invited to the wedding
246 are modelled as the elements of S. The wedding planner wishes to maximise the total happiness of all of the tables.
247
248 A set partitioning problem may be modelled by explicitly enumerating each
249 possible subset. Though this approach does become intractable for large numbers of items (without using
250 column generation \cite{columngeneration}) it does have the advantage that the objective function co-efficients for
251 the partitions can be non-linear expressions (like happiness) and still allow this problem to be solved
252 using Linear Programming.
253
254 First we use \lstinline{pulp.allcombinations} to generate a list of all possible table seatings.
255 \lstinputlisting[linerange={20-22}]{code/wedding.py}
256
257 Then we create a binary variable that will be 1 if the table will be in the solution, or zero otherwise.
258 \lstinputlisting[linerange={24-28}]{code/wedding.py}
259
260 We create the \lstinline{LpProblem} and then make the objective function. Note that
261 happiness function used in this script would be difficult to model in any other way.
262 \lstinputlisting[linerange={30-32}]{code/wedding.py}
263
264 We specify the total number of tables allowed in the solution.
265 \lstinputlisting[linerange={34-35}]{code/wedding.py}
266
267 This set of constraints defines the set partitioning problem by guaranteeing that a guest is allocated to
268 exactly one table.
269 \lstinputlisting[linerange={38-41}]{code/wedding.py}
270
271
272
273 \section{Why pulp}
274 Modelling problems using LP and solving them with pulp can be a very useful approach for the python programmer.
275 This approach allows the programmer to focus on the modelling rather than the algorithms that find the solution.
276 The third party LP solvers that pulp interfaces with are all mature pieces of software that can be trusted to
277 produce the correct solution to the model created in pulp. The difference between these solvers, for a user of pulp,
278 lies mainly in the trade off between cost of the solver and its speed to find a solution.
279
280 LP and IP are well researched areas of mathematics, therefore once a problem is stated as an LP model it is possible
281 to guarantee some properties of the solutions given. For instance, if the solver delivers an optimal solution it
282 will be impossible for someone to create a solution that is better (as measured by the objective function).
283
284 Compared to other LP modelling tools including AMPL \cite{ampl}, GAMS \cite{gams}, mathprog \cite{glpk}, flopc++ \cite{flopc}, and pyomo \cite{pyomo} and poams; pulp offers a number of advantages. These include its:
285 \begin{itemize}
286 \item non-restrictive licensing;
287 \item ease of installation;
288 \item clear syntax;
289 \item interoperability with an number of solvers;
290 \item extensive documentation.
291 \end{itemize}
292
293 \subsection{Licensing}
294 The licensing of pulp under a permissive open-source license allows pulp to be used as a medium for teaching
295 operations research as students can download and use pulp for free. The license allows OR practitioners to
296 integrate pulp in commercial applications for their clients without disclosing how the problem was solved.
297 The license also allows advanced users to modify and improve pulp for their own purposes.
298
299 \subsection{Installation}
300 Pulp is very easy to install. The provision of a setup.py file and registration on pipy, allows the user
301 to use
302 \begin{verbatim}
303 $easy_install pulp-or
304 \end{verbatim}
305 to download and install pulp on their system. For windows and ubuntu users this binary package also includes
306 the coin-or \cite{coin-or} solver so pulp will be immediately functional. For users on other platforms a compatible
307 solver must be installed for a pulp model to be solved.
308
309 \subsection{Syntax}
310 Ideally an LP modelling framework will allow a one-to-one translation of symbols from mathematical notation. If the syntax follows the formulation the programmer can ensure that the model written is the model required. The OR practitioner can also quickly read and understand the a model as written pulp, without having much python background. The standard mathematical notation is very concise and therefore code that mimics it will also be clear and concise.
311
312 The use of a `Pythonic' construction of the pulp framework allows the programmer to use it easily in a variety of ways. Pulp can be directly imported into the local name-space (against python style) to allow simple LP models to be written by non-programmers, in fact most of the case studies on the wiki \cite{pulpwiki} use this style. Pulp also does not force the programmer to use any particular way to store parameter data. Parameter data can be stored as lists, dictionaries or custom classes.
313
314 \subsection{Interoperability}
315 The ability for pulp to call a number of free and non-free solvers is important as the OR practitioner often wishes to compare the solution of a problem with a variety of solvers. The user may wish to develop simple LP models in a free solver and then provide a solution to a client using a commercial solver. The use of non-free solvers may dramatically reduce the solution time of the model. Pulp allows the free interchange of solvers without much change in the program, only a parameter for the \lstinline{LpProblem.solve} function is changed.
316
317 \subsection{Documentation}
318 Pulp is supplied with a user guide with extensive examples (in fact it was converted from a course teaching LP modelling). This user guide and the permissive license were intended to make pulp useful to the largest possible audience.
319
320 \section{Conclusion}
321 In conclusion pulp nicely bridges the gap between the OR practitioner and the python programmer. This allows the OR practitioner to use python to quickly develop and solve LP and IP models while having access to all of the tools available in the python standard library. The python programmer can now embed LP models in complex programs written in python. So next time you find yourself hacking up an algorithm to solve some problem in your code please consider if it would be appropriate to model this problem as an LP or IP instead. If so download and use pulp.
322
323 \section*{Appendix - Example Code in full}
324 \subsection*{whiskas.py}
325 \lstinputlisting{code/whiskas.py}
326
327 \subsection*{beerdistribution.py}
328 \lstinputlisting{code/beerdistribution.py}
329
330 \subsection*{wedding.py}
331 \lstinputlisting{code/wedding.py}
332
333
334 %-------------------------------------------------------------------------
335 %--- back matter: bibliography ---
336 % These are in alphabetical by leading author order.
337 \newpage
338 \bibliographystyle{IEEEtran}
339 \bibliography{references}
340 %-------------------------------------------------------------------------
341 % We need this for the style to work properly, so please leave it in here:
342 \label{lastpagenum}
343 \end{document}