Introduc)on to
Python, Cplex and
Gurobi
Introduc)on
• Python is a widely used, high level
programming language designed by
Guido van Rossum and released on 1991.
• Two stable releases:
– Python 2.7
– Python 3.5
Python
• To open Start Menu-> Python27-> IDLE
• Python is an interacAve interpreted language,
so you can interact directly with the Python
prompt to write a program.
• For example, write on the prompt
– Print(‘Hello World!’)
– 2+4 or 2<4
Python
• Python prompt can be used to write a
program directly
OR
• A Python script can be created.
– File -> New File
– Write the program and save it with the
extension .py
– Run -> Run Module
Basic Syntax
• Print statement
– Elements separated by commas are printed with a
space in the middle.
– Operators such as \n or \t indicate new line or
new tab
– All ‘ – “ – ‘’’ or “”” indicate the same thing.
Basic Syntax
• Comments are iniAalized by #
• Python iden)fiers have to start with a lePer A
to Z (a to z) or an underscore ( _ ) followed by
lePers or numbers.
• Reserved words
And Assert Break Class ConAnue def del elif else except
exec finally for from global if import in is lambda
Not or pass print raise return try while with yield
Basic Syntax
• Blocks of code are denoted by line
indentaAon, no braces are used.
OK
ERROR
Variable Types
• Five standard data types: numbers, string, list,
tuple and dicAonary.
• Assign Values to Variables
• MulAple assignment
Variable Types
• Numbers: four numerical types are supported
– Int (integers), long (long integers) , float (floaAng
point real values) and complex (complex numbers)
• To convert from one to other.
Variable Types
• Some funcAons with numbers
Func)on Descrip)on Func)on Descrip)on
abs(x) Absolute value of x acos(x) Arc cosine of x, radians
ceil(x) Smallest integer not less x asin(x) Arc sine of x, randians
exp(x) e^x atan(x) Arc tangent of x, radians
log(x) Natural logarithm of x cos(x) Cosine of x, radians
log10(x) Base10 logarithm of x sin(x) Sine of x, radians
max(x1,…,xn) Max value of arguments tan(x) Tangent of x, radians
min(x1,…,xn) Min value of arguments degrees(x) Convert from radians to degre
pow(x,y) x^y radians(x) Convert from degree to rad
sqrt(x) Square root of x pi e Constants pi and e
Variable Types
• Strings: create them enclosing characters in
quotes
Variable Types
• Lists: contains items separated by commas
and enclosed within brackets [ ]
Variable Types
• Some funcAons of lists
Func)on Descrip)on
len(A) Returns length of the list
max(A) Returns item from list A with the max value
min(A) Returns item from list A with the min value
[Link](x) Appends x to list A
[Link](x) Returns how many Ames x is in list A
[Link](i,x) Inserts x in list A in posiAon i
[Link](x) Removes x from list A
[Link]() Reverses list A
[Link]() Sorts objects of list A
Variable Types
• Tuples: similar to a list but is enclosed in
parentheses ( ) and cannot be updated. (Read-
only lists)
• List vs Tuple: On a list an assignment can be
done, but not on a tuple. A tuple can be
converted to a list by list(A) .
Variable Types
• DicAonaries: like hash tables. Are enclosed by
curly braces { }
• DATA TYPE COVERSION: To convert between
types you only use the type name as a
funcAon.
Basic Operators
• ArithmeAc Operators
+ AddiAon / Division
- SubstracAon % Module
* MulAplicaAon ** Exponent
• Comparison Operators
a==b True if values are equal a<b True if a less than b
a!=b True if values are not equal a>=b True if a greater or equal than b
a>b True if a greater than b a<=b True if a is less or equal than b
Basic Operators
• Assignment Operators
a=b Assign value of b to a a*=b MulAplies a with b, assigns to a
a+=b Adds b to a, assign to a a/=b Divides a with b, assigns to a
a-=b Subtracts b to a, assign to a a**=b a^b and assigns to a
• Logical Operators
and True if both operators are true
or True if ONE of the operators is true
not NegaAon operator
Decision Making
• CondiAonal statements
Example:
Loops
• Statements are executed sequenAally.
Loop Type Descrip)on
while Repeats a statement while a given condiAon is true
for Executes a sequence of statement mulAple Ames
while:
Loops
• Statements are executed sequenAally.
Loop Type Descrip)on
while Repeats a statement while a given condiAon is true
for Executes a sequence of statement mulAple Ames.
for:
• For allows to iterate along the items of any sequence, that
can be a list. Also range funcAon can be used.
Loops
For:
Loops
• Control statements.
Statement Descrip)on
break Terminates the loop and transfer the execuAon to the
following statement ater the loop
conAnue Causes the loop to skip the remainder of its body and
immediately retest its condiAon prior to reiteraAng.
pass Used when a statement is required but not want to
execute anything on it.
Func)ons
• FuncAons can be defined to provide the
required funcAonality
– Blocks begin with def followed by the name and
parentheses ( )
– Any input should be placed within the
parentheses
– The statement return [ ] exits a funcAon.
• To call the funcAon just write the name of the
funcAon and the input parameters.
Func)ons
• Example
Func)ons
• All parameters are passed by reference. If you
change the value of an argument that was an
input inside the funcAon, it will be changed
also outside.
• But if a variable (with the same name) is
redefined inside the funcAon that will not
change the value outside the funcAon
Func)ons
Files I/O
• Python provides basic funcAons to read and
write files.
• OPEN: before you can read or write a file it
needs to be opened.
Modes Descrip)on
r Opens a file reading only.
r+ Opens a file for both reading and wriAng.
w Opens a file for wriAng only.
w+ Opens a file for both wriAng and reading.
Files I/O
• Close() closes the file and no more wriAng can
be done.
• Write() writes any string to an open file.
• Read() reads a string from an open file.
– readline()
Modules
• A module allows you to logically organize your
Python code.
• The modules, such as Cplex or Gurobi module
are called as follows
Gurobi
• Is a commercial opAmizaAon solver.
• It is named ater its founders: Zonghao Gu,
Edward Rothberg and Robert Bixby.
• It supports a variety of programming and
modelling languages including Python, C++,
etc.
• InstallaAon from [Link] and an
accademic free license can be requested.
LP Example
LP Example
• First we need to import the gurobi module
• We need to define the model with Model().
Inside the parentheses you can add a name to
the model. And the variable m will be used
every Ame we refer to the model on Python.
LP Example
• Create the variables with [Link]()
• [Link](), takes the following
arguments
• vtype can be [Link], [Link],
[Link], [Link] or
[Link]
LP Example
• To integrate new variables, [Link]()
• Set the model objecAve with
[Link](‘EXPRESION’, ‘SENSE’)
• Senses: [Link] and [Link]
LP Example
• Add the constraints with
[Link](‘LHS’, sense, ‘RHS’, name=‘’)
or [Link](‘expression’, “name”)
• Sense: [Link], GRB.LESS_EQUAL or
GRB.GREATER_EQUAL
LP Example
• We can write the formulaAon on a .lp file with
[Link]()
• Finally we want to solve the opAmizaAon
model with [Link]()
LP Example
• Once the problem is solved, we can access to
– ObjecAve FuncAon Value.
[Link]
– Variable values
[Link]()
LP Example
• Other way of solving a problem with Gurobi is
wriAng into a .lp file and reading the file and
solving it.
Cplex
• IBM ILOG CPLEX OpAmizaAon Studio is an
opAmizaAon sotware package.
• Cplex was named for the simplex method as
implemented in the C programming language.
• It was originally developed by Robert E. Bixby
and released on 1998 for the first Ame.
LP Example
LP Example
• First we need to import the cplex module
• We need to define the model with
[Link](). Inside the parentheses you can
add a name to the model. And the variable m
will be used every Ame we refer to the model
on Python.
LP Example
• Create the variables with [Link]()
• [Link](), takes the following
arguments
• types can be binary, conAnuous, integer,
semi_conAnuous or semi_integer.
LP Example
• Set the model objecAve [Link].set_linear
where each variable needs to be followed by
the coefficient.
• To set the objecAve sense, [Link].set_sense()
where the senses can be
[Link]/minimize
LP Example
• Add the constraints with
m.linear_constraints.add(lin_expr=[], senses=[], rhs=[],
names=‘’)
• To create the expression [Link]()
funcAon is needed.
• Senses: ‘G’, ‘L’ or ‘E’
LP Example
• We can write the formulaAon on a .lp file with
[Link]()
• Finally we want to solve the opAmizaAon
model with [Link]()
LP Example
• Once the problem is solved, we can access to
– ObjecAve funcAon value :
[Link].get_objecAve_value()
– Variable values:
[Link].get_values([‘variablesnames’])
LP Example
• Other way of solving a problem with Cplex is
wriAng into a .lp file and reading the file and
solving it.
Exercise