introduction python, cplex and gurobi - unisi.itdetti/introduction to python.pdf · gurobi • is a...

41
Introduction to Python, Cplex and Gurobi

Upload: others

Post on 19-Nov-2019

21 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Introduction Python, Cplex and Gurobi - unisi.itdetti/Introduction to Python.pdf · Gurobi • Is a commercial optimization solver. • It is named after its founders: Zonghao Gu,

Introduction to

Python,Cplex andGurobi

Page 2: Introduction Python, Cplex and Gurobi - unisi.itdetti/Introduction to Python.pdf · Gurobi • Is a commercial optimization solver. • It is named after its founders: Zonghao Gu,

• Pythonisawidelyused,highlevelprogramminglanguagedesignedbyGuidovanRossum andreleasedon1991.

• Twostablereleases:–Python2.7–Python3.5

Introduction

Page 3: Introduction Python, Cplex and Gurobi - unisi.itdetti/Introduction to Python.pdf · Gurobi • Is a commercial optimization solver. • It is named after its founders: Zonghao Gu,

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

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

Page 4: Introduction Python, Cplex and Gurobi - unisi.itdetti/Introduction to Python.pdf · Gurobi • Is a commercial optimization solver. • It is named after its founders: Zonghao Gu,

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

– Run->RunModule• OR

Page 5: Introduction Python, Cplex and Gurobi - unisi.itdetti/Introduction to Python.pdf · Gurobi • Is a commercial optimization solver. • It is named after its founders: Zonghao Gu,

Python• WewilluseJupyter Notebook->Writeandexecutecodeandwritetext.

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

• PythonNotebook

Page 6: Introduction Python, Cplex and Gurobi - unisi.itdetti/Introduction to Python.pdf · Gurobi • Is a commercial optimization solver. • It is named after its founders: Zonghao Gu,

BasicSyntax• Printstatement– Elementsseparatedbycommasareprintedwithaspaceinthemiddle.

– Operatorssuchas\nor\tindicatenewlineornewtab

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

Page 7: Introduction Python, Cplex and Gurobi - unisi.itdetti/Introduction to Python.pdf · Gurobi • Is a commercial optimization solver. • It is named after its founders: Zonghao Gu,

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 Gurobi - unisi.itdetti/Introduction to Python.pdf · Gurobi • Is a commercial optimization solver. • It is named after its founders: Zonghao Gu,

BasicSyntax• Blocksofcodearedenotedbylineindentation,nobracesareused.

OK

ERROR

Page 9: Introduction Python, Cplex and Gurobi - unisi.itdetti/Introduction to Python.pdf · Gurobi • Is a commercial optimization solver. • It is named after its founders: Zonghao Gu,

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

• AssignValuestoVariables

• Multipleassignment

Page 10: Introduction Python, Cplex and Gurobi - unisi.itdetti/Introduction to Python.pdf · Gurobi • Is a commercial optimization solver. • It is named after its founders: Zonghao Gu,

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

• Toconvertfromonetoother.

Page 11: Introduction Python, Cplex and Gurobi - unisi.itdetti/Introduction to Python.pdf · Gurobi • Is a commercial optimization solver. • It is named after its founders: Zonghao Gu,

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 Gurobi - unisi.itdetti/Introduction to Python.pdf · Gurobi • Is a commercial optimization solver. • It is named after its founders: Zonghao Gu,

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

Page 13: Introduction Python, Cplex and Gurobi - unisi.itdetti/Introduction to Python.pdf · Gurobi • Is a commercial optimization solver. • It is named after its founders: Zonghao Gu,

VariableTypes• Strings:createthemenclosingcharactersinquotes

Page 14: Introduction Python, Cplex and Gurobi - unisi.itdetti/Introduction to Python.pdf · Gurobi • Is a commercial optimization solver. • It is named after its founders: Zonghao Gu,

VariableTypes• Lists:containsitemsseparatedbycommasandenclosedwithinbrackets[]

Page 15: Introduction Python, Cplex and Gurobi - unisi.itdetti/Introduction to Python.pdf · Gurobi • Is a commercial optimization solver. • It is named after its founders: Zonghao Gu,

VariableTypes• Lists:containsitemsseparatedbycommasandenclosedwithinbrackets[]

Page 16: Introduction Python, Cplex and Gurobi - unisi.itdetti/Introduction to Python.pdf · Gurobi • Is a commercial optimization solver. • It is named after its founders: Zonghao Gu,

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 Gurobi - unisi.itdetti/Introduction to Python.pdf · Gurobi • Is a commercial optimization solver. • It is named after its founders: Zonghao Gu,

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

Page 18: Introduction Python, Cplex and Gurobi - unisi.itdetti/Introduction to Python.pdf · Gurobi • Is a commercial optimization solver. • It is named after its founders: Zonghao Gu,

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 Gurobi - unisi.itdetti/Introduction to Python.pdf · Gurobi • Is a commercial optimization solver. • It is named after its founders: Zonghao Gu,

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 Gurobi - unisi.itdetti/Introduction to Python.pdf · Gurobi • Is a commercial optimization solver. • It is named after its founders: Zonghao Gu,

DecisionMaking• Conditionalstatements

Example:

Page 21: Introduction Python, Cplex and Gurobi - unisi.itdetti/Introduction to Python.pdf · Gurobi • Is a commercial optimization solver. • It is named after its founders: Zonghao Gu,

Loops• Statementsareexecutedsequentially.

while:

LoopType Descriptionwhile Repeats astatementwhileagivenconditionistrue

for Executesasequenceofstatement multipletimes

Page 22: Introduction Python, Cplex and Gurobi - unisi.itdetti/Introduction to Python.pdf · Gurobi • Is a commercial optimization solver. • It is named after its founders: Zonghao Gu,

Loops• Statementsareexecutedsequentially.

for:

• Forallowstoiteratealongtheitemsofanysequence,thatcanbealist.Alsorangefunctioncanbeused.

LoopType Descriptionwhile Repeats astatementwhileagivenconditionistrue

for Executesasequenceofstatement multipletimes.

Page 23: Introduction Python, Cplex and Gurobi - unisi.itdetti/Introduction to Python.pdf · Gurobi • Is a commercial optimization solver. • It is named after its founders: Zonghao Gu,

LoopsFor:

Page 24: Introduction Python, Cplex and Gurobi - unisi.itdetti/Introduction to Python.pdf · Gurobi • Is a commercial optimization solver. • It is named after its founders: Zonghao Gu,

Loops• Controlstatements.

Statement Descriptionbreak Terminatestheloopandtransfertheexecutiontothe

followingstatementafter theloop

continue Causes thelooptoskiptheremainderofitsbodyandimmediatelyretestitsconditionpriortoreiterating.

pass Used whenastatementisrequiredbutnotwanttoexecuteanythingonit.

Page 25: Introduction Python, Cplex and Gurobi - unisi.itdetti/Introduction to Python.pdf · Gurobi • Is a commercial optimization solver. • It is named after its founders: Zonghao Gu,

Functions• Functionscanbedefinedtoprovidetherequiredfunctionality– Blocksbeginwithdef followedbythenameandparentheses()

– Anyinputshouldbeplacedwithintheparentheses

– Thestatementreturn[]exitsafunction.• Tocallthefunctionjustwritethenameofthefunctionandtheinputparameters.

Page 26: Introduction Python, Cplex and Gurobi - unisi.itdetti/Introduction to Python.pdf · Gurobi • Is a commercial optimization solver. • It is named after its founders: Zonghao Gu,

Functions• Example

Page 27: Introduction Python, Cplex and Gurobi - unisi.itdetti/Introduction to Python.pdf · Gurobi • Is a commercial optimization solver. • It is named after its founders: Zonghao Gu,

Functions• Allparametersarepassedbyreference.Ifyouchangethevalueofanargumentthatwasaninputinsidethefunction,itwillbechangedalsooutside.

• Butifavariable(withthesamename)isredefinedinsidethefunctionthatwillnotchangethevalueoutsidethefunction

Page 28: Introduction Python, Cplex and Gurobi - unisi.itdetti/Introduction to Python.pdf · Gurobi • Is a commercial optimization solver. • It is named after its founders: Zonghao Gu,

Functions

Page 29: Introduction Python, Cplex and Gurobi - unisi.itdetti/Introduction to Python.pdf · Gurobi • Is a commercial optimization solver. • It is named after its founders: Zonghao Gu,

FilesI/O• Pythonprovidesbasicfunctionstoreadandwritefiles.

• OPEN:beforeyoucanreadorwriteafileitneedstobeopened.

Modes Descriptionr Opens afilereadingonly.

r+ Opensafileforbothreadingand writing.

w Opensafileforwritingonly.

w+ Opens afileforbothwritingandreading.

Page 30: Introduction Python, Cplex and Gurobi - unisi.itdetti/Introduction to Python.pdf · Gurobi • Is a commercial optimization solver. • It is named after its founders: Zonghao Gu,

FilesI/O• Close()closesthefileandnomorewritingcanbedone.

• Write()writesanystringtoanopenfile.

• Read()readsastringfromanopenfile.– readline()

Page 31: Introduction Python, Cplex and Gurobi - unisi.itdetti/Introduction to Python.pdf · Gurobi • Is a commercial optimization solver. • It is named after its founders: Zonghao Gu,

Modules• AmoduleallowsyoutologicallyorganizeyourPythoncode.

• Themodules,suchasCplex orGurobi modulearecalledasfollows

Page 32: Introduction Python, Cplex and Gurobi - unisi.itdetti/Introduction to Python.pdf · Gurobi • Is a commercial optimization solver. • It is named after its founders: Zonghao Gu,

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

• ItsupportsavarietyofprogrammingandmodellinglanguagesincludingPython,C++,etc.

• Installationfromwww.gurobi.com andanaccademicfreelicensecanberequested.

Page 33: Introduction Python, Cplex and Gurobi - unisi.itdetti/Introduction to Python.pdf · Gurobi • Is a commercial optimization solver. • It is named after its founders: Zonghao Gu,

LPExample

Page 34: Introduction Python, Cplex and Gurobi - unisi.itdetti/Introduction to Python.pdf · Gurobi • Is a commercial optimization solver. • It is named after its founders: Zonghao Gu,

LPExample• Firstweneedtoimportthegurobi module

• WeneedtodefinethemodelwithModel().Insidetheparenthesesyoucanaddanametothemodel.AndthevariablemwillbeusedeverytimewerefertothemodelonPython.

Page 35: Introduction Python, Cplex and Gurobi - unisi.itdetti/Introduction to Python.pdf · Gurobi • Is a commercial optimization solver. • It is named after its founders: Zonghao Gu,

LPExample• Createthevariableswithmodel.addVar()

• model.addVar(),takesthefollowingarguments

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

Page 36: Introduction Python, Cplex and Gurobi - unisi.itdetti/Introduction to Python.pdf · Gurobi • Is a commercial optimization solver. • It is named after its founders: Zonghao Gu,

LPExample• Tointegratenewvariables,model.update()

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

• Senses:GRB.MAXIMIZEandGRB.MINIMIZE

Page 37: Introduction Python, Cplex and Gurobi - unisi.itdetti/Introduction to Python.pdf · Gurobi • Is a commercial optimization solver. • It is named after its founders: Zonghao Gu,

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 Gurobi - unisi.itdetti/Introduction to Python.pdf · Gurobi • Is a commercial optimization solver. • It is named after its founders: Zonghao Gu,

LPExample• Wecanwritetheformulationona.lp filewithmodel.write()

• Finallywewanttosolvetheoptimizationmodelwithmodel.optimize()

Page 39: Introduction Python, Cplex and Gurobi - unisi.itdetti/Introduction to Python.pdf · Gurobi • Is a commercial optimization solver. • It is named after its founders: Zonghao Gu,

LPExample• Oncetheproblemissolved,wecanaccessto– ObjectiveFunctionValue.

m.objval

– Variablevaluesm.getVars()

Page 40: Introduction Python, Cplex and Gurobi - unisi.itdetti/Introduction to Python.pdf · Gurobi • Is a commercial optimization solver. • It is named after its founders: Zonghao Gu,

LPExample• OtherwayofsolvingaproblemwithGurobi iswritingintoa.lp fileandreadingthefileandsolvingit.

Page 41: Introduction Python, Cplex and Gurobi - unisi.itdetti/Introduction to Python.pdf · Gurobi • Is a commercial optimization solver. • It is named after its founders: Zonghao Gu,

Exercise