лаба 1 готова

This commit is contained in:
2023-12-17 23:37:53 +04:00
parent 6c8ad0399c
commit 9ca2e2b9a4
10 changed files with 172 additions and 0 deletions

3
.idea/.gitignore generated vendored Normal file
View File

@@ -0,0 +1,3 @@
# Default ignored files
/shelf/
/workspace.xml

8
.idea/VM_lab_PIbd_31_Akimova_A.A.iml generated Normal file
View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

View File

@@ -0,0 +1,12 @@
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="PyUnresolvedReferencesInspection" enabled="true" level="WARNING" enabled_by_default="true">
<option name="ignoredIdentifiers">
<list>
<option value="list.__truediv__" />
</list>
</option>
</inspection_tool>
</profile>
</component>

View File

@@ -0,0 +1,6 @@
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>

4
.idea/misc.xml generated Normal file
View File

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.11" project-jdk-type="Python SDK" />
</project>

8
.idea/modules.xml generated Normal file
View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/VM_lab_PIbd_31_Akimova_A.A.iml" filepath="$PROJECT_DIR$/.idea/VM_lab_PIbd_31_Akimova_A.A.iml" />
</modules>
</component>
</project>

6
.idea/vcs.xml generated Normal file
View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
</component>
</project>

View File

@@ -1,2 +1,28 @@
# VM_lab_PIbd_31_Akimova_A.A
# Участники: Акимова А.А.
# Вариант 6.
Для изготовления двух видов продукции P1 и P2 используют 4 вида ресурсов S1, S2, S3, S4.
Запасы ресурсов: S1 - 18, S2 - 16, S3 - 5, S4 - 21.
Число единиц ресурсов,
затрачиваемых на изготовление единицы продукции P1:
S1 - 1, S2 - 2, S3 - нет, S4 - 3
Число единиц ресурсов,
затрачиваемых на изготовление единицы продукции P2:
S1 - 3, S2 - 1, S3 - 1, S4 - нет
Стоимость ед. продукции P1 - 2, P2 - 3.
Необходимо максимизировать прибыль от реализации продукции.
Система неравентсв для решения симплекс-методом:
x1 + 3x2 <= 18
2x1 + x2 <= 16
x2 <= 5
3x1 <= 21
F = 2x1 + 3x2 -> max

80
SimplexMethod.py Normal file
View File

@@ -0,0 +1,80 @@
import numpy as np
class SimplexMethod:
def __init__(self, source):
# исходная таблица source
m, n = source.shape
# table - таблица, с которой будем работать
# basis - базисные переменные
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):
# Основной цикл симплекс-метода
while not self.is_it_end():
# Находим ведущий столбец и ведущую строку
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
# Вытаскиваем решение
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

19
main.py Normal file
View File

@@ -0,0 +1,19 @@
import numpy as np
import tabulate as tb
from SimplexMethod import SimplexMethod
table = np.array([[18, 1, 3],
[16, 2, 1],
[5, 0, 1],
[21, 3, 0],
[0, -2, -3]])
result = np.zeros(2)
S = SimplexMethod(table)
table_result = S.calculate(result)
print(tb.tabulate(table_result))
print("\n")
print(f"X[max] = {result}")
print(f"F[max] = {table_result[-1][0]:.2f}")