introduction python, cplex and gurobidetti/introduction to python... · 2017-05-25 · • vtypecan...

41
Introduction to Python, Cplex and Gurobi

Upload: others

Post on 22-Jan-2020

8 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Introduction Python, Cplex and Gurobidetti/Introduction to Python... · 2017-05-25 · • vtypecan be GRB.BINARY, GRB.CONTINUOUS, GRB.INTEGER, GRB.SEMICONT or GRB.SEMIINT. LP Example

Introduction to

Python,Cplex andGurobi

Page 2: Introduction Python, Cplex and Gurobidetti/Introduction to Python... · 2017-05-25 · • vtypecan be GRB.BINARY, GRB.CONTINUOUS, GRB.INTEGER, GRB.SEMICONT or GRB.SEMIINT. LP Example

• Pythonisawidelyused,highlevelprogramminglanguagedesignedbyGuidovanRossum andreleasedon1991.

• Twostablereleases:–Python2.7–Python3.5

Introduction

Page 3: Introduction Python, Cplex and Gurobidetti/Introduction to Python... · 2017-05-25 · • vtypecan be GRB.BINARY, GRB.CONTINUOUS, GRB.INTEGER, GRB.SEMICONT or GRB.SEMIINT. LP Example

Python• ToopenStartMenu->Python27->IDLE• Pythonisaninteractiveinterpretedlanguage,soyoucaninteractdirectlywiththePythonprompttowriteaprogram.

• Forexample,writeontheprompt– Print(‘HelloWorld!’)– 2+4or2<4

Page 4: Introduction Python, Cplex and Gurobidetti/Introduction to Python... · 2017-05-25 · • vtypecan be GRB.BINARY, GRB.CONTINUOUS, GRB.INTEGER, GRB.SEMICONT or GRB.SEMIINT. LP Example

Python• PythonpromptcanbeusedtowriteaprogramdirectlyOR• APythonscriptcanbecreated.– File->NewFile–Writetheprogramandsaveitwiththeextension.py

– Run->RunModule• OR

Page 5: Introduction Python, Cplex and Gurobidetti/Introduction to Python... · 2017-05-25 · • vtypecan be GRB.BINARY, GRB.CONTINUOUS, GRB.INTEGER, GRB.SEMICONT or GRB.SEMIINT. LP Example

Python• WewilluseJupyter Notebook->Writeandexecutecodeandwritetext.

• OpenTerminal• /opt/anaconda/bin/jupyter notebook

• PythonNotebook

Page 6: Introduction Python, Cplex and Gurobidetti/Introduction to Python... · 2017-05-25 · • vtypecan be GRB.BINARY, GRB.CONTINUOUS, GRB.INTEGER, GRB.SEMICONT or GRB.SEMIINT. LP Example

BasicSyntax• Printstatement– Elementsseparatedbycommasareprintedwithaspaceinthemiddle.

– Operatorssuchas\nor\tindicatenewlineornewtab

– All‘– “– ‘’’or“””indicatethesamething.

Page 7: Introduction Python, Cplex and Gurobidetti/Introduction to Python... · 2017-05-25 · • vtypecan be GRB.BINARY, GRB.CONTINUOUS, GRB.INTEGER, GRB.SEMICONT or GRB.SEMIINT. LP Example

BasicSyntax• Comments areinitializedby#

• PythonidentifiershavetostartwithaletterAtoZ(atoz)oranunderscore(_)followedbylettersornumbers.

• ReservedwordsAnd 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

Page 8: Introduction Python, Cplex and Gurobidetti/Introduction to Python... · 2017-05-25 · • vtypecan be GRB.BINARY, GRB.CONTINUOUS, GRB.INTEGER, GRB.SEMICONT or GRB.SEMIINT. LP Example

BasicSyntax• Blocksofcodearedenotedbylineindentation,nobracesareused.

OK

ERROR

Page 9: Introduction Python, Cplex and Gurobidetti/Introduction to Python... · 2017-05-25 · • vtypecan be GRB.BINARY, GRB.CONTINUOUS, GRB.INTEGER, GRB.SEMICONT or GRB.SEMIINT. LP Example

VariableTypes• Fivestandarddatatypes:numbers,string,list,tupleanddictionary.

• AssignValuestoVariables

• Multipleassignment

Page 10: Introduction Python, Cplex and Gurobidetti/Introduction to Python... · 2017-05-25 · • vtypecan be GRB.BINARY, GRB.CONTINUOUS, GRB.INTEGER, GRB.SEMICONT or GRB.SEMIINT. LP Example

VariableTypes• Numbers:fournumericaltypesaresupported– Int (integers),long (longintegers),float (floatingpointrealvalues)andcomplex (complexnumbers)

• Toconvertfromonetoother.

Page 11: Introduction Python, Cplex and Gurobidetti/Introduction to Python... · 2017-05-25 · • vtypecan be GRB.BINARY, GRB.CONTINUOUS, GRB.INTEGER, GRB.SEMICONT or GRB.SEMIINT. LP Example

VariableTypes• Somefunctionswithnumbers

Function Description Function Descriptionabs(x) Absolute valueofx acos(x) Arccosineofx, radians

ceil(x) Smallest integernotlessx asin(x) Arcsineofx,randians

exp(x) e^x atan(x) Arctangentof x,radians

log(x) Naturallogarithmofx cos(x) Cosine ofx,radians

log10(x) Base10logarithmofx sin(x) Sineofx,radians

max(x1,…,xn) Max valueofarguments tan(x) Tangentofx,radians

min(x1,…,xn) Minvalueofarguments degrees(x) Convertfromradians todegre

pow(x,y) x^y radians(x) Convert fromdegreetorad

sqrt(x) Squarerootofx pi e Constants piande

Page 12: Introduction Python, Cplex and Gurobidetti/Introduction to Python... · 2017-05-25 · • vtypecan be GRB.BINARY, GRB.CONTINUOUS, GRB.INTEGER, GRB.SEMICONT or GRB.SEMIINT. LP Example

VariableTypes• Function:sum([thingtosum] [iteration])– Ifwewanttosumthefollowingnumbers467

Page 13: Introduction Python, Cplex and Gurobidetti/Introduction to Python... · 2017-05-25 · • vtypecan be GRB.BINARY, GRB.CONTINUOUS, GRB.INTEGER, GRB.SEMICONT or GRB.SEMIINT. LP Example

VariableTypes• Strings:createthemenclosingcharactersinquotes

Page 14: Introduction Python, Cplex and Gurobidetti/Introduction to Python... · 2017-05-25 · • vtypecan be GRB.BINARY, GRB.CONTINUOUS, GRB.INTEGER, GRB.SEMICONT or GRB.SEMIINT. LP Example

VariableTypes• Lists:containsitemsseparatedbycommasandenclosedwithinbrackets[]

Page 15: Introduction Python, Cplex and Gurobidetti/Introduction to Python... · 2017-05-25 · • vtypecan be GRB.BINARY, GRB.CONTINUOUS, GRB.INTEGER, GRB.SEMICONT or GRB.SEMIINT. LP Example

VariableTypes• Lists:containsitemsseparatedbycommasandenclosedwithinbrackets[]

Page 16: Introduction Python, Cplex and Gurobidetti/Introduction to Python... · 2017-05-25 · • vtypecan be GRB.BINARY, GRB.CONTINUOUS, GRB.INTEGER, GRB.SEMICONT or GRB.SEMIINT. LP Example

VariableTypes• Somefunctionsoflists

Function Descriptionlen(A) Returns length ofthelist

max(A) Returnsitemfrom listAwiththemaxvalue

min(A) Returnsitemfrom listAwiththeminvalue

A.append(x) AppendsxtolistA

A.count(x) ReturnshowmanytimesxisinlistA

A.insert(i,x) InsertsxinlistAinpositioni

A.remove(x) Removesx fromlistA

A.reverse() ReverseslistA

A.sort() SortsobjectsoflistA

Page 17: Introduction Python, Cplex and Gurobidetti/Introduction to Python... · 2017-05-25 · • vtypecan be GRB.BINARY, GRB.CONTINUOUS, GRB.INTEGER, GRB.SEMICONT or GRB.SEMIINT. LP Example

VariableTypes• DATATYPECOVERSION:Toconvertbetweentypesyouonlyusethetypenameasafunction.– Fromanythingtostring str()– Fromanythingtointeger int()– Fromanythingtofloatingpoint float()

Page 18: Introduction Python, Cplex and Gurobidetti/Introduction to Python... · 2017-05-25 · • vtypecan be GRB.BINARY, GRB.CONTINUOUS, GRB.INTEGER, GRB.SEMICONT or GRB.SEMIINT. LP Example

BasicOperators• ArithmeticOperators

• ComparisonOperators

+ Addition / Division

- Substraction % Module

* Multiplication ** Exponent

a==b True ifvaluesareequal a<b Trueifalessthanb

a!=b Trueifvalues arenotequal a>=b True ifagreaterorequalthanb

a>b Trueifagreaterthanb a<=b Trueifaislessorequalthan b

Page 19: Introduction Python, Cplex and Gurobidetti/Introduction to Python... · 2017-05-25 · • vtypecan be GRB.BINARY, GRB.CONTINUOUS, GRB.INTEGER, GRB.SEMICONT or GRB.SEMIINT. LP Example

BasicOperators• AssignmentOperators

• LogicalOperators

a=b Assignvalueofbtoa a*=b Multipliesawithb,assignstoa

a+=b Addsbtoa,assign toa a/=b Dividesawithb,assignstoa

a-=b Subtractsbtoa,assign toa a**=b a^b andassignstoa

and True ifbothoperatorsaretrue

or True ifONEoftheoperatorsistrue

not Negationoperator

Page 20: Introduction Python, Cplex and Gurobidetti/Introduction to Python... · 2017-05-25 · • vtypecan be GRB.BINARY, GRB.CONTINUOUS, GRB.INTEGER, GRB.SEMICONT or GRB.SEMIINT. LP Example

DecisionMaking• Conditionalstatements

Example:

Page 21: Introduction Python, Cplex and Gurobidetti/Introduction to Python... · 2017-05-25 · • vtypecan be GRB.BINARY, GRB.CONTINUOUS, GRB.INTEGER, GRB.SEMICONT or GRB.SEMIINT. LP Example

Loops• Statementsareexecutedsequentially.

while:

LoopType Descriptionwhile Repeats astatementwhileagivenconditionistrue

for Executesasequenceofstatement multipletimes

Page 22: Introduction Python, Cplex and Gurobidetti/Introduction to Python... · 2017-05-25 · • vtypecan be GRB.BINARY, GRB.CONTINUOUS, GRB.INTEGER, GRB.SEMICONT or GRB.SEMIINT. LP Example

Loops• Statementsareexecutedsequentially.

for:

• Forallowstoiteratealongtheitemsofanysequence,thatcanbealist.Alsorangefunctioncanbeused.

LoopType Descriptionwhile Repeats astatementwhileagivenconditionistrue

for Executesasequenceofstatement multipletimes.

Page 23: Introduction Python, Cplex and Gurobidetti/Introduction to Python... · 2017-05-25 · • vtypecan be GRB.BINARY, GRB.CONTINUOUS, GRB.INTEGER, GRB.SEMICONT or GRB.SEMIINT. LP Example

LoopsFor:

Page 24: Introduction Python, Cplex and Gurobidetti/Introduction to Python... · 2017-05-25 · • vtypecan be GRB.BINARY, GRB.CONTINUOUS, GRB.INTEGER, GRB.SEMICONT or GRB.SEMIINT. LP Example

Loops• Controlstatements.

Statement Descriptionbreak Terminatestheloopandtransfertheexecutiontothe

followingstatementafter theloop

continue Causes thelooptoskiptheremainderofitsbodyandimmediatelyretestitsconditionpriortoreiterating.

pass Used whenastatementisrequiredbutnotwanttoexecuteanythingonit.

Page 25: Introduction Python, Cplex and Gurobidetti/Introduction to Python... · 2017-05-25 · • vtypecan be GRB.BINARY, GRB.CONTINUOUS, GRB.INTEGER, GRB.SEMICONT or GRB.SEMIINT. LP Example

Functions• Functionscanbedefinedtoprovidetherequiredfunctionality– Blocksbeginwithdef followedbythenameandparentheses()

– Anyinputshouldbeplacedwithintheparentheses

– Thestatementreturn[]exitsafunction.• Tocallthefunctionjustwritethenameofthefunctionandtheinputparameters.

Page 26: Introduction Python, Cplex and Gurobidetti/Introduction to Python... · 2017-05-25 · • vtypecan be GRB.BINARY, GRB.CONTINUOUS, GRB.INTEGER, GRB.SEMICONT or GRB.SEMIINT. LP Example

Functions• Example

Page 27: Introduction Python, Cplex and Gurobidetti/Introduction to Python... · 2017-05-25 · • vtypecan be GRB.BINARY, GRB.CONTINUOUS, GRB.INTEGER, GRB.SEMICONT or GRB.SEMIINT. LP Example

Functions• Allparametersarepassedbyreference.Ifyouchangethevalueofanargumentthatwasaninputinsidethefunction,itwillbechangedalsooutside.

• Butifavariable(withthesamename)isredefinedinsidethefunctionthatwillnotchangethevalueoutsidethefunction

Page 28: Introduction Python, Cplex and Gurobidetti/Introduction to Python... · 2017-05-25 · • vtypecan be GRB.BINARY, GRB.CONTINUOUS, GRB.INTEGER, GRB.SEMICONT or GRB.SEMIINT. LP Example

Functions

Page 29: Introduction Python, Cplex and Gurobidetti/Introduction to Python... · 2017-05-25 · • vtypecan be GRB.BINARY, GRB.CONTINUOUS, GRB.INTEGER, GRB.SEMICONT or GRB.SEMIINT. LP Example

FilesI/O• Pythonprovidesbasicfunctionstoreadandwritefiles.

• OPEN:beforeyoucanreadorwriteafileitneedstobeopened.

Modes Descriptionr Opens afilereadingonly.

r+ Opensafileforbothreadingand writing.

w Opensafileforwritingonly.

w+ Opens afileforbothwritingandreading.

Page 30: Introduction Python, Cplex and Gurobidetti/Introduction to Python... · 2017-05-25 · • vtypecan be GRB.BINARY, GRB.CONTINUOUS, GRB.INTEGER, GRB.SEMICONT or GRB.SEMIINT. LP Example

FilesI/O• Close()closesthefileandnomorewritingcanbedone.

• Write()writesanystringtoanopenfile.

• Read()readsastringfromanopenfile.– readline()

Page 31: Introduction Python, Cplex and Gurobidetti/Introduction to Python... · 2017-05-25 · • vtypecan be GRB.BINARY, GRB.CONTINUOUS, GRB.INTEGER, GRB.SEMICONT or GRB.SEMIINT. LP Example

Modules• AmoduleallowsyoutologicallyorganizeyourPythoncode.

• Themodules,suchasCplex orGurobi modulearecalledasfollows

Page 32: Introduction Python, Cplex and Gurobidetti/Introduction to Python... · 2017-05-25 · • vtypecan be GRB.BINARY, GRB.CONTINUOUS, GRB.INTEGER, GRB.SEMICONT or GRB.SEMIINT. LP Example

Gurobi• Isacommercialoptimizationsolver.• Itisnamedafteritsfounders:Zonghao Gu,EdwardRothbergandRobertBixby.

• ItsupportsavarietyofprogrammingandmodellinglanguagesincludingPython,C++,etc.

• Installationfromwww.gurobi.com andanaccademicfreelicensecanberequested.

Page 33: Introduction Python, Cplex and Gurobidetti/Introduction to Python... · 2017-05-25 · • vtypecan be GRB.BINARY, GRB.CONTINUOUS, GRB.INTEGER, GRB.SEMICONT or GRB.SEMIINT. LP Example

LPExample

Page 34: Introduction Python, Cplex and Gurobidetti/Introduction to Python... · 2017-05-25 · • vtypecan be GRB.BINARY, GRB.CONTINUOUS, GRB.INTEGER, GRB.SEMICONT or GRB.SEMIINT. LP Example

LPExample• Firstweneedtoimportthegurobi module

• WeneedtodefinethemodelwithModel().Insidetheparenthesesyoucanaddanametothemodel.AndthevariablemwillbeusedeverytimewerefertothemodelonPython.

Page 35: Introduction Python, Cplex and Gurobidetti/Introduction to Python... · 2017-05-25 · • vtypecan be GRB.BINARY, GRB.CONTINUOUS, GRB.INTEGER, GRB.SEMICONT or GRB.SEMIINT. LP Example

LPExample• Createthevariableswithmodel.addVar()

• model.addVar(),takesthefollowingarguments

• vtype canbeGRB.BINARY,GRB.CONTINUOUS,GRB.INTEGER,GRB.SEMICONTorGRB.SEMIINT

Page 36: Introduction Python, Cplex and Gurobidetti/Introduction to Python... · 2017-05-25 · • vtypecan be GRB.BINARY, GRB.CONTINUOUS, GRB.INTEGER, GRB.SEMICONT or GRB.SEMIINT. LP Example

LPExample• Tointegratenewvariables,model.update()

• Setthemodelobjectivewithmodel.setObjective(‘EXPRESION’,‘SENSE’)

• Senses:GRB.MAXIMIZEandGRB.MINIMIZE

Page 37: Introduction Python, Cplex and Gurobidetti/Introduction to Python... · 2017-05-25 · • vtypecan be GRB.BINARY, GRB.CONTINUOUS, GRB.INTEGER, GRB.SEMICONT or GRB.SEMIINT. LP Example

LPExample• Addtheconstraintswithmodel.addConstr(‘LHS’,sense,‘RHS’,name=‘’)ormodel.addConstr(‘expression’,“name”)

• Sense:GRB.EQUAL,GRB.LESS_EQUALorGRB.GREATER_EQUAL

Page 38: Introduction Python, Cplex and Gurobidetti/Introduction to Python... · 2017-05-25 · • vtypecan be GRB.BINARY, GRB.CONTINUOUS, GRB.INTEGER, GRB.SEMICONT or GRB.SEMIINT. LP Example

LPExample• Wecanwritetheformulationona.lp filewithmodel.write()

• Finallywewanttosolvetheoptimizationmodelwithmodel.optimize()

Page 39: Introduction Python, Cplex and Gurobidetti/Introduction to Python... · 2017-05-25 · • vtypecan be GRB.BINARY, GRB.CONTINUOUS, GRB.INTEGER, GRB.SEMICONT or GRB.SEMIINT. LP Example

LPExample• Oncetheproblemissolved,wecanaccessto– ObjectiveFunctionValue.

m.objval

– Variablevaluesm.getVars()

Page 40: Introduction Python, Cplex and Gurobidetti/Introduction to Python... · 2017-05-25 · • vtypecan be GRB.BINARY, GRB.CONTINUOUS, GRB.INTEGER, GRB.SEMICONT or GRB.SEMIINT. LP Example

LPExample• OtherwayofsolvingaproblemwithGurobi iswritingintoa.lp fileandreadingthefileandsolvingit.

Page 41: Introduction Python, Cplex and Gurobidetti/Introduction to Python... · 2017-05-25 · • vtypecan be GRB.BINARY, GRB.CONTINUOUS, GRB.INTEGER, GRB.SEMICONT or GRB.SEMIINT. LP Example

Exercise