SlideShare ist ein Scribd-Unternehmen logo
1 von 18
Downloaden Sie, um offline zu lesen
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)

Weitere ähnliche Inhalte

Was ist angesagt?

Exploratory Data Analysis using Python
Exploratory Data Analysis using PythonExploratory Data Analysis using Python
Exploratory Data Analysis using PythonShirin Mojarad, Ph.D.
 
Introduction to TensorFlow 2.0
Introduction to TensorFlow 2.0Introduction to TensorFlow 2.0
Introduction to TensorFlow 2.0Databricks
 
Ridge regression, lasso and elastic net
Ridge regression, lasso and elastic netRidge regression, lasso and elastic net
Ridge regression, lasso and elastic netVivian S. Zhang
 
. An introduction to machine learning and probabilistic ...
. An introduction to machine learning and probabilistic .... An introduction to machine learning and probabilistic ...
. An introduction to machine learning and probabilistic ...butest
 
AI search techniques
AI search techniquesAI search techniques
AI search techniquesOmar Isaid
 
Introduction to Machine Learning
Introduction to Machine LearningIntroduction to Machine Learning
Introduction to Machine Learningshivani saluja
 
Karmarkar's Algorithm For Linear Programming Problem
Karmarkar's Algorithm For Linear Programming ProblemKarmarkar's Algorithm For Linear Programming Problem
Karmarkar's Algorithm For Linear Programming ProblemAjay Dhamija
 
Genetic algorithms in Data Mining
Genetic algorithms in Data MiningGenetic algorithms in Data Mining
Genetic algorithms in Data MiningAtul Khanna
 
Logistic regression
Logistic regressionLogistic regression
Logistic regressionVARUN KUMAR
 
Machine Learning Deep Learning AI and Data Science
Machine Learning Deep Learning AI and Data Science Machine Learning Deep Learning AI and Data Science
Machine Learning Deep Learning AI and Data Science Venkata Reddy Konasani
 
Production systems
Production systemsProduction systems
Production systemsAdri Jovin
 
Locality Sensitive Hashing By Spark
Locality Sensitive Hashing By SparkLocality Sensitive Hashing By Spark
Locality Sensitive Hashing By SparkSpark Summit
 
Genetic representation
Genetic representationGenetic representation
Genetic representationDEEPIKA T
 
K-Nearest Neighbor Classifier
K-Nearest Neighbor ClassifierK-Nearest Neighbor Classifier
K-Nearest Neighbor ClassifierNeha Kulkarni
 
Introduction to Optimization.ppt
Introduction to Optimization.pptIntroduction to Optimization.ppt
Introduction to Optimization.pptMonarjayMalbog1
 
Lecture 4 Decision Trees (2): Entropy, Information Gain, Gain Ratio
Lecture 4 Decision Trees (2): Entropy, Information Gain, Gain RatioLecture 4 Decision Trees (2): Entropy, Information Gain, Gain Ratio
Lecture 4 Decision Trees (2): Entropy, Information Gain, Gain RatioMarina Santini
 

Was ist angesagt? (20)

Exploratory Data Analysis using Python
Exploratory Data Analysis using PythonExploratory Data Analysis using Python
Exploratory Data Analysis using Python
 
Introduction to TensorFlow 2.0
Introduction to TensorFlow 2.0Introduction to TensorFlow 2.0
Introduction to TensorFlow 2.0
 
Ridge regression, lasso and elastic net
Ridge regression, lasso and elastic netRidge regression, lasso and elastic net
Ridge regression, lasso and elastic net
 
Genetic algorithm
Genetic algorithmGenetic algorithm
Genetic algorithm
 
. An introduction to machine learning and probabilistic ...
. An introduction to machine learning and probabilistic .... An introduction to machine learning and probabilistic ...
. An introduction to machine learning and probabilistic ...
 
AI search techniques
AI search techniquesAI search techniques
AI search techniques
 
Introduction to Machine Learning
Introduction to Machine LearningIntroduction to Machine Learning
Introduction to Machine Learning
 
Karmarkar's Algorithm For Linear Programming Problem
Karmarkar's Algorithm For Linear Programming ProblemKarmarkar's Algorithm For Linear Programming Problem
Karmarkar's Algorithm For Linear Programming Problem
 
5 csp
5 csp5 csp
5 csp
 
Genetic algorithms in Data Mining
Genetic algorithms in Data MiningGenetic algorithms in Data Mining
Genetic algorithms in Data Mining
 
Logistic regression
Logistic regressionLogistic regression
Logistic regression
 
Machine Learning Deep Learning AI and Data Science
Machine Learning Deep Learning AI and Data Science Machine Learning Deep Learning AI and Data Science
Machine Learning Deep Learning AI and Data Science
 
Production systems
Production systemsProduction systems
Production systems
 
Locality Sensitive Hashing By Spark
Locality Sensitive Hashing By SparkLocality Sensitive Hashing By Spark
Locality Sensitive Hashing By Spark
 
Genetic representation
Genetic representationGenetic representation
Genetic representation
 
Support Vector Machines ( SVM )
Support Vector Machines ( SVM ) Support Vector Machines ( SVM )
Support Vector Machines ( SVM )
 
K-Nearest Neighbor Classifier
K-Nearest Neighbor ClassifierK-Nearest Neighbor Classifier
K-Nearest Neighbor Classifier
 
Introduction to Optimization.ppt
Introduction to Optimization.pptIntroduction to Optimization.ppt
Introduction to Optimization.ppt
 
Machine learning
Machine learningMachine learning
Machine learning
 
Lecture 4 Decision Trees (2): Entropy, Information Gain, Gain Ratio
Lecture 4 Decision Trees (2): Entropy, Information Gain, Gain RatioLecture 4 Decision Trees (2): Entropy, Information Gain, Gain Ratio
Lecture 4 Decision Trees (2): Entropy, Information Gain, Gain Ratio
 

Ähnlich wie 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
 

Ähnlich wie 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
 

Kürzlich hochgeladen

Third Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptxThird Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptxAmita Gupta
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxVishalSingh1417
 
Magic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptxMagic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptxdhanalakshmis0310
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...pradhanghanshyam7136
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docxPoojaSen20
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfSherif Taha
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701bronxfugly43
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxnegromaestrong
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSCeline George
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...ZurliaSoop
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...Poonam Aher Patil
 

Kürzlich hochgeladen (20)

Third Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptxThird Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptx
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Magic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptxMagic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptx
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 

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)