Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Introduc)onto Python,Cplexand Gurobi Introduc)on • Pythonisawidelyused,highlevel programminglanguagedesignedby GuidovanRossumandreleasedon1991. • Twostablereleases: – Python2.7 – Python3.5 Python • ToopenStartMenu->Python27->IDLE • PythonisaninteracAveinterpretedlanguage, soyoucaninteractdirectlywiththePython prompttowriteaprogram. • Forexample,writeontheprompt – Print(‘HelloWorld!’) – 2+4or2<4 Python • Pythonpromptcanbeusedtowritea programdirectly OR • APythonscriptcanbecreated. – File->NewFile – Writetheprogramandsaveitwiththe extension.py – Run->RunModule BasicSyntax • Printstatement – Elementsseparatedbycommasareprintedwitha spaceinthemiddle. – Operatorssuchas\nor\tindicatenewlineor newtab – All‘–“–‘’’or“””indicatethesamething. BasicSyntax • CommentsareiniAalizedby# • Pythoniden)fiershavetostartwithalePerA toZ(atoz)oranunderscore(_)followedby lePersornumbers. • Reservedwords And Assert Break Class ConAnue def del elif exec finally for from global if import in Not or pass print raise return try while else except is lambda with yield BasicSyntax • Blocksofcodearedenotedbyline indentaAon,nobracesareused. OK ERROR VariableTypes • Fivestandarddatatypes:numbers,string,list, tupleanddicAonary. • AssignValuestoVariables • MulApleassignment VariableTypes • Numbers:fournumericaltypesaresupported – Int(integers),long(longintegers),float(floaAng pointrealvalues)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:createthemenclosingcharactersin quotes VariableTypes • Lists:containsitemsseparatedbycommas andenclosedwithinbrackets[] 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:similartoalistbutisenclosedin parentheses()andcannotbeupdated.(Readonlylists) • ListvsTuple:Onalistanassignmentcanbe done,butnotonatuple.Atuplecanbe convertedtoalistbylist(A). VariableTypes • DicAonaries:likehashtables.Areenclosedby curlybraces{} • DATATYPECOVERSION:Toconvertbetween typesyouonlyusethetypenameasa funcAon. BasicOperators • ArithmeAcOperators + AddiAon / Division - SubstracAon % Module * MulAplicaAon ** Exponent • ComparisonOperators a==b Trueifvaluesareequal a<b Trueifalessthanb a!=b Trueifvaluesarenotequal a>=b Trueifagreaterorequalthanb a>b a<=b Trueifaislessorequalthanb Trueifagreaterthanb BasicOperators • AssignmentOperators a=b Assignvalueofbtoa a*=b MulApliesawithb,assignstoa a+=b Addsbtoa,assigntoa a/=b Dividesawithb,assignstoa a-=b Subtractsbtoa,assigntoa a**=b a^bandassignstoa • LogicalOperators and Trueifbothoperatorsaretrue or TrueifONEoftheoperatorsistrue not NegaAonoperator DecisionMaking • CondiAonalstatements Example: Loops • StatementsareexecutedsequenAally. LoopType Descrip)on while RepeatsastatementwhileagivencondiAonistrue for ExecutesasequenceofstatementmulApleAmes while: Loops • StatementsareexecutedsequenAally. LoopType Descrip)on while RepeatsastatementwhileagivencondiAonistrue for ExecutesasequenceofstatementmulApleAmes. for: • Forallowstoiteratealongtheitemsofanysequence,that canbealist.AlsorangefuncAoncanbeused. Loops For: Loops • Controlstatements. Statement Descrip)on break TerminatestheloopandtransfertheexecuAontothe followingstatementatertheloop conAnue Causesthelooptoskiptheremainderofitsbodyand immediatelyretestitscondiAonpriortoreiteraAng. pass Usedwhenastatementisrequiredbutnotwantto executeanythingonit. Func)ons • FuncAonscanbedefinedtoprovidethe requiredfuncAonality – Blocksbeginwithdeffollowedbythenameand parentheses() – Anyinputshouldbeplacedwithinthe parentheses – Thestatementreturn[]exitsafuncAon. • TocallthefuncAonjustwritethenameofthe funcAonandtheinputparameters. Func)ons • Example Func)ons • Allparametersarepassedbyreference.Ifyou changethevalueofanargumentthatwasan inputinsidethefuncAon,itwillbechanged alsooutside. • Butifavariable(withthesamename)is redefinedinsidethefuncAonthatwillnot changethevalueoutsidethefuncAon Func)ons FilesI/O • PythonprovidesbasicfuncAonstoreadand writefiles. • OPEN:beforeyoucanreadorwriteafileit needstobeopened. Modes Descrip)on r Opensafilereadingonly. r+ OpensafileforbothreadingandwriAng. w OpensafileforwriAngonly. w+ OpensafileforbothwriAngandreading. FilesI/O • Close()closesthefileandnomorewriAngcan bedone. • Write()writesanystringtoanopenfile. • Read()readsastringfromanopenfile. – readline() Modules • Amoduleallowsyoutologicallyorganizeyour Pythoncode. • Themodules,suchasCplexorGurobimodule arecalledasfollows Gurobi • IsacommercialopAmizaAonsolver. • Itisnamedateritsfounders:ZonghaoGu, EdwardRothbergandRobertBixby. • Itsupportsavarietyofprogrammingand modellinglanguagesincludingPython,C++, etc. • InstallaAonfromwww.gurobi.comandan accademicfreelicensecanberequested. LPExample LPExample • Firstweneedtoimportthegurobimodule • WeneedtodefinethemodelwithModel(). Insidetheparenthesesyoucanaddanameto themodel.Andthevariablemwillbeused everyAmewerefertothemodelonPython. LPExample • Createthevariableswithmodel.addVar() • model.addVar(),takesthefollowing arguments • vtypecanbeGRB.BINARY,GRB.CONTINUOUS, GRB.INTEGER,GRB.SEMICONTor GRB.SEMIINT LPExample • Tointegratenewvariables,model.update() • SetthemodelobjecAvewith model.setObjecAve(‘EXPRESION’,‘SENSE’) • Senses:GRB.MAXIMIZEandGRB.MINIMIZE LPExample • Addtheconstraintswith model.addConstr(‘LHS’,sense,‘RHS’,name=‘’) ormodel.addConstr(‘expression’,“name”) • Sense:GRB.EQUAL,GRB.LESS_EQUALor GRB.GREATER_EQUAL LPExample • WecanwritetheformulaAonona.lpfilewith model.write() • FinallywewanttosolvetheopAmizaAon modelwithmodel.opAmize() LPExample • Oncetheproblemissolved,wecanaccessto – ObjecAveFuncAonValue. m.objval – Variablevalues m.getVars() LPExample • OtherwayofsolvingaproblemwithGurobiis wriAngintoa.lpfileandreadingthefileand solvingit. Cplex • IBMILOGCPLEXOpAmizaAonStudioisan opAmizaAonsotwarepackage. • Cplexwasnamedforthesimplexmethodas implementedintheCprogramminglanguage. • ItwasoriginallydevelopedbyRobertE.Bixby andreleasedon1998forthefirstAme. LPExample LPExample • Firstweneedtoimportthecplexmodule • Weneedtodefinethemodelwith cplex.Cplex().Insidetheparenthesesyoucan addanametothemodel.Andthevariablem willbeusedeveryAmewerefertothemodel onPython. LPExample • Createthevariableswithm.variables.add() • model.variables.add(),takesthefollowing arguments • typescanbebinary,conAnuous,integer, semi_conAnuousorsemi_integer. LPExample • SetthemodelobjecAvem.objecAve.set_linear whereeachvariableneedstobefollowedby thecoefficient. • TosettheobjecAvesense,m.objecAve.set_sense() wherethesensescanbe m.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.lpfilewith model.write() • FinallywewanttosolvetheopAmizaAon modelwithmodel.solve() LPExample • Oncetheproblemissolved,wecanaccessto – ObjecAvefuncAonvalue: m.soluAon.get_objecAve_value() – Variablevalues: m.soluAon.get_values([‘variablesnames’]) LPExample • OtherwayofsolvingaproblemwithCplexis wriAngintoa.lpfileandreadingthefileand solvingit. Exercise