Computational_Mathematics_L.../simplexImp.py

99 lines
2.7 KiB
Python
Raw Normal View History

2023-12-20 00:52:58 +04:00
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
2023-12-20 01:41:26 +04:00
for j in range(n - 1):
2023-12-20 00:52:58 +04:00
if table[m - 1, j] < table[m - 1, main_col]:
main_col = j
return main_col
2023-12-20 01:41:26 +04:00
def find_min_row(table, column):
2023-12-20 00:52:58 +04:00
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
2023-12-20 01:41:26 +04:00
self.table = np.zeros((m, n + m - 1))
2023-12-20 00:52:58 +04:00
self.table[:, :n - 1] = data[:, :n - 1] # Копируем значения из data в первые n столбцов table
2023-12-20 01:41:26 +04:00
self.table[:, -1] = data[:, -1] # Копируем последний столбец (вектор правой части)
2023-12-20 00:52:58 +04:00
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)
2023-12-20 01:41:26 +04:00
row_with_min_value = find_min_row(self.table, column_with_min_value)
2023-12-20 00:52:58 +04:00
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 = []
2023-12-20 01:41:26 +04:00
for j in range(self.n - 1):
2023-12-20 00:52:58 +04:00
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),
2023-12-20 01:41:26 +04:00
"value": self.table[index, self.n - 1] / self.table[index, j]
2023-12-20 00:52:58 +04:00
})
result.append({
"name": "F",
2023-12-20 01:41:26 +04:00
"value": self.table[self.m - 1, self.n - 1]
2023-12-20 00:52:58 +04:00
})
return result