Introduction to Python, Cplex and Gurobi
Introduction 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 interactive 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. OR File -> New File Write the program and save it with the extension.py Run -> Run Module
Python We will use Jupyter Notebook -> Write and execute code and write text. Open Terminal /opt/anaconda/bin/jupyter notebook Python Notebook
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 initialized by # Python identifiers have to start with a letter A to Z (a to z) or an underscore ( _ ) followed by letters or numbers. Reserved words And Assert Break Class Continue 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 indentation, no braces are used. OK ERROR
Variable Types Five standard data types: numbers, string, list, tuple and dictionary. Assign Values to Variables Multiple assignment
Variable Types Numbers: four numerical types are supported Int (integers), long (long integers), float (floating point real values) and complex (complex numbers) To convert from one to other.
Variable Types Some functions with numbers Function Description Function Description 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 Function: sum([thing to sum] [iteration]) If we want to sum the following numbers 4 6 7
Variable Types Strings: create them enclosing characters in quotes
Variable Types Lists: contains items separated by commas and enclosed within brackets [ ]
Variable Types Lists: contains items separated by commas and enclosed within brackets [ ]
Variable Types Some functions of lists Function len(a) max(a) min(a) A.append(x) A.count(x) A.insert(i,x) A.remove(x) A.reverse() A.sort() Description Returns length of the list Returns item from list A with the max value Returns item from list A with the min value Appends x to list A Returns how many times x is in list A Inserts x in list A in position i Removes x from list A Reverses list A Sorts objects of list A
Variable Types DATA TYPE COVERSION: To convert between types you only use the type name as a function. From anything to string str() From anything to integer int() From anything to floating point float()
Basic Operators Arithmetic Operators + Addition / Division - Substraction % Module * Multiplication ** 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 Multiplies 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 or not True if both operators are true True if ONE of the operators is true Negation operator
Decision Making Conditional statements Example:
Loops Statements are executed sequentially. while: Loop Type while for Description Repeats a statement while a given condition is true Executes a sequence of statement multiple times
Loops Statements are executed sequentially. for: Loop Type while for Description Repeats a statement while a given condition is true Executes a sequence of statement multiple times. For allows to iterate along the items of any sequence, that can be a list. Also range function can be used.
For: Loops
Loops Control statements. Statement break continue pass Description Terminates the loop and transfer the execution to the following statement after the loop Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating. Used when a statement is required but not want to execute anything on it.
Functions Functions can be defined to provide the required functionality Blocks begin with def followed by the name and parentheses ( ) Any input should be placed within the parentheses The statement return [ ] exits a function. To call the function just write the name of the function and the input parameters.
Example Functions
Functions All parameters are passed by reference. If you change the value of an argument that was an input inside the function, it will be changed also outside. But if a variable (with the same name) is redefined inside the function that will not change the value outside the function
Functions
Files I/O Python provides basic functions to read and write files. OPEN: before you can read or write a file it needs to be opened. Modes Description r Opens a file reading only. r+ Opens a file for both reading and writing. w Opens a file for writing only. w+ Opens a file for both writing and reading.
Files I/O Close() closes the file and no more writing 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 optimization solver. It is named after its founders: Zonghao Gu, Edward Rothberg and Robert Bixby. It supports a variety of programming and modelling languages including Python, C++, etc. Installation from www.gurobi.com 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 time we refer to the model on Python.
LP Example Create the variables with model.addvar() model.addvar(), takes the following arguments vtype can be GRB.BINARY, GRB.CONTINUOUS, GRB.INTEGER, GRB.SEMICONT or GRB.SEMIINT
LP Example To integrate new variables, model.update() Set the model objective with model.setobjective( EXPRESION, SENSE ) Senses: GRB.MAXIMIZE and GRB.MINIMIZE
LP Example Add the constraints with model.addconstr( LHS, sense, RHS, name= ) or model.addconstr( expression, name ) Sense: GRB.EQUAL, GRB.LESS_EQUAL or GRB.GREATER_EQUAL
LP Example We can write the formulation on a.lp file with model.write() Finally we want to solve the optimization model with model.optimize()
LP Example Once the problem is solved, we can access to Objective Function Value. m.objval Variable values m.getvars()
LP Example Other way of solving a problem with Gurobi is writing into a.lp file and reading the file and solving it.
Exercise