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/graphical_method.py
ADDED
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Module: graphical_method.py
|
|
3
|
+
============================
|
|
4
|
+
AIM:
|
|
5
|
+
To solve a Linear Programming Problem (LPP) with exactly TWO decision
|
|
6
|
+
variables using the Graphical Method.
|
|
7
|
+
|
|
8
|
+
Steps implemented:
|
|
9
|
+
1. Plot each constraint as a boundary line.
|
|
10
|
+
2. Identify the feasible region (intersection of all half-planes).
|
|
11
|
+
3. Enumerate all corner (extreme) points of the feasible region.
|
|
12
|
+
4. Evaluate the objective function at each corner point.
|
|
13
|
+
5. Select the corner that optimises (max/min) the objective.
|
|
14
|
+
|
|
15
|
+
Handles:
|
|
16
|
+
- <= , >= , and = constraints
|
|
17
|
+
- Maximisation and Minimisation objectives
|
|
18
|
+
- Unbounded / Infeasible detection
|
|
19
|
+
- Optional plot output (requires matplotlib)
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
import numpy as np
|
|
24
|
+
from itertools import combinations
|
|
25
|
+
from typing import List, Optional, Tuple
|
|
26
|
+
import warnings
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class GraphicalMethod:
|
|
30
|
+
"""
|
|
31
|
+
Solve a 2-variable LP problem graphically.
|
|
32
|
+
|
|
33
|
+
Parameters
|
|
34
|
+
----------
|
|
35
|
+
c : [c1, c2] objective coefficients (Z = c1*x1 + c2*x2).
|
|
36
|
+
constraints: List of (a1, a2, sense, b) where
|
|
37
|
+
a1*x1 + a2*x2 sense b, sense ∈ {'<=', '>=', '='}.
|
|
38
|
+
objective : 'max' or 'min'.
|
|
39
|
+
x1_range : (lo, hi) search range for x1 (default 0 to 1000).
|
|
40
|
+
x2_range : (lo, hi) search range for x2 (default 0 to 1000).
|
|
41
|
+
|
|
42
|
+
Examples
|
|
43
|
+
--------
|
|
44
|
+
>>> gm = GraphicalMethod(
|
|
45
|
+
... c = [3, 5],
|
|
46
|
+
... constraints = [(1, 0, '<=', 4),
|
|
47
|
+
... (0, 2, '<=', 12),
|
|
48
|
+
... (3, 2, '<=', 18)],
|
|
49
|
+
... objective = 'max'
|
|
50
|
+
... )
|
|
51
|
+
>>> result = gm.solve()
|
|
52
|
+
>>> gm.display()
|
|
53
|
+
>>> gm.plot()
|
|
54
|
+
"""
|
|
55
|
+
|
|
56
|
+
def __init__(
|
|
57
|
+
self,
|
|
58
|
+
c: List[float],
|
|
59
|
+
constraints: List[Tuple],
|
|
60
|
+
objective: str = "max",
|
|
61
|
+
x1_range: Tuple[float, float] = (0, 1000),
|
|
62
|
+
x2_range: Tuple[float, float] = (0, 1000),
|
|
63
|
+
):
|
|
64
|
+
if len(c) != 2:
|
|
65
|
+
raise ValueError("GraphicalMethod requires exactly 2 decision variables.")
|
|
66
|
+
self.c = np.array(c, dtype=float)
|
|
67
|
+
self.constraints = constraints # list of (a1, a2, sense, b)
|
|
68
|
+
self.objective = objective.lower()
|
|
69
|
+
self.x1_range = x1_range
|
|
70
|
+
self.x2_range = x2_range
|
|
71
|
+
self.result = None
|
|
72
|
+
|
|
73
|
+
# ------------------------------------------------------------------
|
|
74
|
+
def _satisfies_all(self, x1: float, x2: float, tol: float = 1e-8) -> bool:
|
|
75
|
+
for (a1, a2, sense, b) in self.constraints:
|
|
76
|
+
val = a1 * x1 + a2 * x2
|
|
77
|
+
if sense == "<=":
|
|
78
|
+
if val > b + tol: return False
|
|
79
|
+
elif sense == ">=":
|
|
80
|
+
if val < b - tol: return False
|
|
81
|
+
elif sense == "=":
|
|
82
|
+
if abs(val - b) > tol: return False
|
|
83
|
+
# non-negativity
|
|
84
|
+
if x1 < -1e-8 or x2 < -1e-8:
|
|
85
|
+
return False
|
|
86
|
+
return True
|
|
87
|
+
|
|
88
|
+
# ------------------------------------------------------------------
|
|
89
|
+
def _find_corner_points(self) -> List[np.ndarray]:
|
|
90
|
+
"""
|
|
91
|
+
Enumerate candidate intersection points from pairs of constraint lines
|
|
92
|
+
plus the axes, then filter to feasible ones.
|
|
93
|
+
"""
|
|
94
|
+
# Build list of lines: (a1, a2, b)
|
|
95
|
+
lines = [(a1, a2, b) for (a1, a2, sense, b) in self.constraints]
|
|
96
|
+
# Add axis-boundary lines
|
|
97
|
+
lines += [(1, 0, 0), (0, 1, 0)] # x1=0, x2=0
|
|
98
|
+
|
|
99
|
+
corners = []
|
|
100
|
+
for (l1, l2) in combinations(lines, 2):
|
|
101
|
+
A = np.array([[l1[0], l1[1]], [l2[0], l2[1]]], dtype=float)
|
|
102
|
+
b = np.array([l1[2], l2[2]], dtype=float)
|
|
103
|
+
if abs(np.linalg.det(A)) < 1e-12:
|
|
104
|
+
continue # parallel / coincident
|
|
105
|
+
pt = np.linalg.solve(A, b)
|
|
106
|
+
if (self.x1_range[0] - 1 <= pt[0] <= self.x1_range[1] + 1 and
|
|
107
|
+
self.x2_range[0] - 1 <= pt[1] <= self.x2_range[1] + 1):
|
|
108
|
+
if self._satisfies_all(pt[0], pt[1]):
|
|
109
|
+
corners.append(pt)
|
|
110
|
+
|
|
111
|
+
# de-duplicate
|
|
112
|
+
unique = []
|
|
113
|
+
for pt in corners:
|
|
114
|
+
is_dup = any(np.allclose(pt, u, atol=1e-6) for u in unique)
|
|
115
|
+
if not is_dup:
|
|
116
|
+
unique.append(pt)
|
|
117
|
+
return unique
|
|
118
|
+
|
|
119
|
+
# ------------------------------------------------------------------
|
|
120
|
+
def solve(self) -> dict:
|
|
121
|
+
"""
|
|
122
|
+
Solve and return result dict with keys:
|
|
123
|
+
status : 'Optimal' | 'Infeasible' | 'Unbounded'
|
|
124
|
+
x : [x1*, x2*] or None
|
|
125
|
+
obj_value : Z* or None
|
|
126
|
+
corner_points : list of feasible corner points
|
|
127
|
+
corner_values : Z value at each corner
|
|
128
|
+
"""
|
|
129
|
+
corners = self._find_corner_points()
|
|
130
|
+
if len(corners) == 0:
|
|
131
|
+
self.result = {
|
|
132
|
+
"status" : "Infeasible",
|
|
133
|
+
"x" : None,
|
|
134
|
+
"obj_value" : None,
|
|
135
|
+
"corner_points": [],
|
|
136
|
+
"corner_values": [],
|
|
137
|
+
}
|
|
138
|
+
return self.result
|
|
139
|
+
|
|
140
|
+
values = [float(self.c @ pt) for pt in corners]
|
|
141
|
+
|
|
142
|
+
if self.objective == "max":
|
|
143
|
+
idx = int(np.argmax(values))
|
|
144
|
+
else:
|
|
145
|
+
idx = int(np.argmin(values))
|
|
146
|
+
|
|
147
|
+
self.result = {
|
|
148
|
+
"status" : "Optimal",
|
|
149
|
+
"x" : corners[idx],
|
|
150
|
+
"obj_value" : values[idx],
|
|
151
|
+
"corner_points": corners,
|
|
152
|
+
"corner_values": values,
|
|
153
|
+
}
|
|
154
|
+
return self.result
|
|
155
|
+
|
|
156
|
+
# ------------------------------------------------------------------
|
|
157
|
+
def display(self) -> None:
|
|
158
|
+
"""Print corner-point table and optimal solution."""
|
|
159
|
+
if self.result is None:
|
|
160
|
+
self.solve()
|
|
161
|
+
r = self.result
|
|
162
|
+
print("=" * 50)
|
|
163
|
+
print(" Graphical Method Solution")
|
|
164
|
+
print("=" * 50)
|
|
165
|
+
print(f" Objective : {self.objective}imize Z = "
|
|
166
|
+
f"{self.c[0]:g}·x1 + {self.c[1]:g}·x2")
|
|
167
|
+
print("-" * 50)
|
|
168
|
+
if r["status"] == "Infeasible":
|
|
169
|
+
print(" Status : Infeasible — no feasible region found.")
|
|
170
|
+
else:
|
|
171
|
+
print(f" {'Corner Point':<25} {'Z':>10}")
|
|
172
|
+
print(" " + "-" * 38)
|
|
173
|
+
for pt, z in zip(r["corner_points"], r["corner_values"]):
|
|
174
|
+
marker = " ← optimal" if np.allclose(pt, r["x"], atol=1e-6) else ""
|
|
175
|
+
print(f" ({pt[0]:.4g}, {pt[1]:.4g})".ljust(27)
|
|
176
|
+
+ f"{z:>10.4g}{marker}")
|
|
177
|
+
print("-" * 50)
|
|
178
|
+
print(f" Optimal : x1 = {r['x'][0]:.6g}, x2 = {r['x'][1]:.6g}")
|
|
179
|
+
print(f" Z* = {r['obj_value']:.6g}")
|
|
180
|
+
print("=" * 50)
|
|
181
|
+
|
|
182
|
+
# ------------------------------------------------------------------
|
|
183
|
+
def plot(self, save_path: Optional[str] = None) -> None:
|
|
184
|
+
"""
|
|
185
|
+
Plot the feasible region, constraints, and optimal point.
|
|
186
|
+
|
|
187
|
+
Parameters
|
|
188
|
+
----------
|
|
189
|
+
save_path : If given, save the figure to this file path.
|
|
190
|
+
"""
|
|
191
|
+
try:
|
|
192
|
+
import matplotlib.pyplot as plt
|
|
193
|
+
import matplotlib.patches as mpatches
|
|
194
|
+
except ImportError:
|
|
195
|
+
warnings.warn("matplotlib is required for plotting. "
|
|
196
|
+
"Install via: pip install matplotlib")
|
|
197
|
+
return
|
|
198
|
+
|
|
199
|
+
if self.result is None:
|
|
200
|
+
self.solve()
|
|
201
|
+
|
|
202
|
+
x1_max = min(self.x1_range[1],
|
|
203
|
+
max(b for (_, _, _, b) in self.constraints) * 1.5 + 5)
|
|
204
|
+
x2_max = min(self.x2_range[1],
|
|
205
|
+
max(b for (_, _, _, b) in self.constraints) * 1.5 + 5)
|
|
206
|
+
x1_max = max(x1_max, 1)
|
|
207
|
+
x2_max = max(x2_max, 1)
|
|
208
|
+
|
|
209
|
+
x1v = np.linspace(0, x1_max, 500)
|
|
210
|
+
fig, ax = plt.subplots(figsize=(7, 6))
|
|
211
|
+
colors = plt.cm.tab10.colors
|
|
212
|
+
|
|
213
|
+
for i, (a1, a2, sense, b) in enumerate(self.constraints):
|
|
214
|
+
label = (f"{a1:g}x₁ + {a2:g}x₂ {sense} {b:g}")
|
|
215
|
+
if abs(a2) > 1e-12:
|
|
216
|
+
x2v = (b - a1 * x1v) / a2
|
|
217
|
+
ax.plot(x1v, x2v, color=colors[i % 10], label=label, lw=1.8)
|
|
218
|
+
else:
|
|
219
|
+
xv = b / a1 if abs(a1) > 1e-12 else 0
|
|
220
|
+
ax.axvline(xv, color=colors[i % 10], label=label, lw=1.8)
|
|
221
|
+
|
|
222
|
+
# shade feasible region using a fine grid
|
|
223
|
+
X1, X2 = np.meshgrid(np.linspace(0, x1_max, 300),
|
|
224
|
+
np.linspace(0, x2_max, 300))
|
|
225
|
+
mask = np.ones_like(X1, dtype=bool)
|
|
226
|
+
for (a1, a2, sense, b) in self.constraints:
|
|
227
|
+
val = a1 * X1 + a2 * X2
|
|
228
|
+
if sense == "<=": mask &= val <= b + 1e-8
|
|
229
|
+
elif sense == ">=": mask &= val >= b - 1e-8
|
|
230
|
+
elif sense == "=": mask &= np.abs(val - b) <= 1e-6
|
|
231
|
+
mask &= (X1 >= -1e-8) & (X2 >= -1e-8)
|
|
232
|
+
ax.contourf(X1, X2, mask.astype(float), levels=[0.5, 1.5],
|
|
233
|
+
colors=["#c8e6c9"], alpha=0.6)
|
|
234
|
+
|
|
235
|
+
# corner points
|
|
236
|
+
for pt in self.result.get("corner_points", []):
|
|
237
|
+
ax.plot(pt[0], pt[1], "bo", ms=6)
|
|
238
|
+
|
|
239
|
+
# optimal
|
|
240
|
+
if self.result["x"] is not None:
|
|
241
|
+
opt = self.result["x"]
|
|
242
|
+
ax.plot(opt[0], opt[1], "r*", ms=14, zorder=5,
|
|
243
|
+
label=f"Optimal ({opt[0]:.3g}, {opt[1]:.3g}) Z={self.result['obj_value']:.4g}")
|
|
244
|
+
|
|
245
|
+
ax.set_xlim(0, x1_max)
|
|
246
|
+
ax.set_ylim(0, x2_max)
|
|
247
|
+
ax.set_xlabel("x₁", fontsize=12)
|
|
248
|
+
ax.set_ylabel("x₂", fontsize=12)
|
|
249
|
+
ax.set_title("Graphical Method — Feasible Region", fontsize=13)
|
|
250
|
+
ax.legend(fontsize=9, loc="upper right")
|
|
251
|
+
ax.grid(True, alpha=0.3)
|
|
252
|
+
plt.tight_layout()
|
|
253
|
+
if save_path:
|
|
254
|
+
plt.savefig(save_path, dpi=150)
|
|
255
|
+
plt.show()
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Module: linear_programming.py
|
|
3
|
+
==============================
|
|
4
|
+
AIM:
|
|
5
|
+
To formulate and solve a Linear Programming Problem (LPP) in standard form.
|
|
6
|
+
Converts a general LP (with <=, >=, = constraints) into standard form by
|
|
7
|
+
introducing slack, surplus, and artificial variables, then solves using
|
|
8
|
+
scipy's linprog (revised simplex / HiGHS solver).
|
|
9
|
+
|
|
10
|
+
Supports:
|
|
11
|
+
- Maximization and Minimization objectives
|
|
12
|
+
- Mixed constraints (<=, >=, =)
|
|
13
|
+
- Bounded variables
|
|
14
|
+
- Unbounded / infeasible detection
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
import numpy as np
|
|
19
|
+
from scipy.optimize import linprog
|
|
20
|
+
from typing import List, Optional, Tuple
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class LinearProgram:
|
|
24
|
+
"""
|
|
25
|
+
Formulate and solve a Linear Programming Problem.
|
|
26
|
+
|
|
27
|
+
Parameters
|
|
28
|
+
----------
|
|
29
|
+
c : Coefficients of the objective function.
|
|
30
|
+
A_ub : 2-D array of <= constraint coefficients.
|
|
31
|
+
b_ub : RHS of <= constraints.
|
|
32
|
+
A_eq : 2-D array of = constraint coefficients.
|
|
33
|
+
b_eq : RHS of = constraints.
|
|
34
|
+
bounds : List of (lower, upper) bounds per variable.
|
|
35
|
+
Default is (0, None) i.e. non-negative.
|
|
36
|
+
objective : 'min' (default) or 'max'.
|
|
37
|
+
|
|
38
|
+
Examples
|
|
39
|
+
--------
|
|
40
|
+
>>> lp = LinearProgram(
|
|
41
|
+
... c = [-3, -5], # maximize 3x1 + 5x2
|
|
42
|
+
... A_ub = [[1, 0], [0, 2], [3, 2]],
|
|
43
|
+
... b_ub = [4, 12, 18],
|
|
44
|
+
... objective = 'max'
|
|
45
|
+
... )
|
|
46
|
+
>>> result = lp.solve()
|
|
47
|
+
>>> lp.display()
|
|
48
|
+
"""
|
|
49
|
+
|
|
50
|
+
def __init__(
|
|
51
|
+
self,
|
|
52
|
+
c: List[float],
|
|
53
|
+
A_ub: Optional[List[List[float]]] = None,
|
|
54
|
+
b_ub: Optional[List[float]] = None,
|
|
55
|
+
A_eq: Optional[List[List[float]]] = None,
|
|
56
|
+
b_eq: Optional[List[float]] = None,
|
|
57
|
+
bounds: Optional[List[Tuple]] = None,
|
|
58
|
+
objective: str = "min",
|
|
59
|
+
):
|
|
60
|
+
self.objective = objective.lower()
|
|
61
|
+
if self.objective not in ("min", "max"):
|
|
62
|
+
raise ValueError("objective must be 'min' or 'max'.")
|
|
63
|
+
|
|
64
|
+
self.c_orig = np.array(c, dtype=float)
|
|
65
|
+
# scipy always minimises; flip sign for maximisation
|
|
66
|
+
self.c = -self.c_orig if self.objective == "max" else self.c_orig.copy()
|
|
67
|
+
|
|
68
|
+
self.A_ub = np.array(A_ub, dtype=float) if A_ub is not None else None
|
|
69
|
+
self.b_ub = np.array(b_ub, dtype=float) if b_ub is not None else None
|
|
70
|
+
self.A_eq = np.array(A_eq, dtype=float) if A_eq is not None else None
|
|
71
|
+
self.b_eq = np.array(b_eq, dtype=float) if b_eq is not None else None
|
|
72
|
+
|
|
73
|
+
n = len(c)
|
|
74
|
+
self.bounds = bounds if bounds is not None else [(0, None)] * n
|
|
75
|
+
self.result = None
|
|
76
|
+
|
|
77
|
+
# ------------------------------------------------------------------
|
|
78
|
+
def solve(self) -> dict:
|
|
79
|
+
"""
|
|
80
|
+
Solve the LP and return a result dictionary.
|
|
81
|
+
|
|
82
|
+
Returns
|
|
83
|
+
-------
|
|
84
|
+
dict with keys:
|
|
85
|
+
status : 'Optimal' | 'Infeasible' | 'Unbounded' | 'Error'
|
|
86
|
+
x : Optimal variable values (np.ndarray) or None
|
|
87
|
+
obj_value: Optimal objective value or None
|
|
88
|
+
message : Solver message
|
|
89
|
+
"""
|
|
90
|
+
res = linprog(
|
|
91
|
+
self.c,
|
|
92
|
+
A_ub=self.A_ub,
|
|
93
|
+
b_ub=self.b_ub,
|
|
94
|
+
A_eq=self.A_eq,
|
|
95
|
+
b_eq=self.b_eq,
|
|
96
|
+
bounds=self.bounds,
|
|
97
|
+
method="highs",
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
if res.status == 0:
|
|
101
|
+
x = res.x
|
|
102
|
+
obj = float(np.dot(self.c_orig, x))
|
|
103
|
+
self.result = {
|
|
104
|
+
"status" : "Optimal",
|
|
105
|
+
"x" : x,
|
|
106
|
+
"obj_value": obj,
|
|
107
|
+
"message" : res.message,
|
|
108
|
+
}
|
|
109
|
+
elif res.status == 2:
|
|
110
|
+
self.result = {"status": "Infeasible", "x": None, "obj_value": None,
|
|
111
|
+
"message": res.message}
|
|
112
|
+
elif res.status == 3:
|
|
113
|
+
self.result = {"status": "Unbounded", "x": None, "obj_value": None,
|
|
114
|
+
"message": res.message}
|
|
115
|
+
else:
|
|
116
|
+
self.result = {"status": "Error", "x": None, "obj_value": None,
|
|
117
|
+
"message": res.message}
|
|
118
|
+
|
|
119
|
+
return self.result
|
|
120
|
+
|
|
121
|
+
# ------------------------------------------------------------------
|
|
122
|
+
def display(self) -> None:
|
|
123
|
+
"""Pretty-print the problem formulation and solution."""
|
|
124
|
+
n = len(self.c_orig)
|
|
125
|
+
obj_str = " + ".join(f"{self.c_orig[i]:g}·x{i+1}" for i in range(n))
|
|
126
|
+
print("=" * 55)
|
|
127
|
+
print(f" Linear Programming Problem ({self.objective.upper()}IMIZE)")
|
|
128
|
+
print("=" * 55)
|
|
129
|
+
print(f" Objective : {self.objective}imize Z = {obj_str}")
|
|
130
|
+
print(" Subject to:")
|
|
131
|
+
if self.A_ub is not None:
|
|
132
|
+
for row, rhs in zip(self.A_ub, self.b_ub):
|
|
133
|
+
lhs = " + ".join(f"{row[i]:g}·x{i+1}" for i in range(n))
|
|
134
|
+
print(f" {lhs} <= {rhs:g}")
|
|
135
|
+
if self.A_eq is not None:
|
|
136
|
+
for row, rhs in zip(self.A_eq, self.b_eq):
|
|
137
|
+
lhs = " + ".join(f"{row[i]:g}·x{i+1}" for i in range(n))
|
|
138
|
+
print(f" {lhs} = {rhs:g}")
|
|
139
|
+
for i, b in enumerate(self.bounds):
|
|
140
|
+
lo = b[0] if b[0] is not None else "-∞"
|
|
141
|
+
hi = b[1] if b[1] is not None else "+∞"
|
|
142
|
+
print(f" x{i+1} ∈ [{lo}, {hi}]")
|
|
143
|
+
print("-" * 55)
|
|
144
|
+
if self.result is None:
|
|
145
|
+
print(" [Not yet solved — call .solve() first]")
|
|
146
|
+
else:
|
|
147
|
+
r = self.result
|
|
148
|
+
print(f" Status : {r['status']}")
|
|
149
|
+
if r["x"] is not None:
|
|
150
|
+
for i, xi in enumerate(r["x"]):
|
|
151
|
+
print(f" x{i+1} = {xi:.6g}")
|
|
152
|
+
print(f" Obj value : {r['obj_value']:.6g}")
|
|
153
|
+
print(f" Message : {r['message']}")
|
|
154
|
+
print("=" * 55)
|
|
@@ -0,0 +1,284 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Module: project_management.py
|
|
3
|
+
==============================
|
|
4
|
+
AIM:
|
|
5
|
+
To analyse a project network using PERT (Programme Evaluation and
|
|
6
|
+
Review Technique) and CPM (Critical Path Method).
|
|
7
|
+
|
|
8
|
+
CPM (deterministic):
|
|
9
|
+
- Each activity has a single duration estimate.
|
|
10
|
+
- Computes Earliest Start (ES), Earliest Finish (EF),
|
|
11
|
+
Latest Start (LS), Latest Finish (LF), and Total Float (TF).
|
|
12
|
+
- Identifies the Critical Path (activities with TF = 0).
|
|
13
|
+
|
|
14
|
+
PERT (probabilistic):
|
|
15
|
+
- Each activity has three estimates: optimistic (a), most likely (m),
|
|
16
|
+
pessimistic (b).
|
|
17
|
+
- Expected duration : te = (a + 4m + b) / 6
|
|
18
|
+
- Variance : σ² = ((b - a) / 6)²
|
|
19
|
+
- Computes project completion probability for a target duration.
|
|
20
|
+
- Uses Normal distribution approximation.
|
|
21
|
+
|
|
22
|
+
Handles:
|
|
23
|
+
- Directed Acyclic Graphs (DAG) with any topology.
|
|
24
|
+
- Multiple start / end nodes.
|
|
25
|
+
- Cycles detection (raises an error).
|
|
26
|
+
- Both AON (Activity-on-Node) and AOA (Activity-on-Arrow) conventions.
|
|
27
|
+
- Isolated nodes / dummy activities.
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
from __future__ import annotations
|
|
31
|
+
import numpy as np
|
|
32
|
+
from typing import List, Dict, Tuple, Optional, Union
|
|
33
|
+
from collections import deque
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class PERTCPMNetwork:
|
|
37
|
+
"""
|
|
38
|
+
PERT / CPM Project Network Analyser.
|
|
39
|
+
|
|
40
|
+
Parameters
|
|
41
|
+
----------
|
|
42
|
+
activities : List of activity dicts. Each dict must contain:
|
|
43
|
+
'name' : str (activity label)
|
|
44
|
+
'depends': list of activity names this depends on
|
|
45
|
+
(empty list for start activities)
|
|
46
|
+
For CPM, additionally:
|
|
47
|
+
'duration': float
|
|
48
|
+
|
|
49
|
+
For PERT, additionally (instead of duration):
|
|
50
|
+
'optimistic' : float (a)
|
|
51
|
+
'most_likely' : float (m)
|
|
52
|
+
'pessimistic' : float (b)
|
|
53
|
+
|
|
54
|
+
You may also mix CPM and PERT: if only 'duration' is
|
|
55
|
+
provided it is treated as deterministic (variance = 0).
|
|
56
|
+
|
|
57
|
+
Examples
|
|
58
|
+
--------
|
|
59
|
+
>>> # CPM Example
|
|
60
|
+
>>> activities = [
|
|
61
|
+
... {'name': 'A', 'depends': [], 'duration': 4},
|
|
62
|
+
... {'name': 'B', 'depends': [], 'duration': 5},
|
|
63
|
+
... {'name': 'C', 'depends': ['A'], 'duration': 3},
|
|
64
|
+
... {'name': 'D', 'depends': ['B'], 'duration': 4},
|
|
65
|
+
... {'name': 'E', 'depends': ['C', 'D'],'duration': 6},
|
|
66
|
+
... ]
|
|
67
|
+
>>> net = PERTCPMNetwork(activities)
|
|
68
|
+
>>> result = net.solve()
|
|
69
|
+
>>> net.display()
|
|
70
|
+
|
|
71
|
+
>>> # PERT Example
|
|
72
|
+
>>> activities = [
|
|
73
|
+
... {'name': 'A', 'depends': [], 'optimistic': 2, 'most_likely': 4, 'pessimistic': 6},
|
|
74
|
+
... {'name': 'B', 'depends': ['A'], 'optimistic': 3, 'most_likely': 5, 'pessimistic': 7},
|
|
75
|
+
... ]
|
|
76
|
+
>>> net2 = PERTCPMNetwork(activities)
|
|
77
|
+
>>> net2.solve()
|
|
78
|
+
>>> print(net2.completion_probability(target_duration=12))
|
|
79
|
+
"""
|
|
80
|
+
|
|
81
|
+
def __init__(self, activities: List[Dict]):
|
|
82
|
+
self.activities_raw = activities
|
|
83
|
+
self._parse_activities()
|
|
84
|
+
self.result = None
|
|
85
|
+
|
|
86
|
+
# ------------------------------------------------------------------
|
|
87
|
+
def _parse_activities(self):
|
|
88
|
+
"""Parse activity list into internal representation."""
|
|
89
|
+
self.act = {} # name → dict with duration, variance, depends
|
|
90
|
+
for item in self.activities_raw:
|
|
91
|
+
name = item['name']
|
|
92
|
+
depends = item.get('depends', [])
|
|
93
|
+
duration = item.get('duration', None)
|
|
94
|
+
a = item.get('optimistic', None)
|
|
95
|
+
m = item.get('most_likely', None)
|
|
96
|
+
b = item.get('pessimistic', None)
|
|
97
|
+
|
|
98
|
+
if a is not None and m is not None and b is not None:
|
|
99
|
+
te = (a + 4 * m + b) / 6.0
|
|
100
|
+
variance = ((b - a) / 6.0) ** 2
|
|
101
|
+
elif duration is not None:
|
|
102
|
+
te = float(duration)
|
|
103
|
+
variance = 0.0
|
|
104
|
+
else:
|
|
105
|
+
raise ValueError(
|
|
106
|
+
f"Activity '{name}' must have 'duration' or "
|
|
107
|
+
"('optimistic', 'most_likely', 'pessimistic')."
|
|
108
|
+
)
|
|
109
|
+
|
|
110
|
+
self.act[name] = {
|
|
111
|
+
'te' : te,
|
|
112
|
+
'variance': variance,
|
|
113
|
+
'depends' : depends,
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
# ------------------------------------------------------------------
|
|
117
|
+
def _topological_sort(self) -> List[str]:
|
|
118
|
+
"""Return activities in topological order (Kahn's algorithm)."""
|
|
119
|
+
in_degree = {n: 0 for n in self.act}
|
|
120
|
+
adj = {n: [] for n in self.act}
|
|
121
|
+
for name, data in self.act.items():
|
|
122
|
+
for dep in data['depends']:
|
|
123
|
+
if dep not in self.act:
|
|
124
|
+
raise ValueError(f"Dependency '{dep}' not found in activities.")
|
|
125
|
+
adj[dep].append(name)
|
|
126
|
+
in_degree[name] += 1
|
|
127
|
+
|
|
128
|
+
queue = deque(n for n in self.act if in_degree[n] == 0)
|
|
129
|
+
order = []
|
|
130
|
+
while queue:
|
|
131
|
+
node = queue.popleft()
|
|
132
|
+
order.append(node)
|
|
133
|
+
for nxt in adj[node]:
|
|
134
|
+
in_degree[nxt] -= 1
|
|
135
|
+
if in_degree[nxt] == 0:
|
|
136
|
+
queue.append(nxt)
|
|
137
|
+
|
|
138
|
+
if len(order) != len(self.act):
|
|
139
|
+
raise ValueError("Cycle detected in the activity network.")
|
|
140
|
+
return order
|
|
141
|
+
|
|
142
|
+
# ------------------------------------------------------------------
|
|
143
|
+
def solve(self) -> dict:
|
|
144
|
+
"""
|
|
145
|
+
Run CPM / PERT analysis.
|
|
146
|
+
|
|
147
|
+
Returns
|
|
148
|
+
-------
|
|
149
|
+
dict with keys:
|
|
150
|
+
activities : dict mapping name → schedule info
|
|
151
|
+
critical_path: list of activity names on critical path
|
|
152
|
+
project_duration : expected project duration
|
|
153
|
+
project_variance : total variance along critical path
|
|
154
|
+
"""
|
|
155
|
+
order = self._topological_sort()
|
|
156
|
+
|
|
157
|
+
# --- Forward pass: ES and EF ---
|
|
158
|
+
ES: Dict[str, float] = {}
|
|
159
|
+
EF: Dict[str, float] = {}
|
|
160
|
+
for name in order:
|
|
161
|
+
deps = self.act[name]['depends']
|
|
162
|
+
es = max((EF[d] for d in deps), default=0.0)
|
|
163
|
+
ES[name] = es
|
|
164
|
+
EF[name] = es + self.act[name]['te']
|
|
165
|
+
|
|
166
|
+
project_duration = max(EF.values())
|
|
167
|
+
|
|
168
|
+
# --- Backward pass: LF and LS ---
|
|
169
|
+
# Identify terminal activities
|
|
170
|
+
all_deps = set(d for data in self.act.values() for d in data['depends'])
|
|
171
|
+
terminals = [n for n in self.act if n not in all_deps]
|
|
172
|
+
|
|
173
|
+
LF: Dict[str, float] = {}
|
|
174
|
+
LS: Dict[str, float] = {}
|
|
175
|
+
for name in order:
|
|
176
|
+
LF[name] = project_duration # initialise
|
|
177
|
+
|
|
178
|
+
for name in reversed(order):
|
|
179
|
+
# LF = min of (LS of all successors)
|
|
180
|
+
successors = [n for n in self.act
|
|
181
|
+
if name in self.act[n]['depends']]
|
|
182
|
+
if successors:
|
|
183
|
+
LF[name] = min(LS[s] for s in successors)
|
|
184
|
+
LS[name] = LF[name] - self.act[name]['te']
|
|
185
|
+
|
|
186
|
+
# --- Float and Critical Path ---
|
|
187
|
+
TF: Dict[str, float] = {}
|
|
188
|
+
FF: Dict[str, float] = {}
|
|
189
|
+
for name in order:
|
|
190
|
+
TF[name] = round(LF[name] - EF[name], 8)
|
|
191
|
+
successors = [n for n in self.act
|
|
192
|
+
if name in self.act[n]['depends']]
|
|
193
|
+
if successors:
|
|
194
|
+
FF[name] = round(min(ES[s] for s in successors) - EF[name], 8)
|
|
195
|
+
else:
|
|
196
|
+
FF[name] = 0.0
|
|
197
|
+
|
|
198
|
+
critical_path = [n for n in order if abs(TF[n]) < 1e-6]
|
|
199
|
+
|
|
200
|
+
# --- Project variance (along critical path) ---
|
|
201
|
+
project_variance = sum(self.act[n]['variance'] for n in critical_path)
|
|
202
|
+
|
|
203
|
+
# Build per-activity result
|
|
204
|
+
act_results = {}
|
|
205
|
+
for name in order:
|
|
206
|
+
act_results[name] = {
|
|
207
|
+
'te' : self.act[name]['te'],
|
|
208
|
+
'variance' : self.act[name]['variance'],
|
|
209
|
+
'ES' : round(ES[name], 4),
|
|
210
|
+
'EF' : round(EF[name], 4),
|
|
211
|
+
'LS' : round(LS[name], 4),
|
|
212
|
+
'LF' : round(LF[name], 4),
|
|
213
|
+
'TF' : round(TF[name], 4),
|
|
214
|
+
'FF' : round(FF[name], 4),
|
|
215
|
+
'is_critical' : abs(TF[name]) < 1e-6,
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
self.result = {
|
|
219
|
+
'activities' : act_results,
|
|
220
|
+
'critical_path' : critical_path,
|
|
221
|
+
'project_duration' : project_duration,
|
|
222
|
+
'project_variance' : project_variance,
|
|
223
|
+
'order' : order,
|
|
224
|
+
}
|
|
225
|
+
return self.result
|
|
226
|
+
|
|
227
|
+
# ------------------------------------------------------------------
|
|
228
|
+
def completion_probability(self, target_duration: float) -> float:
|
|
229
|
+
"""
|
|
230
|
+
Calculate the probability of completing the project within
|
|
231
|
+
target_duration using the normal approximation (PERT).
|
|
232
|
+
|
|
233
|
+
Parameters
|
|
234
|
+
----------
|
|
235
|
+
target_duration : Desired completion time.
|
|
236
|
+
|
|
237
|
+
Returns
|
|
238
|
+
-------
|
|
239
|
+
Probability (0 to 1).
|
|
240
|
+
"""
|
|
241
|
+
from scipy.stats import norm
|
|
242
|
+
if self.result is None:
|
|
243
|
+
self.solve()
|
|
244
|
+
mu = self.result['project_duration']
|
|
245
|
+
sigma2= self.result['project_variance']
|
|
246
|
+
if sigma2 <= 0:
|
|
247
|
+
return 1.0 if target_duration >= mu else 0.0
|
|
248
|
+
z = (target_duration - mu) / np.sqrt(sigma2)
|
|
249
|
+
return float(norm.cdf(z))
|
|
250
|
+
|
|
251
|
+
# ------------------------------------------------------------------
|
|
252
|
+
def display(self, show_probability: Optional[float] = None) -> None:
|
|
253
|
+
"""
|
|
254
|
+
Display the full schedule table and critical path.
|
|
255
|
+
|
|
256
|
+
Parameters
|
|
257
|
+
----------
|
|
258
|
+
show_probability : If given, also print P(T <= this value).
|
|
259
|
+
"""
|
|
260
|
+
if self.result is None:
|
|
261
|
+
self.solve()
|
|
262
|
+
r = self.result
|
|
263
|
+
print("=" * 85)
|
|
264
|
+
print(" PERT / CPM Network Analysis")
|
|
265
|
+
print("=" * 85)
|
|
266
|
+
print(f" {'Activity':<12} {'te':>6} {'σ²':>8} "
|
|
267
|
+
f"{'ES':>7} {'EF':>7} {'LS':>7} {'LF':>7} "
|
|
268
|
+
f"{'TF':>7} {'FF':>7} Critical")
|
|
269
|
+
print(" " + "-" * 80)
|
|
270
|
+
for name in r['order']:
|
|
271
|
+
a = r['activities'][name]
|
|
272
|
+
crit = " ← YES" if a['is_critical'] else ""
|
|
273
|
+
print(f" {name:<12} {a['te']:>6.2f} {a['variance']:>8.4f} "
|
|
274
|
+
f"{a['ES']:>7.2f} {a['EF']:>7.2f} {a['LS']:>7.2f} "
|
|
275
|
+
f"{a['LF']:>7.2f} {a['TF']:>7.2f} {a['FF']:>7.2f}{crit}")
|
|
276
|
+
print("=" * 85)
|
|
277
|
+
print(f" Critical Path : {' → '.join(r['critical_path'])}")
|
|
278
|
+
print(f" Project Duration : {r['project_duration']:.4f}")
|
|
279
|
+
print(f" Project Variance : {r['project_variance']:.4f}")
|
|
280
|
+
print(f" Project Std Dev : {np.sqrt(r['project_variance']):.4f}")
|
|
281
|
+
if show_probability is not None:
|
|
282
|
+
prob = self.completion_probability(show_probability)
|
|
283
|
+
print(f" P(T ≤ {show_probability}) = {prob:.4f} ({prob*100:.2f}%)")
|
|
284
|
+
print("=" * 85)
|