Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 76aea53

Browse files
author
MohdFuzailHaider
committedOct 9, 2024·
Add linear programming implementation using the simplex method
1 parent fcf82a1 commit 76aea53

File tree

1 file changed

+120
-0
lines changed

1 file changed

+120
-0
lines changed
 

‎my_script.py

Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
import numpy as np
2+
3+
class Tableau:
4+
def __init__(self, tableau):
5+
self.tableau = tableau
6+
self.num_rows, self.num_cols = tableau.shape
7+
8+
def pivot(self, row, col):
9+
# Divide the pivot row by the pivot element
10+
self.tableau[row] /= self.tableau[row, col]
11+
12+
# Subtract multiples of the pivot row from all other rows
13+
for i in range(self.num_rows):
14+
if i != row:
15+
self.tableau[i] -= self.tableau[i, col] * self.tableau[row]
16+
17+
def find_pivot_column(self):
18+
# The pivot column is the most negative value in the objective row (row 0)
19+
obj_row = self.tableau[0, :-1]
20+
pivot_col = np.argmin(obj_row)
21+
if obj_row[pivot_col] >= 0:
22+
return -1 # No negative value, we are done
23+
return pivot_col
24+
25+
def find_pivot_row(self, pivot_col):
26+
# Calculate the ratios of the right-hand side to the pivot column entries
27+
rhs = self.tableau[1:, -1]
28+
col = self.tableau[1:, pivot_col]
29+
ratios = []
30+
for i in range(len(rhs)):
31+
if col[i] > 0:
32+
ratios.append(rhs[i] / col[i])
33+
else:
34+
ratios.append(np.inf) # Ignore non-positive entries
35+
36+
pivot_row = np.argmin(ratios) + 1 # Add 1 because we ignored row 0
37+
if np.isinf(ratios[pivot_row - 1]):
38+
return -1 # No valid pivot row (unbounded)
39+
return pivot_row
40+
41+
def run_simplex(self):
42+
while True:
43+
pivot_col = self.find_pivot_column()
44+
if pivot_col == -1:
45+
break # Optimal solution found
46+
47+
pivot_row = self.find_pivot_row(pivot_col)
48+
if pivot_row == -1:
49+
raise ValueError("Linear program is unbounded.")
50+
51+
self.pivot(pivot_row, pivot_col)
52+
53+
return self.extract_solution()
54+
55+
def extract_solution(self):
56+
solution = np.zeros(self.num_cols - 1)
57+
for i in range(1, self.num_rows):
58+
col = self.tableau[i, :-1]
59+
if np.count_nonzero(col) == 1:
60+
solution[np.argmax(col)] = self.tableau[i, -1]
61+
return solution, -self.tableau[0, -1] # Return solution and optimal value
62+
63+
def construct_tableau(objective, constraints, rhs):
64+
"""
65+
Constructs the initial tableau for the simplex algorithm.
66+
67+
Parameters:
68+
- objective: List of coefficients of the objective function (maximize).
69+
- constraints: List of lists representing coefficients of the constraints.
70+
- rhs: List of right-hand-side values of constraints.
71+
72+
Returns:
73+
- tableau: A numpy array representing the initial simplex tableau.
74+
"""
75+
n_constraints = len(constraints)
76+
n_vars = len(objective)
77+
78+
# Creating the tableau matrix
79+
tableau = np.zeros((n_constraints + 1, n_vars + n_constraints + 1))
80+
81+
# Fill the objective function (row 0, cols 0 to n_vars)
82+
tableau[0, :n_vars] = -np.array(objective) # Maximization -> negate
83+
84+
# Fill the constraints
85+
for i in range(n_constraints):
86+
tableau[i + 1, :n_vars] = constraints[i]
87+
tableau[i + 1, n_vars + i] = 1 # Slack variable
88+
tableau[i + 1, -1] = rhs[i] # RHS of the constraints
89+
90+
return tableau
91+
92+
def solve_linear_program(objective, constraints, rhs):
93+
# Constructing the tableau
94+
tableau = construct_tableau(objective, constraints, rhs)
95+
96+
# Instantiate the Tableau class
97+
simplex_tableau = Tableau(tableau)
98+
99+
# Run the simplex algorithm
100+
solution, optimal_value = simplex_tableau.run_simplex()
101+
102+
# Output the solution
103+
print("Optimal Solution:", solution)
104+
print("Optimal Value:", optimal_value)
105+
106+
# Example usage
107+
if __name__ == "__main__":
108+
# Coefficients of the objective function: maximize 3x1 + 2x2
109+
objective = [3, 2]
110+
111+
# Coefficients of the constraints:
112+
# 2x1 + x2 <= 18
113+
# x1 + 2x2 <= 20
114+
constraints = [[2, 1], [1, 2]]
115+
116+
# Right-hand side of the constraints
117+
rhs = [18, 20]
118+
119+
# Solve the linear program
120+
solve_linear_program(objective, constraints, rhs)

0 commit comments

Comments
 (0)
Please sign in to comment.