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

Post on 19-Nov-2019

23 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Introduction to

Python,Cplex andGurobi

• Pythonisawidelyused,highlevelprogramminglanguagedesignedbyGuidovanRossum andreleasedon1991.

• Twostablereleases:–Python2.7–Python3.5

Introduction

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

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

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

– Run->RunModule• OR

Python• WewilluseJupyter Notebook->Writeandexecutecodeandwritetext.

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

• PythonNotebook

BasicSyntax• Printstatement– Elementsseparatedbycommasareprintedwithaspaceinthemiddle.

– Operatorssuchas\nor\tindicatenewlineornewtab

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

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

BasicSyntax• Blocksofcodearedenotedbylineindentation,nobracesareused.

OK

ERROR

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

• AssignValuestoVariables

• Multipleassignment

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

• Toconvertfromonetoother.

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

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

VariableTypes• Strings:createthemenclosingcharactersinquotes

VariableTypes• Lists:containsitemsseparatedbycommasandenclosedwithinbrackets[]

VariableTypes• Lists:containsitemsseparatedbycommasandenclosedwithinbrackets[]

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

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

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

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

DecisionMaking• Conditionalstatements

Example:

Loops• Statementsareexecutedsequentially.

while:

LoopType Descriptionwhile Repeats astatementwhileagivenconditionistrue

for Executesasequenceofstatement multipletimes

Loops• Statementsareexecutedsequentially.

for:

• Forallowstoiteratealongtheitemsofanysequence,thatcanbealist.Alsorangefunctioncanbeused.

LoopType Descriptionwhile Repeats astatementwhileagivenconditionistrue

for Executesasequenceofstatement multipletimes.

LoopsFor:

Loops• Controlstatements.

Statement Descriptionbreak Terminatestheloopandtransfertheexecutiontothe

followingstatementafter theloop

continue Causes thelooptoskiptheremainderofitsbodyandimmediatelyretestitsconditionpriortoreiterating.

pass Used whenastatementisrequiredbutnotwanttoexecuteanythingonit.

Functions• Functionscanbedefinedtoprovidetherequiredfunctionality– Blocksbeginwithdef followedbythenameandparentheses()

– Anyinputshouldbeplacedwithintheparentheses

– Thestatementreturn[]exitsafunction.• Tocallthefunctionjustwritethenameofthefunctionandtheinputparameters.

Functions• Example

Functions• Allparametersarepassedbyreference.Ifyouchangethevalueofanargumentthatwasaninputinsidethefunction,itwillbechangedalsooutside.

• Butifavariable(withthesamename)isredefinedinsidethefunctionthatwillnotchangethevalueoutsidethefunction

Functions

FilesI/O• Pythonprovidesbasicfunctionstoreadandwritefiles.

• OPEN:beforeyoucanreadorwriteafileitneedstobeopened.

Modes Descriptionr Opens afilereadingonly.

r+ Opensafileforbothreadingand writing.

w Opensafileforwritingonly.

w+ Opens afileforbothwritingandreading.

FilesI/O• Close()closesthefileandnomorewritingcanbedone.

• Write()writesanystringtoanopenfile.

• Read()readsastringfromanopenfile.– readline()

Modules• AmoduleallowsyoutologicallyorganizeyourPythoncode.

• Themodules,suchasCplex orGurobi modulearecalledasfollows

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

• ItsupportsavarietyofprogrammingandmodellinglanguagesincludingPython,C++,etc.

• Installationfromwww.gurobi.com andanaccademicfreelicensecanberequested.

LPExample

LPExample• Firstweneedtoimportthegurobi module

• WeneedtodefinethemodelwithModel().Insidetheparenthesesyoucanaddanametothemodel.AndthevariablemwillbeusedeverytimewerefertothemodelonPython.

LPExample• Createthevariableswithmodel.addVar()

• model.addVar(),takesthefollowingarguments

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

LPExample• Tointegratenewvariables,model.update()

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

• Senses:GRB.MAXIMIZEandGRB.MINIMIZE

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

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

LPExample• Wecanwritetheformulationona.lp filewithmodel.write()

• Finallywewanttosolvetheoptimizationmodelwithmodel.optimize()

LPExample• Oncetheproblemissolved,wecanaccessto– ObjectiveFunctionValue.

m.objval

– Variablevaluesm.getVars()

LPExample• OtherwayofsolvingaproblemwithGurobi iswritingintoa.lp fileandreadingthefileandsolvingit.

Exercise

top related