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?

Random forest and decision tree
Random forest and decision treeRandom forest and decision tree
Random forest and decision treeAAKANKSHA JAIN
 
Ensemble learning Techniques
Ensemble learning TechniquesEnsemble learning Techniques
Ensemble learning TechniquesBabu Priyavrat
 
Overview on Optimization algorithms in Deep Learning
Overview on Optimization algorithms in Deep LearningOverview on Optimization algorithms in Deep Learning
Overview on Optimization algorithms in Deep LearningKhang Pham
 
All pairs shortest path algorithm
All pairs shortest path algorithmAll pairs shortest path algorithm
All pairs shortest path algorithmSrikrishnan Suresh
 
Methods of Optimization in Machine Learning
Methods of Optimization in Machine LearningMethods of Optimization in Machine Learning
Methods of Optimization in Machine LearningKnoldus Inc.
 
Xgboost: A Scalable Tree Boosting System - Explained
Xgboost: A Scalable Tree Boosting System - ExplainedXgboost: A Scalable Tree Boosting System - Explained
Xgboost: A Scalable Tree Boosting System - ExplainedSimon Lia-Jonassen
 
Weights initialization
Weights initializationWeights initialization
Weights initializationHaiyang Kong
 
XGBoost: the algorithm that wins every competition
XGBoost: the algorithm that wins every competitionXGBoost: the algorithm that wins every competition
XGBoost: the algorithm that wins every competitionJaroslaw Szymczak
 
Minimum Spanning Tree using Kruskal's Algorithm
Minimum Spanning Tree using Kruskal's Algorithm Minimum Spanning Tree using Kruskal's Algorithm
Minimum Spanning Tree using Kruskal's Algorithm Mrunal Patil
 
Adversarial search
Adversarial searchAdversarial search
Adversarial searchNilu Desai
 
Preparing your data for Machine Learning with Feature Scaling
Preparing your data for  Machine Learning with Feature ScalingPreparing your data for  Machine Learning with Feature Scaling
Preparing your data for Machine Learning with Feature ScalingRahul K Chauhan
 
Machine learning session4(linear regression)
Machine learning   session4(linear regression)Machine learning   session4(linear regression)
Machine learning session4(linear regression)Abhimanyu Dwivedi
 
Solving problems by searching
Solving problems by searchingSolving problems by searching
Solving problems by searchingLuigi Ceccaroni
 

Was ist angesagt? (20)

Random forest and decision tree
Random forest and decision treeRandom forest and decision tree
Random forest and decision tree
 
Ensemble learning Techniques
Ensemble learning TechniquesEnsemble learning Techniques
Ensemble learning Techniques
 
Overview on Optimization algorithms in Deep Learning
Overview on Optimization algorithms in Deep LearningOverview on Optimization algorithms in Deep Learning
Overview on Optimization algorithms in Deep Learning
 
All pairs shortest path algorithm
All pairs shortest path algorithmAll pairs shortest path algorithm
All pairs shortest path algorithm
 
Methods of Optimization in Machine Learning
Methods of Optimization in Machine LearningMethods of Optimization in Machine Learning
Methods of Optimization in Machine Learning
 
Xgboost: A Scalable Tree Boosting System - Explained
Xgboost: A Scalable Tree Boosting System - ExplainedXgboost: A Scalable Tree Boosting System - Explained
Xgboost: A Scalable Tree Boosting System - Explained
 
Weights initialization
Weights initializationWeights initialization
Weights initialization
 
Traveling Salesman Problem
Traveling Salesman Problem Traveling Salesman Problem
Traveling Salesman Problem
 
XGBoost: the algorithm that wins every competition
XGBoost: the algorithm that wins every competitionXGBoost: the algorithm that wins every competition
XGBoost: the algorithm that wins every competition
 
Combinatorial Optimization
Combinatorial OptimizationCombinatorial Optimization
Combinatorial Optimization
 
Minimum Spanning Tree using Kruskal's Algorithm
Minimum Spanning Tree using Kruskal's Algorithm Minimum Spanning Tree using Kruskal's Algorithm
Minimum Spanning Tree using Kruskal's Algorithm
 
5 csp
5 csp5 csp
5 csp
 
Adversarial search
Adversarial searchAdversarial search
Adversarial search
 
Tuning learning rate
Tuning learning rateTuning learning rate
Tuning learning rate
 
Preparing your data for Machine Learning with Feature Scaling
Preparing your data for  Machine Learning with Feature ScalingPreparing your data for  Machine Learning with Feature Scaling
Preparing your data for Machine Learning with Feature Scaling
 
Branch and bound
Branch and boundBranch and bound
Branch and bound
 
Machine learning session4(linear regression)
Machine learning   session4(linear regression)Machine learning   session4(linear regression)
Machine learning session4(linear regression)
 
Support Vector Machines ( SVM )
Support Vector Machines ( SVM ) Support Vector Machines ( SVM )
Support Vector Machines ( SVM )
 
Solving problems by searching
Solving problems by searchingSolving problems by searching
Solving problems by searching
 
Support Vector machine
Support Vector machineSupport Vector machine
Support Vector machine
 

Ä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

Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
The byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxThe byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxShobhayan Kirtania
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 

Kürzlich hochgeladen (20)

Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
The byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxThe byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptx
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.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)