SlideShare una empresa de Scribd logo
1 de 18
Descargar para leer sin conexión
Tutorial: Python, PuLP & GLPK



            Sucha Supittayapornpong
                          Twitter: @Sucha

                                      5 Mar. 2010




                     Creative Commons Attribution 3.0.
Architecture


Programming Language: Python




Interface: PuLP

Optimization Solvers: GLPK, CPLEX, COIN, etc.
Python

   Python is a programming language.
   Python runs on Windows, Linux/Unix, Mac OS X.
   Python is free to use.




                             From: http://www.python.org/
Python: Features

        High-level data structures
             Ex: list, tuple, dictionary
        Object-oriented
        Interpreter
        Standard library & Third party modules
             Ex: pulp, numpy, matplotlib




From: http://code.google.com/p/pulp-or/ , http://numpy.scipy.org/ , http://matplotlib.sourceforge.net/
Python: Basic Data Type
   Integer (int)
       Ex: 1, 2, 3, 5, 8, 13, 21

   Float (float)
       Ex: 3.14, 2.71828

   Boolean (bool)
       Ex: True, False

   String (str)
       Ex: 'Python', ”Sucha”
Python: High-Level Data Type
   List (list): [ d1, d2, …, dn ]
       Ex: [ 1, 3.14, True, 'a', [1], (2,3), {'B+':3.5} ]

   Tuple (tuple): ( d1, d2, ..., dn, )
       Ex: ( 1, 3.14, True, 'a', [1], (2,3), {'B+':3.5} )

   Dictionary (dict): { k1:v1 , k2:v2 , ..., kn:vn }
       Ex: { 'A':4 , 'B+':3.5 , 3:'B' }

   Set (set): set([ d1, d2, ..., dn ])
       Ex: set([ 4, 3.5, 'B'])
Python: Flow Control - If

   If statement
      if boolean:
         command
      elif boolean:
         command
      else:
         command
Python: Loop - For, While

   For loop
      for var in sequence:
         command


   While loop
      while boolean:
         command
Python: List Comprehensions

   >>>[ i for i in range(5)]
      → [ 0, 1, 2, 3, 4 ]

   >>>[ i for i in range(5) if i <> 3 ]
      → [ 0, 1, 2, 4 ]

   >>>[ (i, j) for i in range(3) for j in range(i) ]
      → [ (1,0), (2,0), (2,1) ]
PuLP & GLPK
   PuLP is an LP modeler written in Python.
   PuLP can generate LP files, and calls solvers to
    solve linear problems.
   Supported solvers are
    GLPK, COIN, CPLEX, and GUROBI.
                                  http://code.google.com/p/pulp-or/

   The GLPK (GNU Linear Programming Kit)
    package is intended for solving
    large-scale linear programming (LP),
    mixed integer programming (MIP),
    and other related problems.
                                  http://www.gnu.org/software/glpk/
PuLP: Import Module

   Import module
       >>>import pulp
        >>>pulp.pulpTestAll()

       >>>from pulp import *
        >>>pulpTestAll()




    Following slides assume the first import method.
PuLP: Create Decision Variables
   DV = pulp.LpVariable(name_str,
                         lowbound,
                         upbound,
                         category)
   For lowbound and upbound, No bound → None .

    category ∈{ pulp.LpContinuous,
                  pulp.LpInteger,
                  pulp.LpBinary }
   Ex: x ∈[0, ∞)
    x = pulp.LpVariable('Var X', 0, None, pulp.LpContinuous)
PuLP: Formulate Problem

   PB = pulp.LpProblem(name_str, sense)
   sense ∈{ pulp.LpMinimize, pulp.LpMaximize }
   Ex: maximization problem
    prob = pulp.LpProblem('Benefit', pulp.LpMaximize)
PuLP: Add Objective Function

   PB += linear_function, objective_name_str
   linear_function is in the form of
    c1*DV1 + c2*DV2 + … + cn*DVn

   Ex: Cost: 2*DV1 – 1.5*DV2
    prob += 2*x1 – 1.5*x2, 'Cost'
PuLP: Add Constraints

   PB += linear_constraint , constraint_name_str
   linear_constraint is in the form of
           a1*DV1 + a2*DV2 + … + an*DVn == a0
        or a1*DV1 + a2*DV2 + … + an*DVn <= a0
        or a1*DV1 + a2*DV2 + … + an*DVn >= a0

   Ex: Con1: 5*DV1 + 6*DV2 <= 7
    prob += 5*x1 + 6*x2 <= 7, 'Con1'
    or
    prob += 2*x1 + 6*x2 <= 7 – 3*x1, 'Con1'
PuLP: Write .lp File

   PB.writeLP(filename_str)

   Ex: write to Benefit.lp
    prob.writeLP('Benefit.lp')
PuLP: Solve

   PB.solve()               // Solved by COIN solver
   Ex: prob.solve()

   PB.solve(pulp.GLPK()) //Solved by GLPK solver
   Ex: prob.solve(pulp.GLPK())
PuLP: Results

   Check status: pulp.LpStatus[PB.status]
   Ex: pulp.LpStatus[prob.status]

   Optimal cost: pulp.value(PB.objective)
   Ex: pulp.value(prob.objective)

   Optimal solution: DV.varValue
   Ex: x1.varValue
    or
    pulp.value(x1)

Más contenido relacionado

La actualidad más candente

Gradient Descent, Back Propagation, and Auto Differentiation - Advanced Spark...
Gradient Descent, Back Propagation, and Auto Differentiation - Advanced Spark...Gradient Descent, Back Propagation, and Auto Differentiation - Advanced Spark...
Gradient Descent, Back Propagation, and Auto Differentiation - Advanced Spark...Chris Fregly
 
recherche operationnelle
recherche operationnelle recherche operationnelle
recherche operationnelle mohamednacim
 
A Comparison of Fuzzy ARTMAP
A Comparison of Fuzzy ARTMAPA Comparison of Fuzzy ARTMAP
A Comparison of Fuzzy ARTMAPESCOM
 
Post-optimal analysis of LPP
Post-optimal analysis of LPPPost-optimal analysis of LPP
Post-optimal analysis of LPPRAVI PRASAD K.J.
 
20170422 数学カフェ Part1
20170422 数学カフェ Part120170422 数学カフェ Part1
20170422 数学カフェ Part1Kenta Oono
 
primal and dual problem
primal and dual problemprimal and dual problem
primal and dual problemYash Lad
 
Solving linear programming model by simplex method
Solving linear programming model by simplex methodSolving linear programming model by simplex method
Solving linear programming model by simplex methodRoshan Kumar Patel
 
Duality in Linear Programming
Duality in Linear ProgrammingDuality in Linear Programming
Duality in Linear Programmingjyothimonc
 
Linear programming Cost Minimization
Linear programming Cost MinimizationLinear programming Cost Minimization
Linear programming Cost MinimizationKhushbu :-)
 
Nonlinear programming 2013
Nonlinear programming 2013Nonlinear programming 2013
Nonlinear programming 2013sharifz
 
Simplex method
Simplex methodSimplex method
Simplex methodtatteya
 
Genetic algorithms
Genetic algorithmsGenetic algorithms
Genetic algorithmsguest9938738
 
Simplex method - Maximisation Case
Simplex method - Maximisation CaseSimplex method - Maximisation Case
Simplex method - Maximisation CaseJoseph Konnully
 
How to make boxed text with LaTeX
How to make boxed text with LaTeXHow to make boxed text with LaTeX
How to make boxed text with LaTeXVesa Linja-aho
 
Factorization Machines and Applications in Recommender Systems
Factorization Machines and Applications in Recommender SystemsFactorization Machines and Applications in Recommender Systems
Factorization Machines and Applications in Recommender SystemsEvgeniy Marinov
 
Multi Objective Optimization
Multi Objective OptimizationMulti Objective Optimization
Multi Objective OptimizationNawroz University
 

La actualidad más candente (20)

Lecture27 linear programming
Lecture27 linear programmingLecture27 linear programming
Lecture27 linear programming
 
Gradient Descent, Back Propagation, and Auto Differentiation - Advanced Spark...
Gradient Descent, Back Propagation, and Auto Differentiation - Advanced Spark...Gradient Descent, Back Propagation, and Auto Differentiation - Advanced Spark...
Gradient Descent, Back Propagation, and Auto Differentiation - Advanced Spark...
 
recherche operationnelle
recherche operationnelle recherche operationnelle
recherche operationnelle
 
A Comparison of Fuzzy ARTMAP
A Comparison of Fuzzy ARTMAPA Comparison of Fuzzy ARTMAP
A Comparison of Fuzzy ARTMAP
 
Post-optimal analysis of LPP
Post-optimal analysis of LPPPost-optimal analysis of LPP
Post-optimal analysis of LPP
 
20170422 数学カフェ Part1
20170422 数学カフェ Part120170422 数学カフェ Part1
20170422 数学カフェ Part1
 
primal and dual problem
primal and dual problemprimal and dual problem
primal and dual problem
 
Solving linear programming model by simplex method
Solving linear programming model by simplex methodSolving linear programming model by simplex method
Solving linear programming model by simplex method
 
Transportation problem
Transportation problemTransportation problem
Transportation problem
 
Duality in Linear Programming
Duality in Linear ProgrammingDuality in Linear Programming
Duality in Linear Programming
 
Linear programming Cost Minimization
Linear programming Cost MinimizationLinear programming Cost Minimization
Linear programming Cost Minimization
 
Nonlinear programming 2013
Nonlinear programming 2013Nonlinear programming 2013
Nonlinear programming 2013
 
Simplex method
Simplex methodSimplex method
Simplex method
 
Genetic algorithms
Genetic algorithmsGenetic algorithms
Genetic algorithms
 
Simplex method - Maximisation Case
Simplex method - Maximisation CaseSimplex method - Maximisation Case
Simplex method - Maximisation Case
 
How to make boxed text with LaTeX
How to make boxed text with LaTeXHow to make boxed text with LaTeX
How to make boxed text with LaTeX
 
Factorization Machines and Applications in Recommender Systems
Factorization Machines and Applications in Recommender SystemsFactorization Machines and Applications in Recommender Systems
Factorization Machines and Applications in Recommender Systems
 
PRIMAL & DUAL PROBLEMS
PRIMAL & DUAL PROBLEMSPRIMAL & DUAL PROBLEMS
PRIMAL & DUAL PROBLEMS
 
Multi Objective Optimization
Multi Objective OptimizationMulti Objective Optimization
Multi Objective Optimization
 
Tuning learning rate
Tuning learning rateTuning learning rate
Tuning learning rate
 

Similar a Tutorial: Python, PuLP and GLPK

Python Training Tutorial for Frreshers
Python Training Tutorial for FrreshersPython Training Tutorial for Frreshers
Python Training Tutorial for Frreshersrajkamaltibacademy
 
SFSCON23 - Emily Bourne Yaman Güçlü - Pyccel write Python code, get Fortran ...
SFSCON23 - Emily Bourne Yaman Güçlü - Pyccel  write Python code, get Fortran ...SFSCON23 - Emily Bourne Yaman Güçlü - Pyccel  write Python code, get Fortran ...
SFSCON23 - Emily Bourne Yaman Güçlü - Pyccel write Python code, get Fortran ...South Tyrol Free Software Conference
 
Phyton Learning extracts
Phyton Learning extracts Phyton Learning extracts
Phyton Learning extracts Pavan Babu .G
 
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...DRVaibhavmeshram1
 
Python Performance 101
Python Performance 101Python Performance 101
Python Performance 101Ankur Gupta
 
Introduction to the basics of Python programming (part 3)
Introduction to the basics of Python programming (part 3)Introduction to the basics of Python programming (part 3)
Introduction to the basics of Python programming (part 3)Pedro Rodrigues
 
FUNDAMENTALS OF PYTHON LANGUAGE
 FUNDAMENTALS OF PYTHON LANGUAGE  FUNDAMENTALS OF PYTHON LANGUAGE
FUNDAMENTALS OF PYTHON LANGUAGE Saraswathi Murugan
 
Python For Scientists
Python For ScientistsPython For Scientists
Python For Scientistsaeberspaecher
 
OpenGurukul : Language : Python
OpenGurukul : Language : PythonOpenGurukul : Language : Python
OpenGurukul : Language : PythonOpen Gurukul
 
Golang basics for Java developers - Part 1
Golang basics for Java developers - Part 1Golang basics for Java developers - Part 1
Golang basics for Java developers - Part 1Robert Stern
 
Python intro ch_e_comp
Python intro ch_e_compPython intro ch_e_comp
Python intro ch_e_compPaulo Castro
 
Go serving: Building server app with go
Go serving: Building server app with goGo serving: Building server app with go
Go serving: Building server app with goHean Hong Leong
 

Similar a Tutorial: Python, PuLP and GLPK (20)

Python Training Tutorial for Frreshers
Python Training Tutorial for FrreshersPython Training Tutorial for Frreshers
Python Training Tutorial for Frreshers
 
SFSCON23 - Emily Bourne Yaman Güçlü - Pyccel write Python code, get Fortran ...
SFSCON23 - Emily Bourne Yaman Güçlü - Pyccel  write Python code, get Fortran ...SFSCON23 - Emily Bourne Yaman Güçlü - Pyccel  write Python code, get Fortran ...
SFSCON23 - Emily Bourne Yaman Güçlü - Pyccel write Python code, get Fortran ...
 
Phyton Learning extracts
Phyton Learning extracts Phyton Learning extracts
Phyton Learning extracts
 
Porting to Python 3
Porting to Python 3Porting to Python 3
Porting to Python 3
 
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
 
Python
PythonPython
Python
 
Python Performance 101
Python Performance 101Python Performance 101
Python Performance 101
 
Introduction to the basics of Python programming (part 3)
Introduction to the basics of Python programming (part 3)Introduction to the basics of Python programming (part 3)
Introduction to the basics of Python programming (part 3)
 
Spsl iv unit final
Spsl iv unit  finalSpsl iv unit  final
Spsl iv unit final
 
Spsl iv unit final
Spsl iv unit  finalSpsl iv unit  final
Spsl iv unit final
 
Pythonppt28 11-18
Pythonppt28 11-18Pythonppt28 11-18
Pythonppt28 11-18
 
FUNDAMENTALS OF PYTHON LANGUAGE
 FUNDAMENTALS OF PYTHON LANGUAGE  FUNDAMENTALS OF PYTHON LANGUAGE
FUNDAMENTALS OF PYTHON LANGUAGE
 
Python overview
Python   overviewPython   overview
Python overview
 
Python 3.pptx
Python 3.pptxPython 3.pptx
Python 3.pptx
 
Python For Scientists
Python For ScientistsPython For Scientists
Python For Scientists
 
OpenGurukul : Language : Python
OpenGurukul : Language : PythonOpenGurukul : Language : Python
OpenGurukul : Language : Python
 
Golang basics for Java developers - Part 1
Golang basics for Java developers - Part 1Golang basics for Java developers - Part 1
Golang basics for Java developers - Part 1
 
Python intro ch_e_comp
Python intro ch_e_compPython intro ch_e_comp
Python intro ch_e_comp
 
Python tour
Python tourPython tour
Python tour
 
Go serving: Building server app with go
Go serving: Building server app with goGo serving: Building server app with go
Go serving: Building server app with go
 

Último

Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
 
Activity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translationActivity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translationRosabel UA
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptxmary850239
 
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptx
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptxMusic 9 - 4th quarter - Vocal Music of the Romantic Period.pptx
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptxleah joy valeriano
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptxmary850239
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Celine George
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxVanesaIglesias10
 
Food processing presentation for bsc agriculture hons
Food processing presentation for bsc agriculture honsFood processing presentation for bsc agriculture hons
Food processing presentation for bsc agriculture honsManeerUddin
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxCarlos105
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYKayeClaireEstoconing
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptxiammrhaywood
 
Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)cama23
 

Último (20)

Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
 
Activity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translationActivity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translation
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx
 
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptx
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptxMusic 9 - 4th quarter - Vocal Music of the Romantic Period.pptx
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptx
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptxFINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptxYOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptx
 
Food processing presentation for bsc agriculture hons
Food processing presentation for bsc agriculture honsFood processing presentation for bsc agriculture hons
Food processing presentation for bsc agriculture hons
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
 
Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)
 

Tutorial: Python, PuLP and GLPK

  • 1. Tutorial: Python, PuLP & GLPK  Sucha Supittayapornpong Twitter: @Sucha 5 Mar. 2010 Creative Commons Attribution 3.0.
  • 2. Architecture Programming Language: Python Interface: PuLP Optimization Solvers: GLPK, CPLEX, COIN, etc.
  • 3. Python  Python is a programming language.  Python runs on Windows, Linux/Unix, Mac OS X.  Python is free to use. From: http://www.python.org/
  • 4. Python: Features  High-level data structures  Ex: list, tuple, dictionary  Object-oriented  Interpreter  Standard library & Third party modules  Ex: pulp, numpy, matplotlib From: http://code.google.com/p/pulp-or/ , http://numpy.scipy.org/ , http://matplotlib.sourceforge.net/
  • 5. Python: Basic Data Type  Integer (int)  Ex: 1, 2, 3, 5, 8, 13, 21  Float (float)  Ex: 3.14, 2.71828  Boolean (bool)  Ex: True, False  String (str)  Ex: 'Python', ”Sucha”
  • 6. Python: High-Level Data Type  List (list): [ d1, d2, …, dn ]  Ex: [ 1, 3.14, True, 'a', [1], (2,3), {'B+':3.5} ]  Tuple (tuple): ( d1, d2, ..., dn, )  Ex: ( 1, 3.14, True, 'a', [1], (2,3), {'B+':3.5} )  Dictionary (dict): { k1:v1 , k2:v2 , ..., kn:vn }  Ex: { 'A':4 , 'B+':3.5 , 3:'B' }  Set (set): set([ d1, d2, ..., dn ])  Ex: set([ 4, 3.5, 'B'])
  • 7. Python: Flow Control - If  If statement if boolean: command elif boolean: command else: command
  • 8. Python: Loop - For, While  For loop for var in sequence: command  While loop while boolean: command
  • 9. Python: List Comprehensions  >>>[ i for i in range(5)] → [ 0, 1, 2, 3, 4 ]  >>>[ i for i in range(5) if i <> 3 ] → [ 0, 1, 2, 4 ]  >>>[ (i, j) for i in range(3) for j in range(i) ] → [ (1,0), (2,0), (2,1) ]
  • 10. PuLP & GLPK  PuLP is an LP modeler written in Python.  PuLP can generate LP files, and calls solvers to solve linear problems.  Supported solvers are GLPK, COIN, CPLEX, and GUROBI. http://code.google.com/p/pulp-or/  The GLPK (GNU Linear Programming Kit) package is intended for solving large-scale linear programming (LP), mixed integer programming (MIP), and other related problems. http://www.gnu.org/software/glpk/
  • 11. PuLP: Import Module  Import module  >>>import pulp >>>pulp.pulpTestAll()  >>>from pulp import * >>>pulpTestAll() Following slides assume the first import method.
  • 12. PuLP: Create Decision Variables  DV = pulp.LpVariable(name_str, lowbound, upbound, category)  For lowbound and upbound, No bound → None .  category ∈{ pulp.LpContinuous, pulp.LpInteger, pulp.LpBinary }  Ex: x ∈[0, ∞) x = pulp.LpVariable('Var X', 0, None, pulp.LpContinuous)
  • 13. PuLP: Formulate Problem  PB = pulp.LpProblem(name_str, sense)  sense ∈{ pulp.LpMinimize, pulp.LpMaximize }  Ex: maximization problem prob = pulp.LpProblem('Benefit', pulp.LpMaximize)
  • 14. PuLP: Add Objective Function  PB += linear_function, objective_name_str  linear_function is in the form of c1*DV1 + c2*DV2 + … + cn*DVn  Ex: Cost: 2*DV1 – 1.5*DV2 prob += 2*x1 – 1.5*x2, 'Cost'
  • 15. PuLP: Add Constraints  PB += linear_constraint , constraint_name_str  linear_constraint is in the form of a1*DV1 + a2*DV2 + … + an*DVn == a0 or a1*DV1 + a2*DV2 + … + an*DVn <= a0 or a1*DV1 + a2*DV2 + … + an*DVn >= a0  Ex: Con1: 5*DV1 + 6*DV2 <= 7 prob += 5*x1 + 6*x2 <= 7, 'Con1' or prob += 2*x1 + 6*x2 <= 7 – 3*x1, 'Con1'
  • 16. PuLP: Write .lp File  PB.writeLP(filename_str)  Ex: write to Benefit.lp prob.writeLP('Benefit.lp')
  • 17. PuLP: Solve  PB.solve() // Solved by COIN solver  Ex: prob.solve()  PB.solve(pulp.GLPK()) //Solved by GLPK solver  Ex: prob.solve(pulp.GLPK())
  • 18. PuLP: Results  Check status: pulp.LpStatus[PB.status]  Ex: pulp.LpStatus[prob.status]  Optimal cost: pulp.value(PB.objective)  Ex: pulp.value(prob.objective)  Optimal solution: DV.varValue  Ex: x1.varValue or pulp.value(x1)