99 lines
2.7 KiB
Python
99 lines
2.7 KiB
Python
import numpy as np
|
|
|
|
|
|
def return_status(table, n):
|
|
for i in range(n - 1):
|
|
if table[-1, i] < 0:
|
|
return True
|
|
return False
|
|
|
|
|
|
def find_min_col(table):
|
|
if np.ndim(table) != 2:
|
|
return
|
|
m, n = table.shape
|
|
main_col = 1
|
|
for j in range(n - 2):
|
|
if table[m - 1, j] < table[m - 1, main_col]:
|
|
main_col = j
|
|
return main_col
|
|
|
|
|
|
def return_row(table, column):
|
|
if np.ndim(table) != 2:
|
|
return
|
|
m, n = table.shape
|
|
main_row = 0
|
|
for i in range(m - 1):
|
|
if table[i, column] > 0:
|
|
main_row = i
|
|
break
|
|
for i in range(main_row + 1, m - 1):
|
|
if table[i, column] > 0 and (table[i, 0] / table[i, column]) < (
|
|
table[main_row, 0] / table[main_row, column]):
|
|
main_row = i
|
|
return main_row
|
|
|
|
|
|
class SimplexMethod:
|
|
def __init__(self, data):
|
|
m, n = data.shape
|
|
|
|
self.table = np.zeros((m, n + m))
|
|
self.table[:, :n - 1] = data[:, :n - 1] # Копируем значения из data в первые n столбцов table
|
|
self.table[:, -2] = data[:, -1] # Копируем последний столбец (вектор правой части)
|
|
|
|
for i in range(m - 1):
|
|
self.table[i, n - 1 + i] = 1
|
|
|
|
self.m, self.n = self.table.shape
|
|
|
|
def return_table(self):
|
|
return self.table
|
|
|
|
def solve(self):
|
|
while return_status(self.table, self.n):
|
|
column_with_min_value = find_min_col(self.table)
|
|
row_with_min_value = return_row(self.table, column_with_min_value)
|
|
|
|
new_table = np.copy(self.table)
|
|
|
|
new_table[row_with_min_value, :] /= self.table[row_with_min_value, column_with_min_value]
|
|
|
|
for i in range(self.m):
|
|
if i == row_with_min_value:
|
|
continue
|
|
|
|
ratio = self.table[i, column_with_min_value]
|
|
|
|
new_table[i, :] -= ratio * new_table[row_with_min_value, :]
|
|
|
|
self.table = new_table
|
|
|
|
def return_result(self, out_count):
|
|
result = []
|
|
|
|
for j in range(self.n - 2):
|
|
if len(result) >= out_count:
|
|
break
|
|
|
|
index = 0
|
|
count = 0
|
|
|
|
for i in range(self.m):
|
|
if self.table[i, j] != 0:
|
|
count += 1
|
|
index = i
|
|
|
|
if count == 1:
|
|
result.append({
|
|
"name": "x" + str(index),
|
|
"value": self.table[index, self.n - 2] / self.table[index, j]
|
|
})
|
|
|
|
result.append({
|
|
"name": "F",
|
|
"value": self.table[self.m - 1, self.n - 2]
|
|
})
|
|
return result
|