SlideShare uma empresa Scribd logo
1 de 18
Baixar para ler 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)

Mais conteúdo relacionado

Mais procurados

Design and Analysis of Algorithms
Design and Analysis of AlgorithmsDesign and Analysis of Algorithms
Design and Analysis of AlgorithmsSwapnil Agrawal
 
Yacc (yet another compiler compiler)
Yacc (yet another compiler compiler)Yacc (yet another compiler compiler)
Yacc (yet another compiler compiler)omercomail
 
Document Object Model
Document Object ModelDocument Object Model
Document Object ModelMayur Mudgal
 
Common dialog control
Common dialog controlCommon dialog control
Common dialog controlSoumya Vijoy
 
Ambiguous & Unambiguous Grammar
Ambiguous & Unambiguous GrammarAmbiguous & Unambiguous Grammar
Ambiguous & Unambiguous GrammarMdImamHasan1
 
Lecture 10 semantic analysis 01
Lecture 10 semantic analysis 01Lecture 10 semantic analysis 01
Lecture 10 semantic analysis 01Iffat Anjum
 
Control Flow Graphs
Control Flow GraphsControl Flow Graphs
Control Flow Graphsdaimk2020
 
Minimization of DFA
Minimization of DFAMinimization of DFA
Minimization of DFAkunj desai
 
Bootstrap PPT Part - 2
Bootstrap PPT Part - 2Bootstrap PPT Part - 2
Bootstrap PPT Part - 2EPAM Systems
 
0015.register allocation-graph-coloring
0015.register allocation-graph-coloring0015.register allocation-graph-coloring
0015.register allocation-graph-coloringsean chen
 
An Overview of HTML, CSS & Java Script
An Overview of HTML, CSS & Java ScriptAn Overview of HTML, CSS & Java Script
An Overview of HTML, CSS & Java ScriptFahim Abdullah
 
Tkinter_GUI_Programming_in_Python.pdf
Tkinter_GUI_Programming_in_Python.pdfTkinter_GUI_Programming_in_Python.pdf
Tkinter_GUI_Programming_in_Python.pdfArielManzano3
 
screen output and keyboard input in js
screen output and keyboard input in jsscreen output and keyboard input in js
screen output and keyboard input in jschauhankapil
 

Mais procurados (20)

Design and Analysis of Algorithms
Design and Analysis of AlgorithmsDesign and Analysis of Algorithms
Design and Analysis of Algorithms
 
C language
C languageC language
C language
 
Yacc (yet another compiler compiler)
Yacc (yet another compiler compiler)Yacc (yet another compiler compiler)
Yacc (yet another compiler compiler)
 
html-table
html-tablehtml-table
html-table
 
Document Object Model
Document Object ModelDocument Object Model
Document Object Model
 
Html form tag
Html form tagHtml form tag
Html form tag
 
Common dialog control
Common dialog controlCommon dialog control
Common dialog control
 
Ambiguous & Unambiguous Grammar
Ambiguous & Unambiguous GrammarAmbiguous & Unambiguous Grammar
Ambiguous & Unambiguous Grammar
 
Lecture 10 semantic analysis 01
Lecture 10 semantic analysis 01Lecture 10 semantic analysis 01
Lecture 10 semantic analysis 01
 
Python GUI
Python GUIPython GUI
Python GUI
 
Control Flow Graphs
Control Flow GraphsControl Flow Graphs
Control Flow Graphs
 
Python Programming Essentials - M9 - String Formatting
Python Programming Essentials - M9 - String FormattingPython Programming Essentials - M9 - String Formatting
Python Programming Essentials - M9 - String Formatting
 
Minimization of DFA
Minimization of DFAMinimization of DFA
Minimization of DFA
 
PHP variables
PHP  variablesPHP  variables
PHP variables
 
Bootstrap PPT Part - 2
Bootstrap PPT Part - 2Bootstrap PPT Part - 2
Bootstrap PPT Part - 2
 
GUI programming
GUI programmingGUI programming
GUI programming
 
0015.register allocation-graph-coloring
0015.register allocation-graph-coloring0015.register allocation-graph-coloring
0015.register allocation-graph-coloring
 
An Overview of HTML, CSS & Java Script
An Overview of HTML, CSS & Java ScriptAn Overview of HTML, CSS & Java Script
An Overview of HTML, CSS & Java Script
 
Tkinter_GUI_Programming_in_Python.pdf
Tkinter_GUI_Programming_in_Python.pdfTkinter_GUI_Programming_in_Python.pdf
Tkinter_GUI_Programming_in_Python.pdf
 
screen output and keyboard input in js
screen output and keyboard input in jsscreen output and keyboard input in js
screen output and keyboard input in js
 

Semelhante 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
 

Semelhante 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

Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfPatidar M
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management systemChristalin Nelson
 
Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1GloryAnnCastre1
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptxmary850239
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxlancelewisportillo
 
MS4 level being good citizen -imperative- (1) (1).pdf
MS4 level   being good citizen -imperative- (1) (1).pdfMS4 level   being good citizen -imperative- (1) (1).pdf
MS4 level being good citizen -imperative- (1) (1).pdfMr Bounab Samir
 
Scientific Writing :Research Discourse
Scientific  Writing :Research  DiscourseScientific  Writing :Research  Discourse
Scientific Writing :Research DiscourseAnita GoswamiGiri
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDecoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDhatriParmar
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmStan Meyer
 
How to Make a Duplicate of Your Odoo 17 Database
How to Make a Duplicate of Your Odoo 17 DatabaseHow to Make a Duplicate of Your Odoo 17 Database
How to Make a Duplicate of Your Odoo 17 DatabaseCeline George
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfVanessa Camilleri
 
4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptx4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptxmary850239
 
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...DhatriParmar
 
Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfPrerana Jadhav
 
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQ-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQuiz Club NITW
 
Measures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataMeasures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataBabyAnnMotar
 
week 1 cookery 8 fourth - quarter .pptx
week 1 cookery 8  fourth  -  quarter .pptxweek 1 cookery 8  fourth  -  quarter .pptx
week 1 cookery 8 fourth - quarter .pptxJonalynLegaspi2
 

Último (20)

Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdf
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management system
 
Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
 
MS4 level being good citizen -imperative- (1) (1).pdf
MS4 level   being good citizen -imperative- (1) (1).pdfMS4 level   being good citizen -imperative- (1) (1).pdf
MS4 level being good citizen -imperative- (1) (1).pdf
 
Paradigm shift in nursing research by RS MEHTA
Paradigm shift in nursing research by RS MEHTAParadigm shift in nursing research by RS MEHTA
Paradigm shift in nursing research by RS MEHTA
 
Scientific Writing :Research Discourse
Scientific  Writing :Research  DiscourseScientific  Writing :Research  Discourse
Scientific Writing :Research Discourse
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDecoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and Film
 
How to Make a Duplicate of Your Odoo 17 Database
How to Make a Duplicate of Your Odoo 17 DatabaseHow to Make a Duplicate of Your Odoo 17 Database
How to Make a Duplicate of Your Odoo 17 Database
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdf
 
4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptx4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptx
 
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
 
Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdf
 
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQ-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
 
Faculty Profile prashantha K EEE dept Sri Sairam college of Engineering
Faculty Profile prashantha K EEE dept Sri Sairam college of EngineeringFaculty Profile prashantha K EEE dept Sri Sairam college of Engineering
Faculty Profile prashantha K EEE dept Sri Sairam college of Engineering
 
Measures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataMeasures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped data
 
week 1 cookery 8 fourth - quarter .pptx
week 1 cookery 8  fourth  -  quarter .pptxweek 1 cookery 8  fourth  -  quarter .pptx
week 1 cookery 8 fourth - quarter .pptx
 

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)