Ticket #9836: trac_9836.patch

File trac_9836.patch, 25.0 KB (added by ncohen, 9 years ago)
  • doc/en/constructions/index.rst

    # HG changeset patch
    # User Nathann Cohen <nathann.cohen@gmail.com>
    # Date 1283600443 -7200
    # Node ID 69e2253c2a5eef5c8f1ccc6e2f52a16f26a52dbd
    # Parent  5a26560c3ceded43f0115375e8a8b97de0a253b1
    trac 9836 -- creates a linear_programming tutorial and removes the old one from the construction document.
    
    diff -r 5a26560c3ced -r 69e2253c2a5e doc/en/constructions/index.rst
    a b  
    3434   linear_algebra
    3535   linear_codes
    3636   graph_theory
    37    linear_programming
    3837   rep_theory
    3938   rings
    4039   polynomials
  • deleted file doc/en/constructions/linear_programming.rst

    diff -r 5a26560c3ced -r 69e2253c2a5e doc/en/constructions/linear_programming.rst
    + -  
    1 Linear Programming
    2 ==================
    3 
    4 
    5 Basics
    6 ------
    7 
    8 What is a linear program?
    9 """""""""""""""""""""""""
    10 
    11 A linear program consists of the following two pieces of information:
    12 
    13 * A linear function, called the objective function, which is
    14   to be maximized or minimized, e.g. `2 x + y`.
    15 
    16 * Linear constraints on the variables, e.g. `3 x + y \leq 2` and
    17   `2 x + 3 y \leq 8`.
    18 
    19 A linear program solver would then try to find a solution to the
    20 system of constraints such that the objective function is optimized, and
    21 return specific values for the variables.
    22 
    23 What is a mixed integer linear program?
    24 """""""""""""""""""""""""""""""""""""""
    25 
    26 A mixed integer linear program is a linear program such that some
    27 variables are forced to take integer values instead of real
    28 values. This difference affects the time required to solve a
    29 particular linear program. Indeed, solving a linear program can be
    30 done in polynomial time while solving a general mixed integer linear
    31 program is usually `NP`-complete, i.e. it can take exponential time,
    32 according to a widely-held belief that `P \neq NP`.
    33 
    34 Why is linear programming so useful?
    35 """"""""""""""""""""""""""""""""""""
    36 
    37 Linear programming is very useful in many optimization and
    38 graph-theoretic problems because of its wide range of expression.
    39 A linear program can be written to solve a problem whose
    40 solution could be obtained within reasonable time using the wealth of
    41 heuristics already contained in linear program solvers. It is often
    42 difficult to theoretically determine the execution time of a linear
    43 program, though it could produce very interesting results in
    44 practice.
    45 
    46 For more information, consult the Wikipedia page dedicated to
    47 linear programming: http://en.wikipedia.org/wiki/Linear_programming
    48 
    49 
    50 How can I solve a linear program using Sage?
    51 --------------------------------------------
    52 
    53 Sage can solve linear programs or mixed integer linear programs
    54 through the class ``MixedIntegerLinearProgram`` defined in
    55 ``sage.numerical.mip``. To illustrate how it can be used, we will try
    56 to solve the following problem:
    57 
    58 .. MATH::
    59 
    60     \text{Maximize: }  & 2 x_1 + x_2 \\
    61     \text{Such that: } & 3 x_1 + 4 x_2 \leq 2.5 \\
    62                        & 0.5 \leq 1.2 x_1 + 0.5 x_2 \leq 4
    63 
    64 First, we need to discuss ``MIPVariable`` and how to read the optimal
    65 values when the solver has finished its job.
    66 
    67 Variables in ``MixedIntegerLinearProgram``
    68 """"""""""""""""""""""""""""""""""""""""""
    69 
    70 A variable linked to an instance of ``MixedIntegerLinearProgram``
    71 behaves exactly as a dictionary would. It is declared as follows::
    72 
    73     sage: p = MixedIntegerLinearProgram()
    74     sage: variable = p.new_variable()
    75 
    76 The variable ``variable`` can contain as many keys as you
    77 like, where each key must be unique. For example, the following
    78 constraint (where `P` denotes pressure and `T` temperature)
    79 
    80 .. MATH::
    81 
    82     2 T_{\text{Madrid}} + 3 T_{\text{London}} - P_{\text{Seattle}} + \text{flow}_{3, 5} + 8 \text{cost}_{(1, 3)} + x_3 < 5
    83 
    84 can be written as::
    85 
    86     sage: p = MixedIntegerLinearProgram()
    87     sage: temperature = p.new_variable()
    88     sage: pressure = p.new_variable()
    89     sage: x = p.new_variable()
    90     sage: cost = p.new_variable()
    91     sage: flow = p.new_variable(dim=2)
    92     sage: p.add_constraint(2*temperature["Madrid"] + 3*temperature["London"] - pressure["Seattle"] + flow[3][5] + 8*cost[(1, 3)] + x[3], max=5)
    93 
    94 This example shows different possibilities for using the
    95 ``MixedIntegerLinearProgram`` class. You would not need to declare so
    96 many variables in some common applications of linear programming.
    97 
    98 Notice how the variable ``flow`` is defined: you can use any hashable
    99 object as a key for a ``MIPVariable``, but if you think you need
    100 more than one dimension, you need to explicitly specify it when
    101 calling ``MixedIntegerLinearProgram.new_variable()``.
    102 
    103 For the user's convenience, there is a default variable
    104 attached to a linear program. The above code listing means that each
    105 ``variable`` actually represents a property of a set of objects
    106 (these objects are strings in the case of ``temperature`` or a pair in
    107 the case of ``cost``). In some cases, it is useful to define an
    108 absolute variable which will not be indexed on anything. This can be
    109 done as follows::
    110 
    111     sage: p = MixedIntegerLinearProgram()
    112     sage: B = p.new_variable()
    113     sage: p.set_objective(p["first unique variable"] + B[2] + p[-3])
    114 
    115 In this case, two of these "unique" variables are defined through
    116 ``p["first unique variable"]`` and ``p[-3]``.
    117 
    118 Let's solve this system
    119 """""""""""""""""""""""
    120 
    121 Now that we know what variables are, we are only several steps away
    122 from solving our system::
    123 
    124     sage: # First, we define our MixedIntegerLinearProgram object,
    125     sage: # setting maximization=True.
    126     sage: p = MixedIntegerLinearProgram(maximization=True)
    127     sage: x = p.new_variable()
    128     sage: # Definition of the objective function
    129     sage: p.set_objective(2*x[1] + x[2])
    130     sage: # Next, the two constraints
    131     sage: p.add_constraint(3*x[1] + 4*x[2], max=2.5)
    132     sage: p.add_constraint(1.5*x[1]+0.5*x[2], max=4, min=0.5)
    133     sage: p.solve()                # optional - requires GLPK or COIN-OR/CBC
    134     1.6666666666666667
    135     sage: x_sol = p.get_values(x)  # optional - requires GLPK or COIN-OR/CBC
    136     sage: print x_sol              # optional - requires GLPK or COIN-OR/CBC
    137     {1: 0.83333333333333337, 2: 0.0}
    138 
    139 The value returned by ``MixedIntegerLinearProgram.solve()`` is the
    140 optimal value of the objective function. To read the values taken by
    141 the variables, one needs to call the method
    142 ``MixedIntegerLinearProgram.get_values()`` which can return multiple
    143 values at the same time if needed (type
    144 ``MixedIntegerLinearProgram.get_values?`` for more information
    145 on this function).
    146 
    147 
    148 Some famous examples
    149 --------------------
    150 
    151 Vertex cover in a graph
    152 """""""""""""""""""""""
    153 
    154 Let `G = (V, E)` be a graph with vertex set `V` and edge set `E`. In
    155 the vertex cover problem, we are given `G` and we want to find
    156 a subset `S \subseteq V` of minimal cardinality such that each
    157 edge `e` is incident to at least one vertex in `S`. In order to
    158 achieve this, we define a binary variable `b_v` for each vertex
    159 `v`. The vertex cover problem can be expressed as the following linear
    160 program:
    161 
    162 .. MATH::
    163 
    164     \text{Maximize: }  & \sum_{v \in V} b_v \\
    165     \text{Such that: } & \forall (u, v) \in E, b_u + b_v \geq 1 \\
    166                        & \forall v, b_v \text{ is a binary variable}
    167 
    168 In the linear program, the syntax is exactly the same::
    169 
    170     sage: g = graphs.PetersenGraph()
    171     sage: p = MixedIntegerLinearProgram(maximization=False)
    172     sage: b = p.new_variable()
    173     sage: for u, v in g.edges(labels=None):
    174     ...       p.add_constraint(b[u] + b[v], min=1)
    175     sage: p.set_binary(b)
    176 
    177 And you need to type ``p.solve()`` to see the result.
    178 
    179 Maximum matching in a graph
    180 """""""""""""""""""""""""""
    181 
    182 In the maximum matching problem, we are given a graph `G = (V, E)`
    183 and we want a set of edges `M \subseteq E` of maximum cardinality such
    184 that no two edges from `M` are adjacent:
    185 
    186 .. MATH::
    187 
    188     \text{Maximize: }  & \sum_{e \in E} b_e \\
    189     \text{Such that: } & \forall v \in V, \sum_{(v,u) \in E} b_{vu} \leq 1 \\
    190                        & \forall e \in E, b_e \text{ is a binary variable}
    191 
    192 Here, we use Sage to solve the maximum matching problem for the case
    193 of the Petersen graph::
    194 
    195     sage: g = graphs.PetersenGraph()
    196     sage: p = MixedIntegerLinearProgram()
    197     sage: b = p.new_variable(dim=2)
    198     sage: for u in g.vertices():
    199     ...       p.add_constraint(sum([b[u][v] for v in g.neighbors(u)]), max=1)
    200     sage: for u, v in g.edges(labels=None):
    201     ...       p.add_constraint(b[u][v] + b[v][u], min=1, max=1)
    202 
    203 And the next step is ``p.solve()``.
    204 
    205 
    206 Solvers
    207 -------
    208 
    209 Sage solves linear programs by calling specific libraries. The
    210 following libraries are currently supported :
    211 
    212 * `CBC <http://www.coin-or.org/projects/Cbc.xml>`_: A solver from
    213   from `COIN-OR <http://www.coin-or.org/>`_ (CPL -- Free)
    214 
    215 * `CPLEX <http://www-01.ibm.com/software/integration/optimization/cplex/>`_: A
    216   solver from `ILOG <http://www.ilog.com/>`_ (Proprietary)
    217 
    218 * `GLPK <http://www.gnu.org/software/glpk/>`_: A solver
    219   from `GNU <http://www.gnu.org/>`_ (GPL3, Free)
    220 
    221 Installing GLPK or CBC
    222 """"""""""""""""""""""""
    223 
    224 GPLK and CBC being free softwares, they can be easily installed
    225 as follows::
    226 
    227     sage: # To install GLPK
    228     sage: install_package("glpk")  # not tested
    229     sage: # To install COIN-OR Branch and Cut (CBC)
    230     sage: install_package("cbc")   # not tested
    231 
    232 Installing CPLEX
    233 """"""""""""""""
    234 
    235 ILOG CPLEX, on the other hand, is Proprietary -- to use it through Sage, you
    236 must first be in possession of :
    237 
    238 * A valid license file
    239 * A compiled version of the CPLEX library (usually named libcplex.a)
    240 * The header file cplex.h
    241 
    242 The license file path must be set the value of the environment
    243 variable ILOG_LICENSE_FILE. For example, you can write ::
    244 
    245     export ILOG_LICENSE_FILE=/path/to/the/license/ilog/ilm/access_1.ilm
    246 
    247 at the end of your .bashrc file.
    248 
    249 As Sage also needs the files libcplex.a and cplex.h, the easiest way
    250 is to create symbolic links toward these files in the appropriate
    251 directories :
    252 
    253 * libcplex.a -- in SAGE_ROOT/local/lib/, type ::
    254 
    255     ln -s /path/to/lib/libcplex.a .
    256 
    257 * cplex.h -- in SAGE_ROOT/local/include/, type ::
    258 
    259     ln -s /path/to/include/cplex.h .
    260 
    261 Once this is done, and as CPLEX is used in Sage through the Osi
    262 library, which is part of the Cbc package, you can type::
    263 
    264     sage: install_package("cbc")  # not tested
    265 
    266 or, if you had already installed Cbc ::
    267 
    268     sage: install_package("cbc", force = True)  # not tested
    269 
    270 to reinstall it.
    271 
  • doc/en/thematic_tutorials/index.rst

    diff -r 5a26560c3ced -r 69e2253c2a5e doc/en/thematic_tutorials/index.rst
    a b  
    1717 
    1818   functional_programming
    1919   group_theory
     20   linear_programming
    2021
    2122Indices and tables
    2223==================
  • new file doc/en/thematic_tutorials/linear_programming.rst

    diff -r 5a26560c3ced -r 69e2253c2a5e doc/en/thematic_tutorials/linear_programming.rst
    - +  
     1(Mixed Integer) Linear Programming
     2==================================
     3
     4This document explains the use of Linear Programming (LP) -- and of Mixed Integer Linear Programming (MILP) -- in Sage by illustrating it with several problems it can solve. Most of the examples given are motivated by graph-theoretic concerns, and should be understandabe without any specific knowledge of this field. As a tool in Combinatorics, using Linear Programming amounts to understanding how to reformulate an optimization (or existence) problem through linear constraints.
     5
     6.. centered::
     7    *(this is a translation of a chapter from the book "Calcul mathematique avec Sage")*
     8
     9Definition
     10----------
     11
     12Set to bear once more upon our shoulders the heavy weight of mathematical formalism, let us give here the usual definition of what a Linear Program is : it is defined by a matrix `A: \mathbb{R}^m\mapsto \mathbb{R}^n`, along with two vectors `b,c\in \mathbb{R}^n`. Solving a Linear Program is a quest for a vector `x` maximizing an *objective* function and satisfying a set of constraints, i.e.
     13
     14.. MATH::
     15      c^t x = \max_{x' \text{ such that}Ax'\leq b}c^t x'`
     16
     17(where the ordering `u\leq u'` between two vectors means that the entries of `u'` are pairwise greater than the entries of `u`). We also write :
     18
     19.. MATH::
     20      \text{Max : }&c^t x\\
     21      \text{ Such that : }&Ax\leq b
     22
     23Equivalently, we can also say that solving a linear program amounts to maximizing a linear function defined over a polytope (preimage or `A^{-1}(\leq b)`). These definitions, however, do not tell us how to use linear programming in combinatorics. In the following, we will try to fix this by showing how to solve optimization problems like the Knapsack problem, the Maximum Matching problem, and a Flow problem.
     24
     25
     26Mixed Integer Linear Programming
     27--------------------------------
     28
     29There is a bad news coming along with this definition of linear programming : a LP can be solved in polynomial time. This is indeed a bad news, because this would mean than unless we define LP of exponential size, we can not expect LP to solve NP-complete problems, which would be a disappointment. On a brighter side, it becomes NP-Complete to solve a Linear Program  if we are allowed to specify constraints of a different kind : requiring that some variables be integers instead of real values. Such a LP is actually called a "Mixed Integer Linear Program" (some variables can be integers, some other reals). Hence, we can expect to find in the MILP framework a *wide* range of expressivity.
     30
     31Practically
     32-----------
     33
     34The ``MILP`` class
     35^^^^^^^^^^^^^^^^^^
     36
     37The ``MILP`` class in Sage represents a ... MILP ! It is also used to solve regular LP. It has a very small number of methods, meant to define our set of constraints and variables, then to read the solution found by the solvers once computed. It is also possible to export a MILP defined with Sage to a .lp or .mps file, understood by most solvers.
     38
     39Let us ask Sage to solve the following LP :
     40
     41.. MATH::
     42  \text{Max : }&x+y-3z\\
     43  \text{Such that : }&x+2y \leq 4\\
     44  \text{}&5z  - y \leq 8\\
     45
     46To achieve it, we need to define a corresponding ``MILP`` object, along with the 3 variables we need ::
     47
     48  sage: p = MixedIntegerLinearProgram()
     49  sage: x, y, z = p['x'], p['y'], p['z']
     50
     51The objective function
     52
     53.. link
     54
     55::
     56
     57  sage: p.set_objective( x + y + 3*z )
     58
     59And finally the constraints
     60
     61.. link
     62
     63::
     64
     65  sage: p.add_constraint( x + 2*y <= 4 )
     66  sage: p.add_constraint( 5*z - y  <= 8 )
     67 
     68The ``solve`` method returns by default the optimal value reached by the objective function
     69
     70.. link
     71
     72::
     73
     74  sage: round(p.solve(),2)
     75  8.8
     76
     77We can read the optimal assignation found by the solver for `x, y` and `z` through the ``get_values`` method
     78
     79.. link
     80
     81::
     82
     83  sage: round(p.get_values(x),2)
     84  4.0
     85  sage: round(p.get_values(y), 2)
     86  0.0
     87  sage: round(p.get_values(z), 2)
     88  1.6
     89
     90Variables
     91^^^^^^^^^
     92
     93The variables associated with an instance of ``MILP`` belong to the ``MIPVariable`` class, though we should not be concerned with this. In the previous example, we obtained these variables through the "shortcut" ``p['x']``, which is easy enough when our LP is defined over a small number of variables. This being said, the LP/MILP we will present afterwards very often require one to associate one -- or many -- variables to each member of a list of objects, which can be integers, or the vertices or edges of a graph, among plenty of other alternatives. This means we will very soon need to talk about vectors of variables, if not of dictionaries of variables.
     94
     95If a LP requires us to define variables named `x_1, \dots, x_{15}`, we will this time make use of the ``new_variable`` method
     96
     97.. link
     98
     99::
     100
     101  sage: x = p.new_variable()
     102
     103It is now very easy to define constraints using our `15` variables
     104
     105.. link
     106
     107::
     108
     109  sage: p.add_constraint( x[1] + x[12] - x[14] >= 8 )
     110
     111Notice that we did not need to define the length of our vector. Actually, ``x`` would accept any immutable object as a key, as a dictionary would. We can now write
     112
     113.. link
     114
     115::
     116
     117  sage: p.add_constraint( x["I am a valid key"]
     118  ...                   + x[("a",pi)] <= 3 )
     119
     120
     121Other LP may require variables indexed several times. Of course, it is already possible to emulate it by using tuples like `x[(2,3)]`, though to keep the code understandable the method ``new_variable`` accepts as a parameter the integer ``dim``, which lets us define the dimension of the variable. We can now write
     122
     123.. link
     124
     125::
     126
     127  sage: y = p.new_variable(dim = 2)
     128  sage: p.add_constraint( y[3][2] + x[5] == 6)
     129
     130Typed variables
     131"""""""""""""""
     132
     133By default, all the LP variables are assumed to be non-negativereals. They can be defined as binary through the parameter ``binary = True`` (or integer with ``integer = True``). Lower and upper bounds can be defined or re-defined (for instance when you want some variables to be negative) using the methods ``set_min`` and ``set_max``.
     134
     135It is also possible to change the type of a variable after it has been created with the methods ``set_binary`` and ``set_integer``.
     136
     137Basic Linear Programs
     138---------------------
     139
     140Knapsack
     141^^^^^^^^
     142
     143The *Knapsack* problem is the following : given a collection of items having both a weight and a *usefulness*, we would like to fill a bag whose capacity is constrained through maximizing the usefulness of the items it contains (we will here consider their sum).
     144
     145To achieve this, we have to associate to each object `o` of our collection `C` a binary variable ``taken[o]``, set to 1 when the object is in the bag, and to 0 otherwise. We are trying to solve the following MILP
     146
     147.. MATH::
     148  \text{Max : }&\sum_{o\in L}usefulness_o\times taken_o\\
     149  \text{Tel que : }&\sum_{o\in L} poids_o\times taken_o \leq C\\
     150
     151Using \Sage, we will give to our items a random weight ::
     152
     153  sage: C = 1
     154
     155
     156
     157.. link
     158
     159::
     160
     161  sage: L = ["Casserole", "Livre", "Couteau",
     162  ...        "Gourde", "Lampe de poche"]
     163
     164
     165
     166.. link
     167
     168::
     169
     170  sage: L.extend( ["divers_"+str(i) for i in range(20)] )
     171
     172
     173
     174.. link
     175
     176::
     177
     178  sage: poids = {}
     179  sage: usefulness = {}
     180
     181
     182
     183.. link
     184
     185::
     186
     187  sage: set_random_seed(685474)
     188  sage: for o in L:
     189  ...      poids[o]   = random()
     190  ...      usefulness[o] = random()
     191
     192We can now define the MILP itself
     193
     194.. link
     195
     196::
     197
     198
     199  sage: p = MixedIntegerLinearProgram()
     200  sage: taken = p.new_variable( binary = True )
     201
     202
     203.. link
     204
     205::
     206
     207  sage: p.add_constraint(
     208  ...     sum( poids[o] * taken[o] for o in L ) <= C )
     209
     210
     211.. link
     212
     213::
     214
     215  sage: p.set_objective(
     216  ...     sum( usefulness[o] * taken[o] for o in L ) )
     217
     218
     219.. link
     220
     221::
     222
     223  sage: p.solve()
     224  3.1502766806530307
     225  sage: taken = p.get_values(taken)
     226
     227The solution found is (of course) admissible
     228
     229.. link
     230
     231::
     232
     233  sage: sum( poids[o] * taken[o] for o in L )
     234  0.69649597966191712
     235
     236Should we take a flashlight ?
     237
     238.. link
     239
     240::
     241
     242  sage: taken["Lampe de poche"]
     243  1.0
     244
     245Wise advice. Based on purely random considerations.
     246
     247Matching
     248--------
     249
     250Given a graph `G`, a matching is a set of pairwise disjoint edges. The empty set being a matching, we naturally focus our attention on maximum matchings : we want to find in a graph a matching whose cardinality is maximal. Computing the maximum matching in a graph is a polynomial problem, which is a famous result of Edmonds : his algorithm is based on local improvements, and the proof that a given matching is maximum if it can not be improved. This algorithm is not the hardest to implement among those Graph Theory can offer, though this problem can be modeled with a very simple MILP.
     251
     252To do it, we need -- as previously -- to associate a binary variable to each one of our objects : the edges of our graph (a value of 1 meaning that the corresponding edge is included in the maximum matching). Our constraint on the edges taken being that they are disjoint, it is enough to require that, `x` and `y` being two edges and `m_x,m_y` their associated variables, the inequality `m_x + m_y \leq 1` is satisfied, as we are sure that the two of them can not both belong to the matching. Hence, we are able to write the MILP we want. However, the number of inequalities can be easily decreaded by noticing that two edges can not be taken simultaneously inside a matching if and only if they have a common endpoint `v`. We can then require instead that at most one edge incident to `v` be taken inside the matching (which is a linear constraint). We will be solving :
     253
     254.. MATH::
     255  \text{Max : }&\sum_{e\in E(G)}m_e\\
     256  \text{Tel que : }&\forall v, \sum_{e\in E(G)\atop v\sim e} m_e \leq 1\\
     257
     258Let us write the Sage code of this MILP::
     259
     260  sage: g = graphs.PetersenGraph()
     261  sage: p = MixedIntegerLinearProgram()
     262  sage: matching = p.new_variable(binary = True)
     263
     264
     265
     266.. link
     267
     268::
     269
     270  sage: p.set_objective(sum( matching[e]
     271  ...                   for e in g.edges(labels = False)))
     272
     273
     274
     275.. link
     276
     277::
     278
     279  sage: for v in g:
     280  ...      p.add_constraint(sum( matching[e]
     281  ...           for e in g.edges_incident(v, labels = False)) <= 1)
     282
     283
     284
     285.. link
     286
     287::
     288
     289  sage: p.solve()
     290  5.0
     291
     292
     293
     294.. link
     295
     296::
     297
     298  sage: matching = p.get_values(matching)
     299  sage: [e for e,b in matching.iteritems() if b == 1]
     300  [(0, 1), (6, 9), (2, 7), (3, 4), (5, 8)]
     301
     302Flows
     303-----
     304
     305Yet another fundamental algorithm in graph theory : maximum flow ! It consists, given a directed graph and two vertices `s, t`, in sending a maximum *flow* from `s` to `t` using the edges of `G`, each f them having a maximal capacity.
     306
     307
     308.. image:: lp_flot1.png
     309   :align: center
     310
     311The definition of this problem is almost its LP formulation. We are looking for real values associted to each edge, which would representthe intensity of flow going through them, under two types of constraints:
     312
     313    * The amount of flow arriving on a vertex (different from `s` or `t`) is equal to the amount of flow leaving it
     314    * The amount of flow going through an edge is bounded by the capacity of this edge
     315
     316This being said, we but have to maximize the amount of flow leaving `s` : all of it will end up in `t`, as the other vertices are sending just as much as they receive. We can model the flow problem with the following LP
     317
     318.. MATH::
     319  \text{Max : }&\sum_{sv\in G}f_{sv}\\
     320  \text{Tel que : }&\forall v\in G, {v\neq s\atop v\neq t}, \sum_{vu\in G}f_{vu} - \sum_{uv \in G}f_{uv} = 0\\
     321  &\forall uv\in G, f_{uv} \leq 1\\
     322
     323We will he solve the flow problem on an orienration of Chvatal's Graph, in which all the edges have a capacity of 1::
     324
     325  sage: g = graphs.ChvatalGraph()
     326  sage: g = g.minimum_outdegree_orientation()
     327
     328
     329
     330.. link
     331
     332::
     333
     334  sage: p = MixedIntegerLinearProgram()
     335  sage: f = p.new_variable()
     336  sage: s, t = 0, 2
     337
     338
     339
     340.. link
     341
     342::
     343
     344  sage: for v in g:
     345  ...      if v != s and v != t:
     346  ...          p.add_constraint(
     347  ...              sum( f[(v,u)] for u in g.neighbors_out(v))
     348  ...             -sum( f[(u,v)] for u in g.neighbors_in(v)) == 0)
     349
     350
     351
     352.. link
     353
     354::
     355
     356  sage: for e in g.edges(labels = False):
     357  ...      p.add_constraint( f[e] <= 1 )
     358
     359
     360
     361.. link
     362
     363::
     364
     365  sage: p.set_objective(sum( f[(s,u)] for u in g.neighbors_out(s)))
     366
     367
     368
     369.. link
     370
     371::
     372
     373  sage: p.solve()
     374  2.0
     375
     376.. image:: lp_flot2.png
     377   :align: center
     378
     379Solvers
     380-------
     381
     382Sage solves linear programs by calling specific libraries. The
     383following libraries are currently supported :
     384
     385* `CBC <http://www.coin-or.org/projects/Cbc.xml>`_: A solver from from
     386  `COIN-OR <http://www.coin-or.org/>`_ (CPL -- Free)
     387
     388  CBC can be installed through the command ``install_package("cbc")``
     389
     390* `CPLEX
     391  <http://www-01.ibm.com/software/integration/optimization/cplex/>`_:
     392  A solver from `ILOG <http://www.ilog.com/>`_ (Proprietary, but free
     393  for researchers and students)
     394
     395* `GLPK <http://www.gnu.org/software/glpk/>`_: A solver from `GNU
     396  <http://www.gnu.org/>`_ (GPL3, Free)
     397
     398  This solver is installed by default with Sage
     399
     400Installing CPLEX
     401----------------
     402
     403ILOG CPLEX being Proprietary -- you must be in possession of several
     404files to use it through Sage:
     405
     406* A valid license file
     407* A compiled version of the CPLEX library (usually named libcplex.a)
     408* The header file cplex.h
     409
     410The license file path must be set the value of the environment
     411variable ILOG_LICENSE_FILE. For example, you can write ::
     412
     413    export ILOG_LICENSE_FILE=/path/to/the/license/ilog/ilm/access_1.ilm
     414
     415at the end of your .bashrc file.
     416
     417As Sage also needs the files libcplex.a and cplex.h, the easiest way
     418is to create symbolic links toward these files in the appropriate
     419directories :
     420
     421* libcplex.a -- in SAGE_ROOT/local/lib/, type ::
     422
     423    ln -s /path/to/lib/libcplex.a .
     424
     425* cplex.h -- in SAGE_ROOT/local/include/, type ::
     426
     427    ln -s /path/to/include/cplex.h .
     428
     429Once this is done, and as CPLEX is used in Sage through the Osi
     430library, which is part of the Cbc package, you can type::
     431
     432    sage: install_package("cbc")  # not tested
     433
     434or, if you had already installed Cbc ::
     435
     436    sage: install_package("cbc", force = True)  # not tested
     437
     438to reinstall it.
     439