0% found this document useful (0 votes)
58 views

Least Cost Method

The document describes the least cost method for solving transportation problems. It defines a function that takes in a cost matrix, supply capacities, and demand requirements. The function finds the minimum cost item that can be transported without exceeding supply or demand. It deducts this amount from the corresponding supply and demand and returns the total cost. The function is called in a loop until no more items can be transported. The total cost calculated is printed as the output.

Uploaded by

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

Least Cost Method

The document describes the least cost method for solving transportation problems. It defines a function that takes in a cost matrix, supply capacities, and demand requirements. The function finds the minimum cost item that can be transported without exceeding supply or demand. It deducts this amount from the corresponding supply and demand and returns the total cost. The function is called in a loop until no more items can be transported. The total cost calculated is printed as the output.

Uploaded by

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

Least Cost Method

Ritwika Das
def least(mat,cap,req): Roll-16IT8058
minimum=float("Inf")
min_i=0
min_j=0
result=0
for i in range(0,3):
for j in range(0,5):
if minimum>mat[i][j] and cap[i]!=0 and req[j]!=0:
minimum=mat[i][j]
min_i=i
min_j=j
if mini==float("Inf"):
return 0
deduct=min(cap[min_i],req[min_j])
cap[min_i]=cap[min_i]-deduct
req[min_j]=req[min_j]-deduct
result+=mat[min_i][min_j]*deduct
return result
mat=[[1,9,13,36,51],[24,12,16,20,1],[14,33,1,23,26]]
cap=[50,100,150]
req=[100,60,50,50,40]
result=0
temp=float("Inf")

while temp!=0:
temp=least(mat,cap,req)
if temp!=0:
result+=temp
print("Total cost by least cost method",result)

OUTPUT
VAM Method
req=[25,35,105,20] Ritwika Das
avl=[50,70,30,50] Roll -16IT8058
cost=[[4,6,8,13],[13,11,10,8],[14,4,10,13],[9,11,13,8]]
total_req=0
total_avl=0
for i in range(0,len(req)):
total_req+=req[i]
for i in range(0,len(avl)):
total_avl+=avl[i]
if total_req<total_avl:
diff=total_avl-total_req
req.append(diff)
i=0;
while i<4:
cost[i].append(0)
i=i+1
elif total_req>total_avl:
diff=total_req-total_avl
avl.append(diff)
extra=[0]*len(req)
cost.append(extra)

allocation=[]
for i in range(0,len(avl)):
alloc=[]
for j in range(0,len(req)):
alloc.append(0)
allocation.append(alloc)

print ("Requirement =",req)


print ("Availability = ",avl)
print ("cost Matrix = ",cost)
i=0
j=0
columns=[]
rows=[]
valid_row=[1,1,1,1]
valid_col=[1,1,1,1,1]
while len(rows)<4 and len(columns)<5:
row=0;
max_row_diff=0
x=i
while x<4:
if valid_row[x]==1:
first_min=100000
sec_min=100000
y=j
while y<5:
if valid_col[y]==1:
if cost[x][y]<first_min:
sec_min=first_min
first_min=cost[x][y]
elif cost[x][y]<sec_min:
sec_min=cost[x][y]
y=y+1
diff=sec_min-first_min
if diff>=max_row_diff:
max_row_diff=diff
row=x Ritwika Das
elif diff==max_row_diff: Roll-16IT8058
if avl[x]>avl[row]:
row=x
x=x+1

max_col_diff=0
y=j
col=0
while y<5:
if valid_col[y]==1:
first_min=100000
sec_min=100000
x=i
while x<4:
if valid_row[x]==1:
if valid_col[y]==1 and
cost[x][y]<first_min:
sec_min=first_min
first_min=cost[x][y]
elif cost[x][y]<sec_min:
sec_min=cost[x][y]
x=x+1
diff=sec_min-first_min
if diff>max_col_diff:
max_col_diff=diff
col=y
elif diff==max_col_diff:
if req[y]>req[col]:
col=y
y=y+1

minimum=100000
if max_col_diff<max_row_diff:
a=row
b=0
l=0
while l<5:
if valid_col[l]==1 and cost[row][l]<minimum:
minimum=cost[row][l]
b=l
l=l+1
else:
b=col
l=0
while l<4:
if valid_row[l]==1 and cost[l][col]<minimum:
minimum=cost[l][col]
a=l
l=l+1
val=min(req[b],avl[a])
if val==req[b]:
columns.append(b)
valid_col[b]=0

else:
rows.append(a)
valid_row[a]=0

allocation[a][b]=val
req[b]-=val Ritwika Das
avl[a]-=val Roll-16IT8058

print( "Initial basic feasible solution : ",allocation)


c=0
i=0
for i in range(4):
for j in range(5):
if allocation[i][j]>0:
c+=cost[i][j]*allocation[i][j]
#j=j+1
#i=i+1
print ("Total cost = ",c)

OUTPUT
MODI’S Method
import sys Ritwika Das

def notvalid(i,j): Roll-16IT8058

if(i<0 or i>=3):
return 0
if(j<0 or j>=4):
return 0
return 1
def parent(a,b,c,d):
if((a==c) and (b==d)):
return 0
return 1
def loop_through(i,j,allocated,a,b,li,pi,pj):
if (notvalid(i,j)==0):
return 0
if(i==a and j==b):
return 1
if allocated[i][j]==0:
return 0

if(parent(i+1,j,pi,pj)==1):
if(loop_through(i+1,j,allocated,a,b,li,i,j)):
li.append([i,j])
return 1
if(parent(i-1,j,pi,pj)==1):
if(loop_through(i-1,j,allocated,a,b,li,i,j)):
li.append([i,j])
return 1
if(parent(i,j-1,pi,pj)==1):
if(loop_through(i,j-1,allocated,a,b,li,i,j)):
li.append([i,j])
return 1
if(parent(i,j+1,pi,pj)==1):
if(loop_through(i,j+1,allocated,a,b,li,i,j)):
li.append([i,j])
return 1
return 0
def loop(i,j,allocated):
li=[]
if(loop_through(i+1,j,allocated,i,j,li,i,j)):
return li
pi=[]
if(loop_through(i-1,j,allocated,i,j,pi,i,j)):
return pi
mi=[]
if(loop_through(i,j+1,allocated,i,j,mi,i,j)):
return mi
gi=[]
if(loop_through(i,j-1,allocated,i,j,gi,i,j)):
return gi
cost=[[3,1,7,4],[2,6,5,9],[8,3,3,2]]
allocated=[[200,50,0,0],[0,250,100,0],[0,0,250,150]]
u=[0,-1,-1]
v=[-1,-1,-1,-1]
for i in range(3):
for j in range(4):
if allocated[i][j]!=0:
if(u[i]==-1): Ritwika Das
u[i]=cost[i][j]-v[j] Roll-16IT8058

if (v[j]==-1):
v[j]=cost[i][j]-u[i]
print(u)
print(v)
while(1):
temp=[]
for i in range(3):
for j in range(4):
if(allocated[i][j]==0):
p=u[i]+v[j]-cost[i][j]
if(p>0):
l=[p,i,j]
temp.append(l)
if(len(temp)==0):
break
m=0
p=-1
h=-1
res=[0,0]
for k in range (len(temp)):
if(temp[k][0]>m):
m=temp[k][0]
p=temp[k][1]
h=temp[k][2]
pi=loop(p,h,allocated)
r=sys.max
for i in range(len(pi)):
if(i%2==0):
r=min(r,allocated[pi[i][0]][pi[i][1]])

for i in range(len(pi)):
if(i%2==0):
allocated[pi[i][0]][pi[i][1]]-=r
else:
allocated[pi[i][0]][pi[i][1]]+=r
allocated[p][h]+=r
print("allocated ",allocated)
res=0
for i in range(3):
for j in range(4):
res+=(allocated[i][j]*cost[i][j])
print("result= ",res)

OUTPUT
LPP Using Graphical Method
import numpy as np Ritwika Das
from matplotlib import pyplot as plt Roll-16IT8058
def line_intersection(line1, line2):
xdiff = (line1[0][0] - line1[1][0], line2[0][0] - line2[1][0])
ydiff = (line1[0][1] - line1[1][1], line2[0][1] - line2[1][1])

def det(a, b):


return a[0] * b[1] - a[1] * b[0]

div = det(xdiff, ydiff)


if div == 0:
raise Exception('lines do not intersect')

d = (det(*line1), det(*line2))
x = det(d, xdiff) / div
y = det(d, ydiff) / div
return x, y
x=np.linspace(0,70,2000)
y1=(x*0)+0
y2=(100-5*x)/4.0
y3=(150-3*x)/5.0
y4=(200-5*x)/4.0
y5=(80-8*x)/4.0
plt.plot(x,y1,label=r'$y\geq 0$')
plt.plot(x,y2,label=r'$4y\geq 100-5x$')
plt.plot(x,y3,label=r'$5y\leq 150-3x$')
plt.plot(x,y4,label=r'$4y\leq 200-5x$')
plt.plot(x,y5,label=r'$4y\geq 80-8x$')
plt.xlim(0,50)
plt.ylim(0,50)
plt.xlabel(r'$x$')
plt.ylabel(r'$y$')
y6=np.minimum(y3,y4)
y7=np.maximum(y1,y2)
y7=np.maximum(y7,y5)

A = [0, 50]
B = [40, 0]
C=[0,30]
D=[50,0]

x2,y2=line_intersection((A,B),(C,D))
x12=[20,40,x2,0,0]
y12=[0,0,y2,30,25]
n=[(20,0),(40,0),(x2,y2),(0,30),(0,25)]
m=0
for i in range(5):
print("Intersection points",x12[i],y12[i])
for i in range(5):
k=300*x12[i]+400*y12[i]
if(m<k):
m=k
p=x12[i]
q=y12[i]
print("Max Value",m)
plt.scatter(x12,y12)
#lt.scatter(p,q)
for i, txt in enumerate(n):
plt.annotate(txt, (x12[i], y12[i])) Ritwika Das
plt.fill_between(x,y6,y7,where=y6>y7,color='grey',alpha=0.5) Roll-16IT8058
plt.legend(bbox_to_anchor=(1.05,1),loc=2,borderaxespad=0.)
plt.show()

OUTPUT
Linear Regression
import numpy as np Ritwika Das
import matplotlib.pyplot as plt Roll-16IT8058
import random
x = np.linspace(0,100,100)
y = 15*x + 5 + np.random.normal(0,10,100)
plt.scatter(x,y)
x1 = x - np.mean(x)
x2 = y - np.mean(y)
x3 = np.multiply(x1,x2)
x4 = np.sum(x3)
x5 = np.sum(x1**2)
beta1 = x4/x5
x_cal=np.linspace(0,100,100)
beta0 = np.mean(y) - beta1*(np.mean(x))
y_cal = beta0 + beta1*x
plt.plot(x_cal,y_cal,'-r',label='y=b0+b1*x')
Sres = np.sum((y - y_cal)**2)
Sebeta1 = Sres/(100*x5)
Sebeta1 = Sebeta1**0.5
Stotal = np.sum(x2**2)
rs = 1 - (Sres/Stotal)
x6 = np.sum(x*y) - np.sum(x)
x7 = 100*np.sum(y)*x6
x8 = 100*np.sum(x**2) - (np.sum(x))**2
x9 = 100*np.sum(y**2) - (np.sum(y))**2
x10 = np.sqrt(x8*x9)
rho = x7/x10
print("Beta0", beta0)
print("Beta1", beta1)
print("Sres", Sres)
print("Sebeta1", Sebeta1)
print("Stotal", Stotal)
print("R^2", rs)
print("Rho", rho)
plt.plot(x,y_cal)
plt.legend()
plt.show()

OUTPUT
NATIONAL INSTITUTE OF TECHNOLOGY
SIMULATION LAB (IT-752)
NAME-RITWIKA DAS
ROLL-16IT8058
SIMPLEX METHOD
import heapq Ritwika Das
Roll-16IT8058
def identity(numRows, numCols, val=1, rowStart=0):
return [[(val if i == j else 0) for j in range(numCols)]
for i in range(rowStart, numRows)]
def standardForm(cost, greaterThans=[], gtThreshold=[], lessThans=[],
ltThreshold=[],
equalities=[], eqThreshold=[], maximization=True):
newVars = 0
numRows = 0
if gtThreshold != []:
newVars += len(gtThreshold)
numRows += len(gtThreshold)
if ltThreshold != []:
newVars += len(ltThreshold)
numRows += len(ltThreshold)
if eqThreshold != []:
numRows += len(eqThreshold)
if not maximization:
cost = [-x for x in cost]
if newVars == 0:
return cost, equalities, eqThreshold
newCost = list(cost) + [0] * newVars
constraints = []
threshold = []
oldConstraints = [(greaterThans, gtThreshold, -1), (lessThans,
ltThreshold, 1),
(equalities, eqThreshold, 0)]

offset = 0
for constraintList, oldThreshold, coefficient in oldConstraints:
constraints += [c + r for c, r in zip(constraintList,
identity(numRows, newVars, coefficient, offset))]

threshold += oldThreshold
offset += len(oldThreshold)

return newCost, constraints, threshold


def dot(a,b):
return sum(x*y for x,y in zip(a,b))

def column(A, j):


return [row[j] for row in A]

def transpose(A):
return [column(A, j) for j in range(len(A[0]))]

def isPivotCol(col):
return (len([c for c in col if c == 0]) == len(col) - 1) and sum(col) ==
1

def variableValueForPivotColumn(tableau, column):


pivotRow = [i for (i, x) in enumerate(column) if x == 1][0]
return tableau[pivotRow][-1]

def initialTableau(c, A, b):


tableau = [row[:] + [x] for row, x in zip(A, b)]
tableau.append([ci for ci in c] + [0]) Ritwika Das
return tableau Roll-16IT8058

def primalSolution(tableau):

columns = transpose(tableau)
indices = [j for j, col in enumerate(columns[:-1]) if isPivotCol(col)]
return [(colIndex, variableValueForPivotColumn(tableau,
columns[colIndex]))
for colIndex in indices]

def objectiveValue(tableau):
return -(tableau[-1][-1])

def canImprove(tableau):
lastRow = tableau[-1]
return any(x > 0 for x in lastRow[:-1])

def moreThanOneMin(L):
if len(L) <= 1:
return False

x,y = heapq.nsmallest(2, L, key=lambda x: x[1])


return x == y

def findPivotIndex(tableau):
column_choices = [(i,x) for (i,x) in enumerate(tableau[-1][:-1]) if x >
0]
column = min(column_choices, key=lambda a: a[1])[0]

if all(row[column] <= 0 for row in tableau):


raise Exception('Linear program is unbounded.')

quotients = [(i, r[-1] / r[column])


for i,r in enumerate(tableau[:-1]) if r[column] > 0]

if moreThanOneMin(quotients):
raise Exception('Linear program is degenerate.')

row = min(quotients, key=lambda x: x[1])[0]

return row, column

def pivotAbout(tableau, pivot):


i,j = pivot

pivotDenom = tableau[i][j]
tableau[i] = [x / pivotDenom for x in tableau[i]]

for k,row in enumerate(tableau):


if k != i:
pivotRowMultiple = [y * tableau[k][j] for y in tableau[i]]
tableau[k] = [x - y for x,y in zip(tableau[k], pivotRowMultiple)]
def simplex(c, A, b): Ritwika Das
tableau = initialTableau(c, A, b) Roll-16IT8058
print("Initial table:")
for row in tableau:
print(row)
print()

while canImprove(tableau):
pivot = findPivotIndex(tableau)
print("Next pivot index is=%d,%d \n" % pivot)
pivotAbout(tableau, pivot)
print("Table after pivot:")
for row in tableau:
print(row)
print()

return tableau, primalSolution(tableau), objectiveValue(tableau)

if __name__ == "__main__":
# c = [300, 250, 450]
# A = [[15, 20, 25], [35, 60, 60], [20, 30, 25], [0, 250, 0]]
# b = [1200, 3000, 1500, 500]

c = [4,3]
A = [[2,1], [1,1], [1,0], [0,1]]
b = [1000, 800, 400, 700]

# add slack variables by hand


A[0] += [1,0,0,0]
A[1] += [0,1,0,0]
A[2] += [0,0,1,0]
A[3] += [0,0,0,1]
c += [0,0,0,0]

t, s, v = simplex(c, A, b)
print(s)
print(v)
OUTPUT
MULTI VARIATE METHOD
from sympy import diff,symbols Riwika Das
import numpy as np Roll-16IT8058
from matplotlib import pyplot as plt
from mpl_toolkits import mplot3d
x1,x2,s1,s2,lamda1,lamda2=symbols('x1 x2 s1 s2 lamda1 lamda2',real=True)
f=(10*x1-x1**2+10*x2-x2**2)-lamda1*(x1+x2+s1**2-14)-lamda2*(-x1+x2+s2**2-6)
l1=diff(f,x1)
l2=diff(f,x2)
s11=diff(f,s1)
s12=diff(f,s2)
a=diff(f,lamda1)
b=diff(f,lamda2)
l11=diff(l1,x1)
l12=diff(l1,x2)
l21=diff(l2,x1)
l22=diff(l2,x2)
det=l11*l22-l12*l21
import sympy as sym
sym.init_printing()
c=sym.Eq(l1)
d=sym.Eq(l2)
e=sym.Eq(s11)
f=sym.Eq(s12)
g=sym.Eq(a)
h=sym.Eq(b)
y=sym.solve([c,d,e,f,g,h],(x1,x2,s1,s2,lamda1,lamda2))
t=[]
for i in range(len(y)):
if y[i][4]==0 and y[i][5]==0:
t.append(y[i])
print(t)
func=10*int(t[0][0])-int(t[0][0])**2+10*int(t[0][1])-int(t[0][1])**2
print(func)
fig=plt.figure()
ax = plt.axes(projection="3d")
def f(x, y):
return 10*x-x**2+10*y-y**2

#def f(x, y):


#return np.sin(np.sqrt(x ** 2 + y ** 2))

x = np.linspace(-6, 6, 30)
y = np.linspace(-6, 6, 30)

X, Y = np.meshgrid(x, y)
Z = f(X,Y)
fig = plt.figure()
ax = plt.axes(projection="3d")
ax.plot_wireframe(X, Y, Z, color='green')
ax.set_xlabel('x')
ax.set_ylabel('y')
#ax.set_zlevel('z')
plt.show()
OUTPUT Ritwika Das

Roll-16IT8058

You might also like