PyOR 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pyOR/__init__.py +55 -0
- pyOR/assignment.py +281 -0
- pyOR/big_m.py +308 -0
- pyOR/curve_fitting.py +339 -0
- pyOR/dual_simplex.py +254 -0
- pyOR/graphical_method.py +255 -0
- pyOR/linear_programming.py +154 -0
- pyOR/project_management.py +284 -0
- pyOR/simplex.py +248 -0
- pyOR/spline_fitting.py +306 -0
- pyOR/transportation.py +527 -0
- pyor-1.0.0.dist-info/METADATA +313 -0
- pyor-1.0.0.dist-info/RECORD +16 -0
- pyor-1.0.0.dist-info/WHEEL +5 -0
- pyor-1.0.0.dist-info/licenses/LICENSE +21 -0
- pyor-1.0.0.dist-info/top_level.txt +1 -0
pyOR/__init__.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
"""
|
|
2
|
+
PyOR - Python Operations Research Library
|
|
3
|
+
==========================================
|
|
4
|
+
A comprehensive library for solving Operations Research problems.
|
|
5
|
+
|
|
6
|
+
Modules:
|
|
7
|
+
- linear_programming : LP Formulation using standard form
|
|
8
|
+
- graphical_method : Graphical method for 2-variable LP
|
|
9
|
+
- simplex : Simplex Method (Maximization & Minimization)
|
|
10
|
+
- dual_simplex : Dual Simplex Method
|
|
11
|
+
- big_m : Big-M Method
|
|
12
|
+
- transportation : NW Corner, Least Cost, VAM, MODI's Method
|
|
13
|
+
- assignment : Assignment Problem (Hungarian Algorithm)
|
|
14
|
+
- project_management : PERT / CPM
|
|
15
|
+
- curve_fitting : Least Squares Curve Fitting
|
|
16
|
+
- spline_fitting : Cubic Spline Interpolation
|
|
17
|
+
|
|
18
|
+
Author : PyOR Contributors
|
|
19
|
+
License : MIT
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from .linear_programming import LinearProgram
|
|
23
|
+
from .graphical_method import GraphicalMethod
|
|
24
|
+
from .simplex import SimplexMethod
|
|
25
|
+
from .dual_simplex import DualSimplex
|
|
26
|
+
from .big_m import BigMMethod
|
|
27
|
+
from .transportation import (
|
|
28
|
+
north_west_corner,
|
|
29
|
+
least_cost_method,
|
|
30
|
+
vogel_approximation,
|
|
31
|
+
modi_method,
|
|
32
|
+
)
|
|
33
|
+
from .assignment import AssignmentProblem
|
|
34
|
+
from .project_management import PERTCPMNetwork
|
|
35
|
+
from .curve_fitting import CurveFitter
|
|
36
|
+
from .spline_fitting import CubicSplineFitter
|
|
37
|
+
|
|
38
|
+
__all__ = [
|
|
39
|
+
"LinearProgram",
|
|
40
|
+
"GraphicalMethod",
|
|
41
|
+
"SimplexMethod",
|
|
42
|
+
"DualSimplex",
|
|
43
|
+
"BigMMethod",
|
|
44
|
+
"north_west_corner",
|
|
45
|
+
"least_cost_method",
|
|
46
|
+
"vogel_approximation",
|
|
47
|
+
"modi_method",
|
|
48
|
+
"AssignmentProblem",
|
|
49
|
+
"PERTCPMNetwork",
|
|
50
|
+
"CurveFitter",
|
|
51
|
+
"CubicSplineFitter",
|
|
52
|
+
]
|
|
53
|
+
|
|
54
|
+
__version__ = "1.0.0"
|
|
55
|
+
__author__ = "PyOR Contributors"
|
pyOR/assignment.py
ADDED
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Module: assignment.py
|
|
3
|
+
======================
|
|
4
|
+
AIM:
|
|
5
|
+
To solve the Assignment Problem (minimisation / maximisation) using
|
|
6
|
+
the Hungarian Algorithm (also called the Munkres or Kuhn-Munkres method).
|
|
7
|
+
|
|
8
|
+
The Assignment Problem assigns n workers to n jobs (or tasks to agents)
|
|
9
|
+
such that the total cost (or profit) is minimised (or maximised).
|
|
10
|
+
|
|
11
|
+
Steps of the Hungarian Algorithm:
|
|
12
|
+
1. Subtract row minima from each row.
|
|
13
|
+
2. Subtract column minima from each column.
|
|
14
|
+
3. Cover all zeros with the minimum number of lines.
|
|
15
|
+
4. If #lines == n → optimal assignment found.
|
|
16
|
+
5. Otherwise, find the minimum uncovered element, subtract it
|
|
17
|
+
from uncovered elements, and add it to doubly-covered elements.
|
|
18
|
+
6. Repeat from step 3.
|
|
19
|
+
|
|
20
|
+
Handles:
|
|
21
|
+
- Square and non-square matrices (auto-padded with dummy rows/cols).
|
|
22
|
+
- Maximisation (converted to minimisation by negating / subtracting).
|
|
23
|
+
- Multiple optimal solutions (returns one).
|
|
24
|
+
- Infeasibility detection (though a valid assignment always exists
|
|
25
|
+
for finite cost matrices).
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
from __future__ import annotations
|
|
29
|
+
import numpy as np
|
|
30
|
+
from typing import List, Optional, Tuple
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class AssignmentProblem:
|
|
34
|
+
"""
|
|
35
|
+
Solve the Assignment Problem using the Hungarian Algorithm.
|
|
36
|
+
|
|
37
|
+
Parameters
|
|
38
|
+
----------
|
|
39
|
+
cost_matrix : 2-D cost (or profit) matrix.
|
|
40
|
+
objective : 'min' (default) or 'max'.
|
|
41
|
+
row_names : Optional labels for rows (agents / workers).
|
|
42
|
+
col_names : Optional labels for columns (tasks / jobs).
|
|
43
|
+
|
|
44
|
+
Examples
|
|
45
|
+
--------
|
|
46
|
+
>>> ap = AssignmentProblem(
|
|
47
|
+
... cost_matrix = [[9, 2, 7, 8],
|
|
48
|
+
... [6, 4, 3, 7],
|
|
49
|
+
... [5, 8, 1, 8],
|
|
50
|
+
... [7, 6, 9, 4]],
|
|
51
|
+
... objective = 'min'
|
|
52
|
+
... )
|
|
53
|
+
>>> result = ap.solve()
|
|
54
|
+
>>> ap.display()
|
|
55
|
+
|
|
56
|
+
>>> # Maximisation example
|
|
57
|
+
>>> ap2 = AssignmentProblem(
|
|
58
|
+
... cost_matrix = [[10, 5, 7],
|
|
59
|
+
... [3, 9, 8],
|
|
60
|
+
... [6, 4, 2]],
|
|
61
|
+
... objective = 'max'
|
|
62
|
+
... )
|
|
63
|
+
>>> ap2.solve()
|
|
64
|
+
"""
|
|
65
|
+
|
|
66
|
+
def __init__(
|
|
67
|
+
self,
|
|
68
|
+
cost_matrix: List[List[float]],
|
|
69
|
+
objective: str = "min",
|
|
70
|
+
row_names: Optional[List[str]] = None,
|
|
71
|
+
col_names: Optional[List[str]] = None,
|
|
72
|
+
):
|
|
73
|
+
self.C_orig = np.array(cost_matrix, dtype=float)
|
|
74
|
+
self.objective = objective.lower()
|
|
75
|
+
if self.objective not in ("min", "max"):
|
|
76
|
+
raise ValueError("objective must be 'min' or 'max'.")
|
|
77
|
+
|
|
78
|
+
m, n = self.C_orig.shape
|
|
79
|
+
self.m_orig, self.n_orig = m, n
|
|
80
|
+
|
|
81
|
+
self.row_names = row_names or [f"Agent {i+1}" for i in range(m)]
|
|
82
|
+
self.col_names = col_names or [f"Task {j+1}" for j in range(n)]
|
|
83
|
+
self.result = None
|
|
84
|
+
|
|
85
|
+
# ------------------------------------------------------------------
|
|
86
|
+
def _pad_square(self, C: np.ndarray) -> np.ndarray:
|
|
87
|
+
"""Pad to square if non-square; fill with max value (zero cost)."""
|
|
88
|
+
m, n = C.shape
|
|
89
|
+
if m == n:
|
|
90
|
+
return C.copy()
|
|
91
|
+
size = max(m, n)
|
|
92
|
+
padded = np.zeros((size, size), dtype=float)
|
|
93
|
+
padded[:m, :n] = C
|
|
94
|
+
return padded
|
|
95
|
+
|
|
96
|
+
# ------------------------------------------------------------------
|
|
97
|
+
def _hungarian(self, C: np.ndarray) -> Tuple[List[Tuple[int,int]], float]:
|
|
98
|
+
"""Core Hungarian algorithm. C must be square."""
|
|
99
|
+
n = C.shape[0]
|
|
100
|
+
mat = C.copy()
|
|
101
|
+
|
|
102
|
+
# Step 1: Row reduction
|
|
103
|
+
mat -= mat.min(axis=1, keepdims=True)
|
|
104
|
+
# Step 2: Column reduction
|
|
105
|
+
mat -= mat.min(axis=0, keepdims=True)
|
|
106
|
+
|
|
107
|
+
for _ in range(10 * n): # bounded iterations
|
|
108
|
+
# Step 3: Cover all zeros with minimum lines
|
|
109
|
+
row_covered, col_covered = self._min_lines(mat, n)
|
|
110
|
+
|
|
111
|
+
if sum(row_covered) + sum(col_covered) >= n:
|
|
112
|
+
break # Optimal
|
|
113
|
+
|
|
114
|
+
# Step 5: Find minimum uncovered element
|
|
115
|
+
uncovered_vals = []
|
|
116
|
+
for i in range(n):
|
|
117
|
+
for j in range(n):
|
|
118
|
+
if not row_covered[i] and not col_covered[j]:
|
|
119
|
+
uncovered_vals.append(mat[i, j])
|
|
120
|
+
mn = min(uncovered_vals)
|
|
121
|
+
|
|
122
|
+
# Subtract from uncovered, add to doubly-covered
|
|
123
|
+
for i in range(n):
|
|
124
|
+
for j in range(n):
|
|
125
|
+
if not row_covered[i] and not col_covered[j]:
|
|
126
|
+
mat[i, j] -= mn
|
|
127
|
+
elif row_covered[i] and col_covered[j]:
|
|
128
|
+
mat[i, j] += mn
|
|
129
|
+
|
|
130
|
+
# Extract assignment from zero matrix
|
|
131
|
+
assignment = self._extract_assignment(mat, n)
|
|
132
|
+
total = sum(C[i, j] for (i, j) in assignment)
|
|
133
|
+
return assignment, float(total)
|
|
134
|
+
|
|
135
|
+
# ------------------------------------------------------------------
|
|
136
|
+
def _min_lines(self, mat: np.ndarray, n: int):
|
|
137
|
+
"""
|
|
138
|
+
Find minimum number of lines to cover all zeros (König's theorem).
|
|
139
|
+
Returns (row_covered, col_covered) boolean arrays.
|
|
140
|
+
"""
|
|
141
|
+
zero_mask = (mat == 0)
|
|
142
|
+
|
|
143
|
+
# Step A: Find a maximal independent set of zeros (greedy matching)
|
|
144
|
+
row_assign = [-1] * n # row_assign[j] = row assigned to col j
|
|
145
|
+
col_assign = [-1] * n # col_assign[i] = col assigned to row i
|
|
146
|
+
|
|
147
|
+
for i in range(n):
|
|
148
|
+
for j in range(n):
|
|
149
|
+
if zero_mask[i, j] and col_assign[i] == -1 and row_assign[j] == -1:
|
|
150
|
+
col_assign[i] = j
|
|
151
|
+
row_assign[j] = i
|
|
152
|
+
|
|
153
|
+
# Step B: Mark rows not in matching
|
|
154
|
+
marked_rows = set(i for i in range(n) if col_assign[i] == -1)
|
|
155
|
+
# Step C: Propagate marks
|
|
156
|
+
changed = True
|
|
157
|
+
marked_cols: set = set()
|
|
158
|
+
while changed:
|
|
159
|
+
changed = False
|
|
160
|
+
new_cols = set()
|
|
161
|
+
for i in marked_rows:
|
|
162
|
+
for j in range(n):
|
|
163
|
+
if zero_mask[i, j] and j not in marked_cols:
|
|
164
|
+
new_cols.add(j)
|
|
165
|
+
for j in new_cols:
|
|
166
|
+
marked_cols.add(j)
|
|
167
|
+
changed = True
|
|
168
|
+
new_rows = set()
|
|
169
|
+
for j in marked_cols:
|
|
170
|
+
if row_assign[j] != -1 and row_assign[j] not in marked_rows:
|
|
171
|
+
new_rows.add(row_assign[j])
|
|
172
|
+
for i in new_rows:
|
|
173
|
+
marked_rows.add(i)
|
|
174
|
+
changed = True
|
|
175
|
+
|
|
176
|
+
# Step D: Lines = unmarked rows + marked cols
|
|
177
|
+
row_covered = [i not in marked_rows for i in range(n)]
|
|
178
|
+
col_covered = [j in marked_cols for j in range(n)]
|
|
179
|
+
return row_covered, col_covered
|
|
180
|
+
|
|
181
|
+
# ------------------------------------------------------------------
|
|
182
|
+
def _extract_assignment(self, mat: np.ndarray, n: int) -> List[Tuple[int,int]]:
|
|
183
|
+
"""Extract a complete assignment from the reduced zero matrix."""
|
|
184
|
+
assigned_rows = set()
|
|
185
|
+
assigned_cols = set()
|
|
186
|
+
assignment = []
|
|
187
|
+
|
|
188
|
+
# Greedy: prefer rows/cols with fewest zeros
|
|
189
|
+
zero_mask = (mat < 1e-10)
|
|
190
|
+
row_zeros = zero_mask.sum(axis=1)
|
|
191
|
+
|
|
192
|
+
for i in sorted(range(n), key=lambda x: row_zeros[x]):
|
|
193
|
+
for j in range(n):
|
|
194
|
+
if zero_mask[i, j] and j not in assigned_cols:
|
|
195
|
+
assignment.append((i, j))
|
|
196
|
+
assigned_rows.add(i)
|
|
197
|
+
assigned_cols.add(j)
|
|
198
|
+
break
|
|
199
|
+
|
|
200
|
+
# Fill any unassigned rows (fallback)
|
|
201
|
+
unassigned_rows = [i for i in range(n) if i not in assigned_rows]
|
|
202
|
+
unassigned_cols = [j for j in range(n) if j not in assigned_cols]
|
|
203
|
+
for i, j in zip(unassigned_rows, unassigned_cols):
|
|
204
|
+
assignment.append((i, j))
|
|
205
|
+
|
|
206
|
+
return assignment
|
|
207
|
+
|
|
208
|
+
# ------------------------------------------------------------------
|
|
209
|
+
def solve(self) -> dict:
|
|
210
|
+
"""
|
|
211
|
+
Solve the Assignment Problem.
|
|
212
|
+
|
|
213
|
+
Returns
|
|
214
|
+
-------
|
|
215
|
+
dict with keys:
|
|
216
|
+
status : 'Optimal'
|
|
217
|
+
assignment : List of (row, col) pairs
|
|
218
|
+
obj_value : Total cost / profit
|
|
219
|
+
assignment_matrix : n×n binary matrix
|
|
220
|
+
"""
|
|
221
|
+
C = self.C_orig.copy()
|
|
222
|
+
|
|
223
|
+
# For maximisation: convert to minimisation
|
|
224
|
+
if self.objective == "max":
|
|
225
|
+
C = C.max() - C
|
|
226
|
+
|
|
227
|
+
# Pad to square if non-square
|
|
228
|
+
m_orig, n_orig = C.shape
|
|
229
|
+
C_sq = self._pad_square(C)
|
|
230
|
+
n = C_sq.shape[0]
|
|
231
|
+
|
|
232
|
+
assignment_sq, _ = self._hungarian(C_sq)
|
|
233
|
+
|
|
234
|
+
# Filter dummy assignments
|
|
235
|
+
assignment = [(i, j) for (i, j) in assignment_sq
|
|
236
|
+
if i < m_orig and j < n_orig]
|
|
237
|
+
|
|
238
|
+
# Total cost on original matrix
|
|
239
|
+
obj = float(sum(self.C_orig[i, j] for (i, j) in assignment))
|
|
240
|
+
|
|
241
|
+
# Assignment matrix
|
|
242
|
+
A_mat = np.zeros_like(self.C_orig, dtype=int)
|
|
243
|
+
for (i, j) in assignment:
|
|
244
|
+
A_mat[i, j] = 1
|
|
245
|
+
|
|
246
|
+
self.result = {
|
|
247
|
+
"status" : "Optimal",
|
|
248
|
+
"assignment" : assignment,
|
|
249
|
+
"obj_value" : obj,
|
|
250
|
+
"assignment_matrix" : A_mat,
|
|
251
|
+
}
|
|
252
|
+
return self.result
|
|
253
|
+
|
|
254
|
+
# ------------------------------------------------------------------
|
|
255
|
+
def display(self) -> None:
|
|
256
|
+
"""Print the cost matrix, optimal assignment, and total cost."""
|
|
257
|
+
if self.result is None:
|
|
258
|
+
self.solve()
|
|
259
|
+
r = self.result
|
|
260
|
+
m, n = self.C_orig.shape
|
|
261
|
+
|
|
262
|
+
print("=" * 55)
|
|
263
|
+
print(f" Assignment Problem ({self.objective.upper()}IMISATION)")
|
|
264
|
+
print("=" * 55)
|
|
265
|
+
print(" Cost Matrix:")
|
|
266
|
+
hdr = " " + " " * 14 + " ".join(f"{c:<8}" for c in self.col_names)
|
|
267
|
+
print(hdr)
|
|
268
|
+
for i in range(m):
|
|
269
|
+
mark_str = ""
|
|
270
|
+
row = f" {self.row_names[i]:<14}"
|
|
271
|
+
for j in range(n):
|
|
272
|
+
mark = "*" if (i, j) in r["assignment"] else " "
|
|
273
|
+
row += f"{self.C_orig[i,j]:>7.4g}{mark} "
|
|
274
|
+
print(row)
|
|
275
|
+
print("-" * 55)
|
|
276
|
+
print(" Optimal Assignment:")
|
|
277
|
+
for (i, j) in r["assignment"]:
|
|
278
|
+
print(f" {self.row_names[i]} → {self.col_names[j]}"
|
|
279
|
+
f" (cost = {self.C_orig[i,j]:g})")
|
|
280
|
+
print(f"\n Total {self.objective.capitalize()} Value = {r['obj_value']:.6g}")
|
|
281
|
+
print("=" * 55)
|
pyOR/big_m.py
ADDED
|
@@ -0,0 +1,308 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Module: big_m.py
|
|
3
|
+
=================
|
|
4
|
+
AIM:
|
|
5
|
+
To solve a Linear Programming Problem using the Big-M Method.
|
|
6
|
+
|
|
7
|
+
The Big-M Method handles >= and = constraints by introducing
|
|
8
|
+
artificial variables with a very large penalty coefficient (M)
|
|
9
|
+
in the objective function. If any artificial variable is > 0
|
|
10
|
+
in the final solution the problem is infeasible.
|
|
11
|
+
|
|
12
|
+
Steps:
|
|
13
|
+
1. Convert to standard form:
|
|
14
|
+
<= : add slack variable
|
|
15
|
+
>= : subtract surplus + add artificial variable
|
|
16
|
+
= : add artificial variable
|
|
17
|
+
2. Add M * (artificial) to objective (for minimisation)
|
|
18
|
+
or -M * (artificial) to objective (for maximisation).
|
|
19
|
+
3. Run primal simplex until optimality.
|
|
20
|
+
4. Check feasibility by inspecting artificial variable values.
|
|
21
|
+
|
|
22
|
+
Handles:
|
|
23
|
+
- Maximisation and Minimisation
|
|
24
|
+
- Mixed constraints (<= / >= / =)
|
|
25
|
+
- Infeasibility detection
|
|
26
|
+
- Full tableau printout
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
from __future__ import annotations
|
|
30
|
+
import numpy as np
|
|
31
|
+
from typing import List, Optional
|
|
32
|
+
|
|
33
|
+
_M = 1e7 # Big-M constant
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class BigMMethod:
|
|
37
|
+
"""
|
|
38
|
+
Big-M Method for solving LP problems with >= / = constraints.
|
|
39
|
+
|
|
40
|
+
Parameters
|
|
41
|
+
----------
|
|
42
|
+
c : Objective coefficients.
|
|
43
|
+
A : Constraint matrix.
|
|
44
|
+
b : RHS vector (must be >= 0; multiply row by -1 otherwise).
|
|
45
|
+
senses : List of '<=' | '>=' | '=' per constraint.
|
|
46
|
+
objective : 'min' (default) or 'max'.
|
|
47
|
+
var_names : Optional variable names.
|
|
48
|
+
M : Big-M value (default 1e7).
|
|
49
|
+
|
|
50
|
+
Examples
|
|
51
|
+
--------
|
|
52
|
+
>>> bm = BigMMethod(
|
|
53
|
+
... c = [2, 3],
|
|
54
|
+
... A = [[1, 1], [1, 0], [0, 1]],
|
|
55
|
+
... b = [4, 2, 3],
|
|
56
|
+
... senses = ['<=', '>=', '>='],
|
|
57
|
+
... objective= 'min'
|
|
58
|
+
... )
|
|
59
|
+
>>> result = bm.solve()
|
|
60
|
+
>>> bm.display()
|
|
61
|
+
"""
|
|
62
|
+
|
|
63
|
+
def __init__(
|
|
64
|
+
self,
|
|
65
|
+
c: List[float],
|
|
66
|
+
A: List[List[float]],
|
|
67
|
+
b: List[float],
|
|
68
|
+
senses: Optional[List[str]] = None,
|
|
69
|
+
objective: str = "min",
|
|
70
|
+
var_names: Optional[List[str]] = None,
|
|
71
|
+
M: float = _M,
|
|
72
|
+
):
|
|
73
|
+
self.c_orig = np.array(c, dtype=float)
|
|
74
|
+
self.A_orig = np.array(A, dtype=float)
|
|
75
|
+
self.b_orig = np.array(b, dtype=float)
|
|
76
|
+
self.objective = objective.lower()
|
|
77
|
+
self.M = M
|
|
78
|
+
m, n = self.A_orig.shape
|
|
79
|
+
self.m, self.n = m, n
|
|
80
|
+
|
|
81
|
+
if senses is None:
|
|
82
|
+
senses = ["<="] * m
|
|
83
|
+
if len(senses) != m:
|
|
84
|
+
raise ValueError("len(senses) must equal number of constraints.")
|
|
85
|
+
self.senses = senses
|
|
86
|
+
|
|
87
|
+
# Ensure b >= 0
|
|
88
|
+
for i in range(m):
|
|
89
|
+
if self.b_orig[i] < 0:
|
|
90
|
+
self.b_orig[i] *= -1
|
|
91
|
+
self.A_orig[i, :] *= -1
|
|
92
|
+
opposite = {"<=": ">=", ">=": "<=", "=": "="}
|
|
93
|
+
self.senses[i] = opposite[self.senses[i]]
|
|
94
|
+
|
|
95
|
+
if var_names:
|
|
96
|
+
self.var_names = list(var_names)
|
|
97
|
+
else:
|
|
98
|
+
self.var_names = [f"x{i+1}" for i in range(n)]
|
|
99
|
+
|
|
100
|
+
self.result = None
|
|
101
|
+
|
|
102
|
+
# ------------------------------------------------------------------
|
|
103
|
+
def _build_tableau(self):
|
|
104
|
+
m, n = self.m, self.n
|
|
105
|
+
senses = self.senses
|
|
106
|
+
|
|
107
|
+
# Count extra variables
|
|
108
|
+
n_slack = senses.count("<=")
|
|
109
|
+
n_surplus = senses.count(">=")
|
|
110
|
+
n_artificial= senses.count(">=") + senses.count("=")
|
|
111
|
+
total_vars = n + n_slack + n_surplus + n_artificial
|
|
112
|
+
|
|
113
|
+
T = np.zeros((m + 1, total_vars + 1))
|
|
114
|
+
basis = []
|
|
115
|
+
var_names_ext = self.var_names[:]
|
|
116
|
+
art_indices = []
|
|
117
|
+
|
|
118
|
+
slack_idx = n
|
|
119
|
+
surp_idx = n + n_slack
|
|
120
|
+
art_idx = n + n_slack + n_surplus
|
|
121
|
+
|
|
122
|
+
s_count = a_count = 0
|
|
123
|
+
col_slack = []
|
|
124
|
+
col_art = []
|
|
125
|
+
|
|
126
|
+
for i, sense in enumerate(senses):
|
|
127
|
+
T[i, :n] = self.A_orig[i]
|
|
128
|
+
T[i, -1] = self.b_orig[i]
|
|
129
|
+
|
|
130
|
+
if sense == "<=":
|
|
131
|
+
T[i, slack_idx + s_count] = 1
|
|
132
|
+
var_names_ext.append(f"s{i+1}")
|
|
133
|
+
basis.append(slack_idx + s_count)
|
|
134
|
+
col_slack.append(slack_idx + s_count)
|
|
135
|
+
s_count += 1
|
|
136
|
+
|
|
137
|
+
elif sense == ">=":
|
|
138
|
+
T[i, surp_idx + len(col_art)] = -1 # surplus
|
|
139
|
+
var_names_ext.append(f"e{i+1}") # surplus name
|
|
140
|
+
T[i, art_idx + len(col_art)] = 1 # artificial
|
|
141
|
+
var_names_ext.append(f"A{i+1}")
|
|
142
|
+
art_indices.append(art_idx + len(col_art))
|
|
143
|
+
basis.append(art_idx + len(col_art))
|
|
144
|
+
col_art.append(art_idx + len(col_art))
|
|
145
|
+
s_count += 0 # surplus handled above
|
|
146
|
+
a_count += 1
|
|
147
|
+
|
|
148
|
+
elif sense == "=":
|
|
149
|
+
T[i, art_idx + len(col_art)] = 1
|
|
150
|
+
var_names_ext.append(f"A{i+1}")
|
|
151
|
+
art_indices.append(art_idx + len(col_art))
|
|
152
|
+
basis.append(art_idx + len(col_art))
|
|
153
|
+
col_art.append(art_idx + len(col_art))
|
|
154
|
+
a_count += 1
|
|
155
|
+
|
|
156
|
+
# Reconstruct surplus column tracking properly
|
|
157
|
+
# Redo more carefully
|
|
158
|
+
T, basis, var_names_ext, art_indices = self._rebuild(m, n)
|
|
159
|
+
return T, basis, var_names_ext, art_indices
|
|
160
|
+
|
|
161
|
+
# ------------------------------------------------------------------
|
|
162
|
+
def _rebuild(self, m, n):
|
|
163
|
+
"""Properly build tableau with correct column ordering."""
|
|
164
|
+
senses = self.senses
|
|
165
|
+
# Columns: originals | slacks(<=) | surplus(>=) | artificials(>=,=)
|
|
166
|
+
slack_count = sum(1 for s in senses if s == "<=")
|
|
167
|
+
surplus_count = sum(1 for s in senses if s == ">=")
|
|
168
|
+
art_count = sum(1 for s in senses if s in (">=", "="))
|
|
169
|
+
total = n + slack_count + surplus_count + art_count
|
|
170
|
+
|
|
171
|
+
T = np.zeros((m + 1, total + 1))
|
|
172
|
+
basis= [None] * m
|
|
173
|
+
vnames = self.var_names[:]
|
|
174
|
+
for i in range(slack_count): vnames.append(f"s{i+1}")
|
|
175
|
+
for i in range(surplus_count):vnames.append(f"e{i+1}")
|
|
176
|
+
for i in range(art_count): vnames.append(f"A{i+1}")
|
|
177
|
+
|
|
178
|
+
s_ptr = n # next slack column
|
|
179
|
+
e_ptr = n + slack_count # next surplus column
|
|
180
|
+
a_ptr = n + slack_count + surplus_count # next artificial column
|
|
181
|
+
art_indices = []
|
|
182
|
+
|
|
183
|
+
for i, sense in enumerate(senses):
|
|
184
|
+
T[i, :n] = self.A_orig[i]
|
|
185
|
+
T[i, -1] = self.b_orig[i]
|
|
186
|
+
if sense == "<=":
|
|
187
|
+
T[i, s_ptr] = 1
|
|
188
|
+
basis[i] = s_ptr
|
|
189
|
+
s_ptr += 1
|
|
190
|
+
elif sense == ">=":
|
|
191
|
+
T[i, e_ptr] = -1
|
|
192
|
+
T[i, a_ptr] = 1
|
|
193
|
+
basis[i] = a_ptr
|
|
194
|
+
art_indices.append(a_ptr)
|
|
195
|
+
e_ptr += 1
|
|
196
|
+
a_ptr += 1
|
|
197
|
+
elif sense == "=":
|
|
198
|
+
T[i, a_ptr] = 1
|
|
199
|
+
basis[i] = a_ptr
|
|
200
|
+
art_indices.append(a_ptr)
|
|
201
|
+
a_ptr += 1
|
|
202
|
+
|
|
203
|
+
# --- Objective row ---
|
|
204
|
+
# Minimise originally: c·x + M·Σ(artificial)
|
|
205
|
+
# Internally we maximise: -(c·x) - M·Σ(artificial)
|
|
206
|
+
sign = -1 if self.objective == "min" else 1
|
|
207
|
+
T[-1, :n] = sign * self.c_orig
|
|
208
|
+
for a in art_indices:
|
|
209
|
+
T[-1, a] = -self.M # always penalise artificial (maximising -M·A)
|
|
210
|
+
|
|
211
|
+
# Eliminate artificials from objective row using basis rows
|
|
212
|
+
for i, b in enumerate(basis):
|
|
213
|
+
if b in art_indices:
|
|
214
|
+
T[-1, :] += self.M * T[i, :] # restore reduced costs
|
|
215
|
+
|
|
216
|
+
return T, basis, vnames, art_indices
|
|
217
|
+
|
|
218
|
+
# ------------------------------------------------------------------
|
|
219
|
+
def _pivot(self, T, row, col):
|
|
220
|
+
T = T.copy()
|
|
221
|
+
T[row, :] /= T[row, col]
|
|
222
|
+
for i in range(T.shape[0]):
|
|
223
|
+
if i != row:
|
|
224
|
+
T[i, :] -= T[i, col] * T[row, :]
|
|
225
|
+
return T
|
|
226
|
+
|
|
227
|
+
# ------------------------------------------------------------------
|
|
228
|
+
def solve(self, max_iter: int = 500) -> dict:
|
|
229
|
+
T, basis, vnames, art_indices = self._rebuild(self.m, self.n)
|
|
230
|
+
m = self.m
|
|
231
|
+
self._vnames_ext = vnames
|
|
232
|
+
|
|
233
|
+
for iteration in range(max_iter):
|
|
234
|
+
obj_row = T[-1, :-1]
|
|
235
|
+
if all(obj_row <= 1e-9):
|
|
236
|
+
break
|
|
237
|
+
col = int(np.argmax(obj_row))
|
|
238
|
+
|
|
239
|
+
ratios = []
|
|
240
|
+
for i in range(m):
|
|
241
|
+
if T[i, col] > 1e-9:
|
|
242
|
+
ratios.append((T[i, -1] / T[i, col], i))
|
|
243
|
+
if not ratios:
|
|
244
|
+
self.result = {"status": "Unbounded", "x": None,
|
|
245
|
+
"obj_value": None, "iterations": iteration}
|
|
246
|
+
return self.result
|
|
247
|
+
|
|
248
|
+
ratios.sort()
|
|
249
|
+
row = ratios[0][1]
|
|
250
|
+
basis[row] = col
|
|
251
|
+
T = self._pivot(T, row, col)
|
|
252
|
+
|
|
253
|
+
else:
|
|
254
|
+
self.result = {"status": "Max iterations reached", "x": None,
|
|
255
|
+
"obj_value": None, "iterations": max_iter}
|
|
256
|
+
return self.result
|
|
257
|
+
|
|
258
|
+
# Feasibility: check artificials
|
|
259
|
+
infeasible = False
|
|
260
|
+
for a in art_indices:
|
|
261
|
+
if a in basis:
|
|
262
|
+
idx = basis.index(a)
|
|
263
|
+
if abs(T[idx, -1]) > 1e-6:
|
|
264
|
+
infeasible = True
|
|
265
|
+
break
|
|
266
|
+
|
|
267
|
+
if infeasible:
|
|
268
|
+
self.result = {"status": "Infeasible", "x": None,
|
|
269
|
+
"obj_value": None, "iterations": iteration + 1}
|
|
270
|
+
return self.result
|
|
271
|
+
|
|
272
|
+
n = self.n
|
|
273
|
+
x_full = np.zeros(T.shape[1] - 1)
|
|
274
|
+
for i, b in enumerate(basis):
|
|
275
|
+
x_full[b] = T[i, -1]
|
|
276
|
+
|
|
277
|
+
x_orig = x_full[:n]
|
|
278
|
+
z_int = float(T[-1, -1])
|
|
279
|
+
z = -z_int if self.objective == "min" else z_int
|
|
280
|
+
|
|
281
|
+
self.result = {
|
|
282
|
+
"status" : "Optimal",
|
|
283
|
+
"x" : x_orig,
|
|
284
|
+
"obj_value" : z,
|
|
285
|
+
"iterations": iteration + 1,
|
|
286
|
+
"tableau" : T,
|
|
287
|
+
"basis" : basis,
|
|
288
|
+
}
|
|
289
|
+
return self.result
|
|
290
|
+
|
|
291
|
+
# ------------------------------------------------------------------
|
|
292
|
+
def display(self) -> None:
|
|
293
|
+
if self.result is None:
|
|
294
|
+
self.solve()
|
|
295
|
+
r = self.result
|
|
296
|
+
print("=" * 55)
|
|
297
|
+
print(" Big-M Method Solution")
|
|
298
|
+
print("=" * 55)
|
|
299
|
+
c_str = " + ".join(f"{self.c_orig[i]:g}·{self.var_names[i]}"
|
|
300
|
+
for i in range(self.n))
|
|
301
|
+
print(f" Objective : {self.objective}imise Z = {c_str}")
|
|
302
|
+
print(f" Status : {r['status']}")
|
|
303
|
+
if r.get("x") is not None:
|
|
304
|
+
for i, xi in enumerate(r["x"]):
|
|
305
|
+
print(f" {self.var_names[i]:<10} = {xi:.6g}")
|
|
306
|
+
print(f" Z* = {r['obj_value']:.6g}")
|
|
307
|
+
print(f" Iterations: {r['iterations']}")
|
|
308
|
+
print("=" * 55)
|