Introduc)on to Python, Cplex and Gurobidetti/IntroductionToPython.pdf · 2016-05-19 · Python •...
Transcript of Introduc)on to Python, Cplex and Gurobidetti/IntroductionToPython.pdf · 2016-05-19 · Python •...
Introduc)ontoPython,Cplexand
Gurobi
• Pythonisawidelyused,highlevelprogramminglanguagedesignedbyGuidovanRossumandreleasedon1991.
• Twostablereleases:– Python2.7– Python3.5
Introduc)on
Python• ToopenStartMenu->Python27->IDLE• PythonisaninteracAveinterpretedlanguage,soyoucaninteractdirectlywiththePythonprompttowriteaprogram.
• Forexample,writeontheprompt– Print(‘HelloWorld!’)– 2+4or2<4
Python• Pythonpromptcanbeusedtowriteaprogramdirectly
OR• APythonscriptcanbecreated.– File->NewFile– Writetheprogramandsaveitwiththeextension.py
– Run->RunModule
BasicSyntax• Printstatement– Elementsseparatedbycommasareprintedwithaspaceinthemiddle.
– Operatorssuchas\nor\tindicatenewlineornewtab
– All‘–“–‘’’or“””indicatethesamething.
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
BasicSyntax• BlocksofcodearedenotedbylineindentaAon,nobracesareused.
OK
ERROR
VariableTypes• Fivestandarddatatypes:numbers,string,list,tupleanddicAonary.
• AssignValuestoVariables
• MulApleassignment
VariableTypes• Numbers:fournumericaltypesaresupported– Int(integers),long(longintegers),float(floaAngpointrealvalues)andcomplex(complexnumbers)
• Toconvertfromonetoother.
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
VariableTypes• Strings:createthemenclosingcharactersinquotes
VariableTypes• Lists:containsitemsseparatedbycommasandenclosedwithinbrackets[]
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
VariableTypes• Tuples:similartoalistbutisenclosedinparentheses()andcannotbeupdated.(Read-onlylists)
• ListvsTuple:Onalistanassignmentcanbedone,butnotonatuple.Atuplecanbeconvertedtoalistbylist(A).
VariableTypes• DicAonaries:likehashtables.Areenclosedbycurlybraces{}
• DATATYPECOVERSION:ToconvertbetweentypesyouonlyusethetypenameasafuncAon.
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
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
DecisionMaking• CondiAonalstatements
Example:
Loops• StatementsareexecutedsequenAally.
while:
LoopType Descrip)on
while RepeatsastatementwhileagivencondiAonistrue
for ExecutesasequenceofstatementmulApleAmes
Loops• StatementsareexecutedsequenAally.
for:
• Forallowstoiteratealongtheitemsofanysequence,thatcanbealist.AlsorangefuncAoncanbeused.
LoopType Descrip)on
while RepeatsastatementwhileagivencondiAonistrue
for ExecutesasequenceofstatementmulApleAmes.
LoopsFor:
Loops• Controlstatements.
Statement Descrip)on
break TerminatestheloopandtransfertheexecuAontothefollowingstatementatertheloop
conAnue CausesthelooptoskiptheremainderofitsbodyandimmediatelyretestitscondiAonpriortoreiteraAng.
pass Usedwhenastatementisrequiredbutnotwanttoexecuteanythingonit.
Func)ons• FuncAonscanbedefinedtoprovidetherequiredfuncAonality– Blocksbeginwithdeffollowedbythenameandparentheses()
– Anyinputshouldbeplacedwithintheparentheses
– Thestatementreturn[]exitsafuncAon.• TocallthefuncAonjustwritethenameofthefuncAonandtheinputparameters.
Func)ons• Example
Func)ons• Allparametersarepassedbyreference.IfyouchangethevalueofanargumentthatwasaninputinsidethefuncAon,itwillbechangedalsooutside.
• Butifavariable(withthesamename)isredefinedinsidethefuncAonthatwillnotchangethevalueoutsidethefuncAon
Func)ons
FilesI/O• PythonprovidesbasicfuncAonstoreadandwritefiles.
• OPEN:beforeyoucanreadorwriteafileitneedstobeopened.
Modes Descrip)on
r Opensafilereadingonly.
r+ OpensafileforbothreadingandwriAng.
w OpensafileforwriAngonly.
w+ OpensafileforbothwriAngandreading.
FilesI/O• Close()closesthefileandnomorewriAngcanbedone.
• Write()writesanystringtoanopenfile.
• Read()readsastringfromanopenfile.– readline()
Modules• AmoduleallowsyoutologicallyorganizeyourPythoncode.
• Themodules,suchasCplexorGurobimodulearecalledasfollows
Gurobi• IsacommercialopAmizaAonsolver.• Itisnamedateritsfounders:ZonghaoGu,EdwardRothbergandRobertBixby.
• ItsupportsavarietyofprogrammingandmodellinglanguagesincludingPython,C++,etc.
• InstallaAonfromwww.gurobi.comandanaccademicfreelicensecanberequested.
LPExample
LPExample• Firstweneedtoimportthegurobimodule
• WeneedtodefinethemodelwithModel().Insidetheparenthesesyoucanaddanametothemodel.AndthevariablemwillbeusedeveryAmewerefertothemodelonPython.
LPExample• Createthevariableswithmodel.addVar()
• model.addVar(),takesthefollowingarguments
• vtypecanbeGRB.BINARY,GRB.CONTINUOUS,GRB.INTEGER,GRB.SEMICONTorGRB.SEMIINT
LPExample• Tointegratenewvariables,model.update()
• SetthemodelobjecAvewithmodel.setObjecAve(‘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• WecanwritetheformulaAonona.lpfilewithmodel.write()
• FinallywewanttosolvetheopAmizaAonmodelwithmodel.opAmize()
LPExample• Oncetheproblemissolved,wecanaccessto– ObjecAveFuncAonValue.
m.objval– Variablevaluesm.getVars()
LPExample• OtherwayofsolvingaproblemwithGurobiiswriAngintoa.lpfileandreadingthefileandsolvingit.
Cplex• IBMILOGCPLEXOpAmizaAonStudioisanopAmizaAonsotwarepackage.
• CplexwasnamedforthesimplexmethodasimplementedintheCprogramminglanguage.
• ItwasoriginallydevelopedbyRobertE.Bixbyandreleasedon1998forthefirstAme.
LPExample
LPExample• Firstweneedtoimportthecplexmodule
• Weneedtodefinethemodelwithcplex.Cplex().Insidetheparenthesesyoucanaddanametothemodel.AndthevariablemwillbeusedeveryAmewerefertothemodelonPython.
LPExample• Createthevariableswithm.variables.add()
• model.variables.add(),takesthefollowingarguments
• typescanbebinary,conAnuous,integer,semi_conAnuousorsemi_integer.
LPExample• SetthemodelobjecAvem.objecAve.set_linearwhereeachvariableneedstobefollowedbythecoefficient.
• TosettheobjecAvesense,m.objecAve.set_sense()wherethesensescanbem.objecAve.sense.maximize/minimize
LPExample• Addtheconstraintswith
m.linear_constraints.add(lin_expr=[],senses=[],rhs=[],names=‘’)
• Tocreatetheexpressioncplex.SparsePair()funcAonisneeded.
• Senses:‘G’,‘L’or‘E’
LPExample• WecanwritetheformulaAonona.lpfilewithmodel.write()
• FinallywewanttosolvetheopAmizaAonmodelwithmodel.solve()
LPExample• Oncetheproblemissolved,wecanaccessto– ObjecAvefuncAonvalue:m.soluAon.get_objecAve_value()
– Variablevalues:m.soluAon.get_values([‘variablesnames’])
LPExample• OtherwayofsolvingaproblemwithCplexiswriAngintoa.lpfileandreadingthefileandsolvingit.
Exercise