SlideShare a Scribd company logo
1 of 18
Download to read offline
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)

More Related Content

What's hot

Closure properties of context free grammar
Closure properties of context free grammarClosure properties of context free grammar
Closure properties of context free grammarAfshanKhan51
 
Genetic Algorithm
Genetic AlgorithmGenetic Algorithm
Genetic AlgorithmSHIMI S L
 
Non regular languages
Non regular languagesNon regular languages
Non regular languageslavishka_anuj
 
Theory of Automata
Theory of AutomataTheory of Automata
Theory of AutomataFarooq Mian
 
Evolutionary computing - soft computing
Evolutionary computing - soft computingEvolutionary computing - soft computing
Evolutionary computing - soft computingSakshiMahto1
 
AI 9 | Bayesian Network and Probabilistic Inference
AI 9 | Bayesian Network and Probabilistic InferenceAI 9 | Bayesian Network and Probabilistic Inference
AI 9 | Bayesian Network and Probabilistic InferenceMohammad Imam Hossain
 
Supervised learning and Unsupervised learning
Supervised learning and Unsupervised learning Supervised learning and Unsupervised learning
Supervised learning and Unsupervised learning Usama Fayyaz
 
Cosine tf idf_example
Cosine tf idf_exampleCosine tf idf_example
Cosine tf idf_examplehellangel13
 
Introduction to dynamic programming
Introduction to dynamic programmingIntroduction to dynamic programming
Introduction to dynamic programmingAmisha Narsingani
 
String Matching Finite Automata & KMP Algorithm.
String Matching Finite Automata & KMP Algorithm.String Matching Finite Automata & KMP Algorithm.
String Matching Finite Automata & KMP Algorithm.Malek Sumaiya
 
CART – Classification & Regression Trees
CART – Classification & Regression TreesCART – Classification & Regression Trees
CART – Classification & Regression TreesHemant Chetwani
 
02 order of growth
02 order of growth02 order of growth
02 order of growthHira Gul
 
Token, Pattern and Lexeme
Token, Pattern and LexemeToken, Pattern and Lexeme
Token, Pattern and LexemeA. S. M. Shafi
 
Cost estimation for Query Optimization
Cost estimation for Query OptimizationCost estimation for Query Optimization
Cost estimation for Query OptimizationRavinder Kamboj
 

What's hot (20)

Closure properties of context free grammar
Closure properties of context free grammarClosure properties of context free grammar
Closure properties of context free grammar
 
Bayesian learning
Bayesian learningBayesian learning
Bayesian learning
 
Genetic Algorithm
Genetic AlgorithmGenetic Algorithm
Genetic Algorithm
 
Em Algorithm | Statistics
Em Algorithm | StatisticsEm Algorithm | Statistics
Em Algorithm | Statistics
 
Non regular languages
Non regular languagesNon regular languages
Non regular languages
 
Theory of Automata
Theory of AutomataTheory of Automata
Theory of Automata
 
Evolutionary computing - soft computing
Evolutionary computing - soft computingEvolutionary computing - soft computing
Evolutionary computing - soft computing
 
AI 9 | Bayesian Network and Probabilistic Inference
AI 9 | Bayesian Network and Probabilistic InferenceAI 9 | Bayesian Network and Probabilistic Inference
AI 9 | Bayesian Network and Probabilistic Inference
 
Supervised learning and Unsupervised learning
Supervised learning and Unsupervised learning Supervised learning and Unsupervised learning
Supervised learning and Unsupervised learning
 
Cosine tf idf_example
Cosine tf idf_exampleCosine tf idf_example
Cosine tf idf_example
 
Introduction to dynamic programming
Introduction to dynamic programmingIntroduction to dynamic programming
Introduction to dynamic programming
 
Machine Learning (Classification Models)
Machine Learning (Classification Models)Machine Learning (Classification Models)
Machine Learning (Classification Models)
 
String Matching Finite Automata & KMP Algorithm.
String Matching Finite Automata & KMP Algorithm.String Matching Finite Automata & KMP Algorithm.
String Matching Finite Automata & KMP Algorithm.
 
CART – Classification & Regression Trees
CART – Classification & Regression TreesCART – Classification & Regression Trees
CART – Classification & Regression Trees
 
02 order of growth
02 order of growth02 order of growth
02 order of growth
 
K Nearest Neighbors
K Nearest NeighborsK Nearest Neighbors
K Nearest Neighbors
 
Token, Pattern and Lexeme
Token, Pattern and LexemeToken, Pattern and Lexeme
Token, Pattern and Lexeme
 
8 issues in pos tagging
8 issues in pos tagging8 issues in pos tagging
8 issues in pos tagging
 
Cost estimation for Query Optimization
Cost estimation for Query OptimizationCost estimation for Query Optimization
Cost estimation for Query Optimization
 
Recovery system
Recovery systemRecovery system
Recovery system
 

Similar to 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 to 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
 

Recently uploaded

ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4MiaBumagat1
 
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
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parentsnavabharathschool99
 
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
 
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
 
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
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 
Integumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptIntegumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptshraddhaparab530
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
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
 
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...JojoEDelaCruz
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...Postal Advocate Inc.
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17Celine George
 

Recently uploaded (20)

ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4
 
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
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parents
 
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
 
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
 
Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 
Integumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptIntegumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.ppt
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
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
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
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
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptxLEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
 
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
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17
 

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)