Introduction to Python, Cplex and Gurobi

Similar documents
Python Lists: Example 1: >>> items=["apple", "orange",100,25.5] >>> items[0] 'apple' >>> 3*items[:2]

Introduction to Computer Programming in Python Dr. William C. Bulko. Data Types

Ordinary Differential Equation Solver Language (ODESL) Reference Manual

CSI31 Lecture 5. Topics: 3.1 Numeric Data Types 3.2 Using the Math Library 3.3 Accumulating Results: Factorial

Variable and Data Type 2

Getting Started. Office Hours. CSE 231, Rich Enbody. After class By appointment send an . Michigan State University CSE 231, Fall 2013

PROGRAMMING WITH MATLAB DR. AHMET AKBULUT

Introduction to Programming

Introduction to Engineering gii

Methods CSC 121 Fall 2014 Howard Rosenthal

Sketchify Tutorial Properties and Variables. sketchify.sf.net Željko Obrenović

Chapter 2. Outline. Simple C++ Programs

Python Input, output and variables. Lecture 23 COMPSCI111/111G SS 2018

Data Types and Basic Calculation

Arithmetic. 2.2.l Basic Arithmetic Operations. 2.2 Arithmetic 37

9 Using Equation Networks

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

Engineering Problem Solving with C++, Etter/Ingber

Variable and Data Type I

CSCE 110 Programming I Basics of Python: Variables, Expressions, Input/Output

C++ Programming Lecture 11 Functions Part I

Goals for This Lecture:

C++ Overview. Chapter 1. Chapter 2

Introduction to MATLAB. Computational Probability and Statistics CIS 2033 Section 003

Lesson #3. Variables, Operators, and Expressions. 3. Variables, Operators and Expressions - Copyright Denis Hamelin - Ryerson University

Downloaded from Chapter 2. Functions

Short, Unique and Mysterious

Introduction to Computer Programming CSCI-UA 2. Review Midterm Exam 1

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

Product Price Formula extension for Magento2. User Guide

Table of Contents EVALUATION COPY

Built-in Types of Data

Custom Variables (Virtual Variables)

Matlab Programming Introduction 1 2

2 Making Decisions. Store the value 3 in memory location y

CT 229 Java Syntax Continued

Basic Syntax - First Program 1

Functions and Inverses ID1050 Quantitative & Qualitative Reasoning

XQ: An XML Query Language Language Reference Manual

ME 142 Engineering Computation I. Unit 1.2 Excel Functions

Variable and Data Type I

6-1 (Function). (Function) !*+!"#!, Function Description Example. natural logarithm of x (base e) rounds x to smallest integer not less than x

There are two ways to use the python interpreter: interactive mode and script mode. (a) open a terminal shell (terminal emulator in Applications Menu)

Chapter 4: Basic C Operators

Programming in QBasic

There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals:

Jython. secondary. memory

Outline. CSE 1570 Interacting with MATLAB. Starting MATLAB. Outline (Cont d) MATLAB Windows. MATLAB Desktop Window. Instructor: Aijun An

ANSI C Programming Simple Programs

Outline. CSE 1570 Interacting with MATLAB. Starting MATLAB. Outline. MATLAB Windows. MATLAB Desktop Window. Instructor: Aijun An.

Methods CSC 121 Fall 2016 Howard Rosenthal

USER-DEFINED ELEMENT IN ZMAN TM

MYSQL NUMERIC FUNCTIONS

Maths Functions User Manual

CHAPTER 2: Introduction to Python COMPUTER PROGRAMMING SKILLS

Methods CSC 121 Spring 2017 Howard Rosenthal

Python Input, output and variables

There are two ways to use the python interpreter: interactive mode and script mode. (a) open a terminal shell (terminal emulator in Applications Menu)

Python Input, output and variables. Lecture 22 COMPSCI111/111G SS 2016

ENGR 101 Engineering Design Workshop

What is MATLAB? What is MATLAB? Programming Environment MATLAB PROGRAMMING. Stands for MATrix LABoratory. A programming environment

And Parallelism. Parallelism in Prolog. OR Parallelism

Chapter 2 Getting Started with Python

Introduction to MATLAB

Expressions. Eric McCreath

Python. Objects. Geog 271 Geographic Data Analysis Fall 2010

Computer Science & Engineering 150A Problem Solving Using Computers

PYTHON FOR KIDS A Pl ayfu l I ntrodu ctio n to Prog r am m i ng J a s o n R. B r i g g s

Beyond Blocks: Python Session #1

Computer Science & Engineering 150A Problem Solving Using Computers. Chapter 3. Existing Information. Notes. Notes. Notes. Lecture 03 - Functions

The Number object. to set specific number types (like integer, short, In JavaScript all numbers are 64bit floating point

Chapter 3. Computer Science & Engineering 155E Computer Science I: Systems Engineering Focus. Existing Information.

Operators Functions Order of Operations Mixed Mode Arithmetic VOID Data. Syntax and type conventions Using the Script window interface

Introduction to MATLAB

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Python Intro GIS Week 1. Jake K. Carr

Chapter 1 Introduction to MATLAB

Chapter 3 : Informatics Practices. Class XI ( As per CBSE Board) Python Fundamentals. Visit : python.mykvs.in for regular updates

06/11/2014. Subjects. CS Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / ) Beginning with Python

Introduction to Matlab

Introduction to MATLAB

CSCE 110 Programming I

Outline. CSE 1570 Interacting with MATLAB. Outline. Starting MATLAB. MATLAB Windows. MATLAB Desktop Window. Instructor: Aijun An.

Quick MATLAB Syntax Guide

Fundamentals of Programming & Procedural Programming

Some material adapted from Upenn cmpe391 slides and other sources

Operations. Making Things Happen

Programming in MATLAB

Chapter 2 Writing Simple Programs

TECH TIP VISION Calibration and Data Acquisition Software

SECTION 1: INTRODUCTION. ENGR 112 Introduction to Engineering Computing

The Three Rules. Program. What is a Computer Program? 5/30/2018. Interpreted. Your First Program QuickStart 1. Chapter 1

Part V Appendices c Copyright, Todd Young and Martin Mohlenkamp, Department of Mathematics, Ohio University, 2017

Digital Image Analysis and Processing CPE

DaMPL. Language Reference Manual. Henrique Grando

Variables, expressions and statements

Python I. Some material adapted from Upenn cmpe391 slides and other sources

History Installing & Running Python Names & Assignment Sequences types: Lists, Tuples, and Strings Mutability

VBScript: Math Functions

Week 2: Console I/O and Operators Arithmetic Operators. Integer Division. Arithmetic Operators. Gaddis: Chapter 3 (2.14,3.1-6,3.9-10,5.

Transcription:

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