0% found this document useful (0 votes)
117 views20 pages

LAB0 UPDATED Converted - Compressed PDF

This document provides instructions on how to summarize a linear programming problem in Python using PuLP. It includes: 1) Installing Python 2.7, Anaconda, and PuLP. 2) Defining decision variables, constraints, and the objective function to build the linear programming model. 3) Solving the model and outputting the optimal objective value and variable values. 4) An example problem that minimizes shipping costs by determining optimal orders from warehouses to customers.

Uploaded by

Akash Kanyadhara
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
117 views20 pages

LAB0 UPDATED Converted - Compressed PDF

This document provides instructions on how to summarize a linear programming problem in Python using PuLP. It includes: 1) Installing Python 2.7, Anaconda, and PuLP. 2) Defining decision variables, constraints, and the objective function to build the linear programming model. 3) Solving the model and outputting the optimal objective value and variable values. 4) An example problem that minimizes shipping costs by determining optimal orders from warehouses to customers.

Uploaded by

Akash Kanyadhara
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

LAB 0

To run linear programming in python, Pulp programs to be run.


To do this, Python 2.7 and Anaconda Jupiter notebook has to be installed

Python 2.7 installation Process:

Step 1:
Type python 2.7 in Google, click on Python 2.7.0 Release | python.org

Step 2:
Click on Windows X86-64 MSI Installer (2.7.0)[1](sig)
Step 3:
Click on Exe file then start installing process

Click on Next

Click on Next

Click on Next
Click on Next and after completing installing process, Click on Next.

Installation of Anaconda:

Step 1: click on Individual Edition-Anaconda


Step 2:
Scroll down and click on 64-bit Graphical Installer (413MB)

Step 3:
Run the exe file then start installing process
Step 3.1: Click on Next
Step 3.2: click on I Agree

Step 3.3: Click on Next


Step 3.4: Click on Next

Step 3.5: Select Add anaconda to my PATH environment variable and click on
Install.
Step 3.6: Click on Next

Step3.7: Click on Next

-
Step3.8 : Click on Finish

Step 4: Open command prompt and type the following command

Step 5: Then it will ask like Proceed [Y/N] ---type “Y”


Step 6: Open Anaconda2 then click on Jupyter notebook
Step 7: Goto New tab then select python 2

Step 8: Run PULP programs

PULP:

PuLP is a free open source software written in Python. It is used to describe


optimisation problems as mathematical models. PuLP can then call any of
numerous external LP solvers (CBC, GLPK, CPLEX, Gurobi etc) to solve this model
and then use python commands to manipulate and display the solution. Do read
its documentation which is super-helpful. The following link also helps you
understand how you can install the library PuLP and any required solver in your
Python environment.

Standard Library and Packages:

One of the strengths of the Python language is the extensive standard library that is available to every
program that uses the Python interpreter
The standard library includes hundreds of modules that allow the programmer to, for example:

• read data files and databases;

• fetch information from the Internet;

• manipulate numbers and dates;

• create graphical user interfaces

Examples: PuLP in Action

Python Syntax To aid in the understanding of the examples, it is helpful to introduce some of the relevant
language features of Python.

• Whitespace: Python uses indentation (with spaces or tabs) to indicate subsections of code.

• Variable declaration: Variables do have specific types (e.g. string, number, object), but it is not necessary to
pre-declare the variable types - the Python interpreter will determine the type from the first use of the
variable.

• Dictionaries and Lists: These are two common data structures in Python. Lists are a simple container of
items, much like arrays in many languages. They can change size at any time, can contain items of different
types, and are one dimensional. Dictionaries are another storage structure, where each item is associated with
a “key”. This is sometimes called a map or associative array in other languages. The key maybe be almost
anything, as long as it is unique.

. myList = ['apple', 'orange', 'banana']

myDict = {'apple':'red, 'orange':'orange', 'banana':'yellow}

print myList[0] % Displays "apple"

print myDict['apple'] % Displays "red"

• List comprehension: These are “functional programming” devices used in Python to dynamically generate
lists, and are very useful for generating linear expressions like finding the sum of a set. Many examples are
provided in the code below, but the general concept is to create a new list in place by filtering, manipulating or
combining other lists. For example, a list comprehension that provides the even numbers between 1 and 9 is
implemented with the Python code:

even = [i for i in [1,2,3,4,5,6,7,8,9] if i%2 == 0]

where we have use the modulo division operator % as our filter.


Use Python and a linear programming optimization package PuLP, copy-paste
install with pip:

pip install pulp

from pulp import *


problem = LpProblem("problemName", LpMaximize)

Add the constraints and objective function to this object.


Problem constructor receives a problem name and LpMaximize, which means
we want to maximize our objective function.

Decision Variables

In PuLP, a decision variable is defined the following way:

variable = LpVariable("variableName")

Sometimes we need to provide bounds to the variable (the default is no bounds),


in this case, we would write the following:
var = LpVariable("boundedVariableName",lowerBound,upperBound)

Another useful way to define variables in PuLP is using the dicts function.
This can be very useful in cases where we need to define a large number of
variables of the same type and bounds, variableNames would be a list of keys
for the dictionary:
varDict = LpVariable.dicts("varDict", variableNames, lowBound, upBound)

Solving

Once we defined everything that is necessary in our linear programming


problem, solve method can be called.

# solving
problem.solve()

If the problem is solved, output will be 1


If output is -1, then the problem is infeasible.
Introduction to Linear Programming
Linear Programming is basically a subset of optimization. Linear
programming or linear optimization is an optimization technique wherein we
try to find an optimal value for a linear objective function for a system of
linear constraints using a varying set of decision variables.

Understanding the Problem in Hand

You want to minimize the cost of shipping goods from 2 different warehouses to 4
different customers. Each warehouse has a limited supply and each customer has
a certain demand. We need to fulfill the demand of the customers by shipping
products from given warehouses such that the overall cost of shipping is minimum
and we are also able to satisfy the customer demands using limited supply
available with each warehouse.

Import required Libraries


from pulp import *
import pandas as pd
import numpy as np
Data Definition
n_warehouses = 2
n_customers = 4
# Cost Matrix
cost_matrix = np.array([[1, 3, 0.5, 4],
[2.5, 5, 1.5, 2.5]])
# Demand Matrix
cust_demands = np.array([35000, 22000, 18000, 30000])

# Supply Matrix
warehouse_supply = np.array([60000, 80000])

Model Initialization

model = LpProblem("Supply-Demand-Problem", LpMinimize)

Defining Decision Variables


variable_names = [str(i)+str(j)
for j in range(1, n_customers+1)
for i in range(1, n_warehouses+1)]
variable_names.sort()
print("Variable Indices:", variable_names)

Output will be

In order to leverage the Numpy array operations, we can convert our decision
variables to a Numpy array.
DV_variables = LpVariable.matrix("X", variable_names, cat = "Integer", lowBound= 0 )
allocation = np.array(DV_variables).reshape(2,4)
print("Decision Variable/Allocation Matrix: ")
print(allocation)
output will be

Objective Function
obj_func = lpSum(allocation*cost_matrix)print(obj_func)model +=
obj_funcprint(model)

Let us see how our model looks like now.

Constraints

We have 2 major types of constraints that we need to add:-

1) Warehouse or Supply Constraints


#Supply Constraints
for i in range(n_warehouses):
print(lpSum(allocation[i][j] for j in range(n_customers)) <= warehouse_supply[i])
model += lpSum(allocation[i][j] for j in range(n_customers)) <=
warehouse_supply[i] , "Supply Constraints " + str(i)

Output of this constraint:


2) Customer or Demand Constraints
# Demand Constraints
for j in range(n_customers):
print(lpSum(allocation[i][j] for i in range(n_warehouses)) >= cust_demands[j])
model += lpSum(allocation[i][j] for i in range(n_warehouses)) >= cust_demands[j] ,
"Demand Constraints " + str(j)

Output of this constraint:

Check the Model

print(model).

Run the Model and Check Status


#model.solve()
model.solve(PULP_CBC_CMD())
status = LpStatus[model.status]
print(status)
Output the Objective Function Value and Decision Variables Value
print("Total Cost:", model.objective.value())
# Decision Variables
for v in model.variables():
try:
print(v.name,"=", v.value())
except:
print("error couldnt find value")

Output is:

# Warehouse 1 and Warehouse 2 required capacity


for i in range(n_warehouses):
print("Warehouse ", str(i+1))
print(lpSum(allocation[i][j].value() for j in range(n_customers)))

Output:

How to Solve a Linear Programming Problem Using the Graphical Method

https://www.youtube.com/watch?v=8IRrgDoV8Eo
Steps involved in the Graphical Method
1. Step 1: Formulate the LP (Linear programming) problem. ...
2. Step 2: Construct a graph and plot the constraint lines. ...
3. Step 3: Determine the valid side of each constraint line. ...
4. Step 4: Identify the feasible solution region. ...
5. Step 5: Plot the objective function on the graph. ...
6. Step 6: Find the optimum point.

Examples on linear programming that solve graphically

Example 1 Solve the following linear programming problem graphically:

Maximise Z = 4x + y ... (1)


subject to the constraints: x + y ≤ 50 ... (2)
3x + y ≤ 90 ... (3)
x ≥ 0, y ≥ 0 ... (4)
Solution:
The shaded region in the following Fig is the feasible region determined by the system of constraints (2) to (4).
We observe that the feasible region OABC is bounded. So, we now use Corner Point Method to determine the
maximum value of Z.
The coordinates of the corner points O, A, B and C are (0, 0), (30, 0), (20, 30) and (0, 50) respectively. Now we
evaluate Z at each corner point.

Hence, maximum value of Z is 120 at the point (30, 0).


Example 2: Solve the following linear programming problem graphically:

Minimise Z = 200 x + 500 y ... (1)

subject to the constraints: x + 2y ≥ 10 ... (2)

3x + 4y ≤ 24 ... (3)

x ≥ 0, y ≥ 0 ... (4)

Solution:

The shaded region in the following Fig is the feasible region ABC determined by the system of constraints (2) to
(4), which is bounded. The coordinates of corner points

A, B and C are (0,5), (4,3) and (0,6) respectively. Now we evaluate Z = 200x + 500y at these points.

Hence, minimum value of Z is 2300 attained at the point (4, 3)

Simple Algebraic method

https://www.youtube.com/watch?v=Im17WchPw6g&t=447s
Graphical Method:

https://www.youtube.com/watch?v=8IRrgDoV8Eo&t=675s

You might also like