Introduc)on to Python, Cplex and Gurobidetti/IntroductionToPython.pdf · 2016-05-19 · Python •...

48
Introduc)on to Python, Cplex and Gurobi

Transcript of Introduc)on to Python, Cplex and Gurobidetti/IntroductionToPython.pdf · 2016-05-19 · Python •...

Page 1: Introduc)on to Python, Cplex and Gurobidetti/IntroductionToPython.pdf · 2016-05-19 · Python • To open Start Menu-> Python27-> IDLE • Python is an interacAve interpreted language,

Introduc)ontoPython,Cplexand

Gurobi

Page 2: Introduc)on to Python, Cplex and Gurobidetti/IntroductionToPython.pdf · 2016-05-19 · Python • To open Start Menu-> Python27-> IDLE • Python is an interacAve interpreted language,

•  Pythonisawidelyused,highlevelprogramminglanguagedesignedbyGuidovanRossumandreleasedon1991.

•  Twostablereleases:– Python2.7– Python3.5

Introduc)on

Page 3: Introduc)on to Python, Cplex and Gurobidetti/IntroductionToPython.pdf · 2016-05-19 · Python • To open Start Menu-> Python27-> IDLE • Python is an interacAve interpreted language,

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

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

Page 4: Introduc)on to Python, Cplex and Gurobidetti/IntroductionToPython.pdf · 2016-05-19 · Python • To open Start Menu-> Python27-> IDLE • Python is an interacAve interpreted language,

Python•  Pythonpromptcanbeusedtowriteaprogramdirectly

OR•  APythonscriptcanbecreated.– File->NewFile– Writetheprogramandsaveitwiththeextension.py

– Run->RunModule

Page 5: Introduc)on to Python, Cplex and Gurobidetti/IntroductionToPython.pdf · 2016-05-19 · Python • To open Start Menu-> Python27-> IDLE • Python is an interacAve interpreted language,

BasicSyntax•  Printstatement– Elementsseparatedbycommasareprintedwithaspaceinthemiddle.

– Operatorssuchas\nor\tindicatenewlineornewtab

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

Page 6: Introduc)on to Python, Cplex and Gurobidetti/IntroductionToPython.pdf · 2016-05-19 · Python • To open Start Menu-> Python27-> IDLE • Python is an interacAve interpreted language,

BasicSyntax•  CommentsareiniAalizedby#

•  Pythoniden)fiershavetostartwithalePerAtoZ(atoz)oranunderscore(_)followedbylePersornumbers.

•  ReservedwordsAnd Assert Break Class ConAnue 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 7: Introduc)on to Python, Cplex and Gurobidetti/IntroductionToPython.pdf · 2016-05-19 · Python • To open Start Menu-> Python27-> IDLE • Python is an interacAve interpreted language,

BasicSyntax•  BlocksofcodearedenotedbylineindentaAon,nobracesareused.

OK

ERROR

Page 8: Introduc)on to Python, Cplex and Gurobidetti/IntroductionToPython.pdf · 2016-05-19 · Python • To open Start Menu-> Python27-> IDLE • Python is an interacAve interpreted language,

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

•  AssignValuestoVariables

•  MulApleassignment

Page 9: Introduc)on to Python, Cplex and Gurobidetti/IntroductionToPython.pdf · 2016-05-19 · Python • To open Start Menu-> Python27-> IDLE • Python is an interacAve interpreted language,

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

•  Toconvertfromonetoother.

Page 10: Introduc)on to Python, Cplex and Gurobidetti/IntroductionToPython.pdf · 2016-05-19 · Python • To open Start Menu-> Python27-> IDLE • Python is an interacAve interpreted language,

VariableTypes•  SomefuncAonswithnumbers

Func)on Descrip)on Func)on Descrip)on

abs(x) Absolutevalueofx acos(x) Arccosineofx,radians

ceil(x) Smallestintegernotlessx asin(x) Arcsineofx,randians

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

log(x) Naturallogarithmofx cos(x) Cosineofx,radians

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

max(x1,…,xn) Maxvalueofarguments tan(x) Tangentofx,radians

min(x1,…,xn) Minvalueofarguments degrees(x) Convertfromradianstodegre

pow(x,y) x^y radians(x) Convertfromdegreetorad

sqrt(x) Squarerootofx pie Constantspiande

Page 11: Introduc)on to Python, Cplex and Gurobidetti/IntroductionToPython.pdf · 2016-05-19 · Python • To open Start Menu-> Python27-> IDLE • Python is an interacAve interpreted language,

VariableTypes•  Strings:createthemenclosingcharactersinquotes

Page 12: Introduc)on to Python, Cplex and Gurobidetti/IntroductionToPython.pdf · 2016-05-19 · Python • To open Start Menu-> Python27-> IDLE • Python is an interacAve interpreted language,

VariableTypes•  Lists:containsitemsseparatedbycommasandenclosedwithinbrackets[]

Page 13: Introduc)on to Python, Cplex and Gurobidetti/IntroductionToPython.pdf · 2016-05-19 · Python • To open Start Menu-> Python27-> IDLE • Python is an interacAve interpreted language,

VariableTypes•  SomefuncAonsoflists

Func)on Descrip)on

len(A) Returnslengthofthelist

max(A) ReturnsitemfromlistAwiththemaxvalue

min(A) ReturnsitemfromlistAwiththeminvalue

A.append(x) AppendsxtolistA

A.count(x) ReturnshowmanyAmesxisinlistA

A.insert(i,x) InsertsxinlistAinposiAoni

A.remove(x) RemovesxfromlistA

A.reverse() ReverseslistA

A.sort() SortsobjectsoflistA

Page 14: Introduc)on to Python, Cplex and Gurobidetti/IntroductionToPython.pdf · 2016-05-19 · Python • To open Start Menu-> Python27-> IDLE • Python is an interacAve interpreted language,

VariableTypes•  Tuples:similartoalistbutisenclosedinparentheses()andcannotbeupdated.(Read-onlylists)

•  ListvsTuple:Onalistanassignmentcanbedone,butnotonatuple.Atuplecanbeconvertedtoalistbylist(A).

Page 15: Introduc)on to Python, Cplex and Gurobidetti/IntroductionToPython.pdf · 2016-05-19 · Python • To open Start Menu-> Python27-> IDLE • Python is an interacAve interpreted language,

VariableTypes•  DicAonaries:likehashtables.Areenclosedbycurlybraces{}

•  DATATYPECOVERSION:ToconvertbetweentypesyouonlyusethetypenameasafuncAon.

Page 16: Introduc)on to Python, Cplex and Gurobidetti/IntroductionToPython.pdf · 2016-05-19 · Python • To open Start Menu-> Python27-> IDLE • Python is an interacAve interpreted language,

BasicOperators•  ArithmeAcOperators

•  ComparisonOperators

+ AddiAon / Division

- SubstracAon % Module

* MulAplicaAon ** Exponent

a==b Trueifvaluesareequal a<b Trueifalessthanb

a!=b Trueifvaluesarenotequal a>=b Trueifagreaterorequalthanb

a>b Trueifagreaterthanb a<=b Trueifaislessorequalthanb

Page 17: Introduc)on to Python, Cplex and Gurobidetti/IntroductionToPython.pdf · 2016-05-19 · Python • To open Start Menu-> Python27-> IDLE • Python is an interacAve interpreted language,

BasicOperators•  AssignmentOperators

•  LogicalOperators

a=b Assignvalueofbtoa a*=b MulApliesawithb,assignstoa

a+=b Addsbtoa,assigntoa a/=b Dividesawithb,assignstoa

a-=b Subtractsbtoa,assigntoa a**=b a^bandassignstoa

and Trueifbothoperatorsaretrue

or TrueifONEoftheoperatorsistrue

not NegaAonoperator

Page 18: Introduc)on to Python, Cplex and Gurobidetti/IntroductionToPython.pdf · 2016-05-19 · Python • To open Start Menu-> Python27-> IDLE • Python is an interacAve interpreted language,

DecisionMaking•  CondiAonalstatements

Example:

Page 19: Introduc)on to Python, Cplex and Gurobidetti/IntroductionToPython.pdf · 2016-05-19 · Python • To open Start Menu-> Python27-> IDLE • Python is an interacAve interpreted language,

Loops•  StatementsareexecutedsequenAally.

while:

LoopType Descrip)on

while RepeatsastatementwhileagivencondiAonistrue

for ExecutesasequenceofstatementmulApleAmes

Page 20: Introduc)on to Python, Cplex and Gurobidetti/IntroductionToPython.pdf · 2016-05-19 · Python • To open Start Menu-> Python27-> IDLE • Python is an interacAve interpreted language,

Loops•  StatementsareexecutedsequenAally.

for:

•  Forallowstoiteratealongtheitemsofanysequence,thatcanbealist.AlsorangefuncAoncanbeused.

LoopType Descrip)on

while RepeatsastatementwhileagivencondiAonistrue

for ExecutesasequenceofstatementmulApleAmes.

Page 21: Introduc)on to Python, Cplex and Gurobidetti/IntroductionToPython.pdf · 2016-05-19 · Python • To open Start Menu-> Python27-> IDLE • Python is an interacAve interpreted language,

LoopsFor:

Page 22: Introduc)on to Python, Cplex and Gurobidetti/IntroductionToPython.pdf · 2016-05-19 · Python • To open Start Menu-> Python27-> IDLE • Python is an interacAve interpreted language,

Loops•  Controlstatements.

Statement Descrip)on

break TerminatestheloopandtransfertheexecuAontothefollowingstatementatertheloop

conAnue CausesthelooptoskiptheremainderofitsbodyandimmediatelyretestitscondiAonpriortoreiteraAng.

pass Usedwhenastatementisrequiredbutnotwanttoexecuteanythingonit.

Page 23: Introduc)on to Python, Cplex and Gurobidetti/IntroductionToPython.pdf · 2016-05-19 · Python • To open Start Menu-> Python27-> IDLE • Python is an interacAve interpreted language,

Func)ons•  FuncAonscanbedefinedtoprovidetherequiredfuncAonality– Blocksbeginwithdeffollowedbythenameandparentheses()

– Anyinputshouldbeplacedwithintheparentheses

– Thestatementreturn[]exitsafuncAon.•  TocallthefuncAonjustwritethenameofthefuncAonandtheinputparameters.

Page 24: Introduc)on to Python, Cplex and Gurobidetti/IntroductionToPython.pdf · 2016-05-19 · Python • To open Start Menu-> Python27-> IDLE • Python is an interacAve interpreted language,

Func)ons•  Example

Page 25: Introduc)on to Python, Cplex and Gurobidetti/IntroductionToPython.pdf · 2016-05-19 · Python • To open Start Menu-> Python27-> IDLE • Python is an interacAve interpreted language,

Func)ons•  Allparametersarepassedbyreference.IfyouchangethevalueofanargumentthatwasaninputinsidethefuncAon,itwillbechangedalsooutside.

•  Butifavariable(withthesamename)isredefinedinsidethefuncAonthatwillnotchangethevalueoutsidethefuncAon

Page 26: Introduc)on to Python, Cplex and Gurobidetti/IntroductionToPython.pdf · 2016-05-19 · Python • To open Start Menu-> Python27-> IDLE • Python is an interacAve interpreted language,

Func)ons

Page 27: Introduc)on to Python, Cplex and Gurobidetti/IntroductionToPython.pdf · 2016-05-19 · Python • To open Start Menu-> Python27-> IDLE • Python is an interacAve interpreted language,

FilesI/O•  PythonprovidesbasicfuncAonstoreadandwritefiles.

•  OPEN:beforeyoucanreadorwriteafileitneedstobeopened.

Modes Descrip)on

r Opensafilereadingonly.

r+ OpensafileforbothreadingandwriAng.

w OpensafileforwriAngonly.

w+ OpensafileforbothwriAngandreading.

Page 28: Introduc)on to Python, Cplex and Gurobidetti/IntroductionToPython.pdf · 2016-05-19 · Python • To open Start Menu-> Python27-> IDLE • Python is an interacAve interpreted language,

FilesI/O•  Close()closesthefileandnomorewriAngcanbedone.

•  Write()writesanystringtoanopenfile.

•  Read()readsastringfromanopenfile.–  readline()

Page 29: Introduc)on to Python, Cplex and Gurobidetti/IntroductionToPython.pdf · 2016-05-19 · Python • To open Start Menu-> Python27-> IDLE • Python is an interacAve interpreted language,

Modules•  AmoduleallowsyoutologicallyorganizeyourPythoncode.

•  Themodules,suchasCplexorGurobimodulearecalledasfollows

Page 30: Introduc)on to Python, Cplex and Gurobidetti/IntroductionToPython.pdf · 2016-05-19 · Python • To open Start Menu-> Python27-> IDLE • Python is an interacAve interpreted language,

Gurobi•  IsacommercialopAmizaAonsolver.•  Itisnamedateritsfounders:ZonghaoGu,EdwardRothbergandRobertBixby.

•  ItsupportsavarietyofprogrammingandmodellinglanguagesincludingPython,C++,etc.

•  InstallaAonfromwww.gurobi.comandanaccademicfreelicensecanberequested.

Page 31: Introduc)on to Python, Cplex and Gurobidetti/IntroductionToPython.pdf · 2016-05-19 · Python • To open Start Menu-> Python27-> IDLE • Python is an interacAve interpreted language,

LPExample

Page 32: Introduc)on to Python, Cplex and Gurobidetti/IntroductionToPython.pdf · 2016-05-19 · Python • To open Start Menu-> Python27-> IDLE • Python is an interacAve interpreted language,

LPExample•  Firstweneedtoimportthegurobimodule

•  WeneedtodefinethemodelwithModel().Insidetheparenthesesyoucanaddanametothemodel.AndthevariablemwillbeusedeveryAmewerefertothemodelonPython.

Page 33: Introduc)on to Python, Cplex and Gurobidetti/IntroductionToPython.pdf · 2016-05-19 · Python • To open Start Menu-> Python27-> IDLE • Python is an interacAve interpreted language,

LPExample•  Createthevariableswithmodel.addVar()

•  model.addVar(),takesthefollowingarguments

•  vtypecanbeGRB.BINARY,GRB.CONTINUOUS,GRB.INTEGER,GRB.SEMICONTorGRB.SEMIINT

Page 34: Introduc)on to Python, Cplex and Gurobidetti/IntroductionToPython.pdf · 2016-05-19 · Python • To open Start Menu-> Python27-> IDLE • Python is an interacAve interpreted language,

LPExample•  Tointegratenewvariables,model.update()

•  SetthemodelobjecAvewithmodel.setObjecAve(‘EXPRESION’,‘SENSE’)

•  Senses:GRB.MAXIMIZEandGRB.MINIMIZE

Page 35: Introduc)on to Python, Cplex and Gurobidetti/IntroductionToPython.pdf · 2016-05-19 · Python • To open Start Menu-> Python27-> IDLE • Python is an interacAve interpreted language,

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

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

Page 36: Introduc)on to Python, Cplex and Gurobidetti/IntroductionToPython.pdf · 2016-05-19 · Python • To open Start Menu-> Python27-> IDLE • Python is an interacAve interpreted language,

LPExample•  WecanwritetheformulaAonona.lpfilewithmodel.write()

•  FinallywewanttosolvetheopAmizaAonmodelwithmodel.opAmize()

Page 37: Introduc)on to Python, Cplex and Gurobidetti/IntroductionToPython.pdf · 2016-05-19 · Python • To open Start Menu-> Python27-> IDLE • Python is an interacAve interpreted language,

LPExample•  Oncetheproblemissolved,wecanaccessto– ObjecAveFuncAonValue.

m.objval– Variablevaluesm.getVars()

Page 38: Introduc)on to Python, Cplex and Gurobidetti/IntroductionToPython.pdf · 2016-05-19 · Python • To open Start Menu-> Python27-> IDLE • Python is an interacAve interpreted language,

LPExample•  OtherwayofsolvingaproblemwithGurobiiswriAngintoa.lpfileandreadingthefileandsolvingit.

Page 39: Introduc)on to Python, Cplex and Gurobidetti/IntroductionToPython.pdf · 2016-05-19 · Python • To open Start Menu-> Python27-> IDLE • Python is an interacAve interpreted language,

Cplex•  IBMILOGCPLEXOpAmizaAonStudioisanopAmizaAonsotwarepackage.

•  CplexwasnamedforthesimplexmethodasimplementedintheCprogramminglanguage.

•  ItwasoriginallydevelopedbyRobertE.Bixbyandreleasedon1998forthefirstAme.

Page 40: Introduc)on to Python, Cplex and Gurobidetti/IntroductionToPython.pdf · 2016-05-19 · Python • To open Start Menu-> Python27-> IDLE • Python is an interacAve interpreted language,

LPExample

Page 41: Introduc)on to Python, Cplex and Gurobidetti/IntroductionToPython.pdf · 2016-05-19 · Python • To open Start Menu-> Python27-> IDLE • Python is an interacAve interpreted language,

LPExample•  Firstweneedtoimportthecplexmodule

•  Weneedtodefinethemodelwithcplex.Cplex().Insidetheparenthesesyoucanaddanametothemodel.AndthevariablemwillbeusedeveryAmewerefertothemodelonPython.

Page 42: Introduc)on to Python, Cplex and Gurobidetti/IntroductionToPython.pdf · 2016-05-19 · Python • To open Start Menu-> Python27-> IDLE • Python is an interacAve interpreted language,

LPExample•  Createthevariableswithm.variables.add()

•  model.variables.add(),takesthefollowingarguments

•  typescanbebinary,conAnuous,integer,semi_conAnuousorsemi_integer.

Page 43: Introduc)on to Python, Cplex and Gurobidetti/IntroductionToPython.pdf · 2016-05-19 · Python • To open Start Menu-> Python27-> IDLE • Python is an interacAve interpreted language,

LPExample•  SetthemodelobjecAvem.objecAve.set_linearwhereeachvariableneedstobefollowedbythecoefficient.

•  TosettheobjecAvesense,m.objecAve.set_sense()wherethesensescanbem.objecAve.sense.maximize/minimize

Page 44: Introduc)on to Python, Cplex and Gurobidetti/IntroductionToPython.pdf · 2016-05-19 · Python • To open Start Menu-> Python27-> IDLE • Python is an interacAve interpreted language,

LPExample•  Addtheconstraintswith

m.linear_constraints.add(lin_expr=[],senses=[],rhs=[],names=‘’)

•  Tocreatetheexpressioncplex.SparsePair()funcAonisneeded.

•  Senses:‘G’,‘L’or‘E’

Page 45: Introduc)on to Python, Cplex and Gurobidetti/IntroductionToPython.pdf · 2016-05-19 · Python • To open Start Menu-> Python27-> IDLE • Python is an interacAve interpreted language,

LPExample•  WecanwritetheformulaAonona.lpfilewithmodel.write()

•  FinallywewanttosolvetheopAmizaAonmodelwithmodel.solve()

Page 46: Introduc)on to Python, Cplex and Gurobidetti/IntroductionToPython.pdf · 2016-05-19 · Python • To open Start Menu-> Python27-> IDLE • Python is an interacAve interpreted language,

LPExample•  Oncetheproblemissolved,wecanaccessto– ObjecAvefuncAonvalue:m.soluAon.get_objecAve_value()

– Variablevalues:m.soluAon.get_values([‘variablesnames’])

Page 47: Introduc)on to Python, Cplex and Gurobidetti/IntroductionToPython.pdf · 2016-05-19 · Python • To open Start Menu-> Python27-> IDLE • Python is an interacAve interpreted language,

LPExample•  OtherwayofsolvingaproblemwithCplexiswriAngintoa.lpfileandreadingthefileandsolvingit.

Page 48: Introduc)on to Python, Cplex and Gurobidetti/IntroductionToPython.pdf · 2016-05-19 · Python • To open Start Menu-> Python27-> IDLE • Python is an interacAve interpreted language,

Exercise