Advertisement
Andre1314

Untitled

Mar 31st, 2023
173
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.97 KB | None | 0 0
  1. import numpy as np
  2. import math
  3.  
  4.  
  5. def notOptimized(table):
  6.     z = table[-1]
  7.     return any(x > 0 for x in z[:-1])
  8.  
  9.  
  10. def isBasic(column):
  11.     return sum(column) == 1 and len([c for c in column if c == 0]) == len(column) - 1
  12.  
  13.  
  14. def toTable(A, b, c):
  15.     xb = [eq + [x] for eq, x in zip(A, b)]
  16.     z = c + [0]
  17.     return xb + [z]
  18.  
  19.  
  20. def vectorOf(table):
  21.     vecs = np.array(table).T
  22.     res = []
  23.     for column in vecs:
  24.         x = 0
  25.         if isBasic(column):
  26.             one_index = column.tolist().index(1)
  27.             x = vecs[-1][one_index]
  28.         res.append(round(x, 3))
  29.  
  30.     return res
  31.  
  32.  
  33. def pivotPosition(table):
  34.     z = table[-1]
  35.     column = next(i for i, x in enumerate(z[:-1]) if x > 0)
  36.  
  37.     constraints = []
  38.     for eq in table[:-1]:
  39.         el = eq[column]
  40.         constraints.append(math.inf if el <= 0 else eq[-1] / el)
  41.  
  42.     row = constraints.index(min(constraints))
  43.     return row, column
  44.  
  45.  
  46. def pivotStep(table, pivotPosition):
  47.     newTable = [[] for row in range(len(table))]
  48.  
  49.     i, j = pivotPosition
  50.     pivot_value = table[i][j]
  51.     newTable[i] = np.array(table[i]) / pivot_value
  52.  
  53.     for eqi, eq in enumerate(table):
  54.         if eqi != i:
  55.             multiplier = np.array(newTable[i]) * table[eqi][j]
  56.             newTable[eqi] = np.array(table[eqi]) - multiplier
  57.  
  58.     return newTable
  59.  
  60.  
  61. def smethod(A, b, c):
  62.     table = toTable(A, b, c)
  63.     while notOptimized(table):
  64.         pivot_position = pivotPosition(table)
  65.         table = pivotStep(table, pivot_position)
  66.  
  67.     vec = vectorOf(table)[:-1]
  68.     F = 0
  69.     for i in range(len(c)):
  70.         F += c[i] * vec[i]
  71.  
  72.     print("Optimal plan vector:", vec)
  73.     print("Max F:", F)
  74.  
  75.  
  76. # c = np.array([1, 2, 0, 0, 0])
  77. # A = np.array([
  78. #     [5, -2, 1, 0, 0],
  79. #     [-1, 2, 0, 1, 0],
  80. #     [1, 1, 0, 0, -1]
  81. # ])
  82. # b = np.array([4, 4, 4])
  83.  
  84. c = [1, 2, 0, 0, 0]
  85. A = [
  86.     [5, -2, 1, 0, 0],
  87.     [-1, 2, 0, 1, 0],
  88.     [1, 1, 0, 0, -1]
  89. ]
  90. b = [4, 4, 4]
  91.  
  92. smethod(A, b, c)
  93.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement