import numpy as np import tabulate as tb class Simplex: def __init__(self, source): m, n = source.shape self.table = np.zeros((m, n + m - 1)) self.basis = [] for i in range(m): for j in range(self.table.shape[1]): if j < n: self.table[i, j] = source[i, j] else: self.table[i, j] = 0 if (n + i) < self.table.shape[1]: self.table[i, n + i] = 1 self.basis.append(n + i) self.m = m self.n = self.table.shape[1] def calculate(self, result): counter = 0 while not self.is_it_end() and counter < 10: main_col = self.find_main_col() main_row = self.find_main_row(main_col) self.basis[main_row] = main_col new_table = np.zeros((self.m, self.n)) for j in range(self.n): new_table[main_row, j] = self.table[main_row, j] / self.table[main_row, main_col] for i in range(self.m): if i == main_row: continue for j in range(self.n): new_table[i, j] = self.table[i, j] - self.table[i, main_col] * new_table[main_row, j] self.table = new_table counter += 1 print("Main col: " + str(main_col)) print("Main row: " + str(main_row)) print("Basis: ") for i in self.basis: print(self.basis.index(i), i) print(tb.tabulate(self.table)) for i in range(len(result)): k = self.basis.index(i + 1) if i + 1 in self.basis else -1 result[i] = self.table[k, 0] if k != -1 else 0 return self.table def is_it_end(self): return np.all(self.table[self.m - 1, 1:] >= 0) def find_main_col(self): main_col = 1 for j in range(2, self.n): if self.table[self.m - 1, j] > self.table[self.m - 1, main_col]: main_col = j return main_col def find_main_row(self, main_col): main_row = 0 for i in range(self.m - 1): if self.table[i, main_col] > 0: main_row = i break for i in range(main_row + 1, self.m - 1): if self.table[i, main_col] > 0 and (self.table[i, 0] / self.table[i, main_col]) < ( self.table[main_row, 0] / self.table[main_row, main_col]): main_row = i return main_row if __name__ == "__main__": table = np.array([[7, 1, 1, 1, -1, 1, 0], [2, 1, -1, 1, -1, 0, -1], [-5, 3, -1, -2, 2, 0, 0], [0, -1, 2, -3, 3, 0, 0]]) result = np.zeros(6) S = Simplex(table) table_result = S.calculate(result) print("Resulting simplex table") print(tb.tabulate(table_result)) print("\nResult:") print(f"X[max] = {result}") print(f"F[max] = {-1 * table_result[-1][0]:.2f}")