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/transportation.py ADDED
@@ -0,0 +1,527 @@
1
+ """
2
+ Module: transportation.py
3
+ ==========================
4
+ AIM:
5
+ To solve Transportation Problems using four classical methods:
6
+
7
+ 1. north_west_corner : North-West Corner Method (initial BFS)
8
+ - Allocates supply/demand starting from the top-left cell,
9
+ moving right or down as each row/column is exhausted.
10
+
11
+ 2. least_cost_method : Least Cost / Matrix Minima Method (initial BFS)
12
+ - Always allocates to the cell with the minimum transportation cost.
13
+
14
+ 3. vogel_approximation: Vogel's Approximation Method / VAM (initial BFS)
15
+ - Computes row and column penalties; allocates to minimum-cost
16
+ cell in the highest-penalty row/column.
17
+
18
+ 4. modi_method : MODI (Modified Distribution) Method
19
+ - Tests and improves any BFS for optimality using u-v potentials.
20
+ - Returns the optimal solution and total cost.
21
+
22
+ All four functions handle:
23
+ - Balanced and unbalanced problems (auto-balance by adding
24
+ a dummy row or column with zero cost).
25
+ - Degenerate cases (fewer than m+n-1 allocations).
26
+ - Correct handling of row/column exhaustion.
27
+ """
28
+
29
+ from __future__ import annotations
30
+ import numpy as np
31
+ from typing import List, Tuple, Optional
32
+ from copy import deepcopy
33
+
34
+
35
+ # ──────────────────────────────────────────────────────────────────────
36
+ # Helper utilities
37
+ # ──────────────────────────────────────────────────────────────────────
38
+
39
+ def _balance(cost: np.ndarray, supply: np.ndarray,
40
+ demand: np.ndarray) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
41
+ """Add dummy row / column to balance if necessary."""
42
+ cost = cost.astype(float)
43
+ supply = supply.astype(float)
44
+ demand = demand.astype(float)
45
+ ts, td = supply.sum(), demand.sum()
46
+ if ts < td:
47
+ dummy_col = np.zeros((cost.shape[0], 1))
48
+ cost = np.hstack([cost, dummy_col])
49
+ supply = np.append(supply, td - ts)
50
+ elif td < ts:
51
+ dummy_row = np.zeros((1, cost.shape[1]))
52
+ cost = np.vstack([cost, dummy_row])
53
+ demand = np.append(demand, ts - td)
54
+ return cost, supply, demand
55
+
56
+
57
+ def _total_cost(alloc: np.ndarray, cost: np.ndarray) -> float:
58
+ return float((alloc * cost).sum())
59
+
60
+
61
+ def _display_solution(alloc: np.ndarray, cost: np.ndarray,
62
+ method_name: str) -> None:
63
+ m, n = alloc.shape
64
+ print("=" * 60)
65
+ print(f" {method_name}")
66
+ print("=" * 60)
67
+ print(" Allocation matrix:")
68
+ header = " " + "".join(f" D{j+1} " for j in range(n))
69
+ print(header)
70
+ for i in range(m):
71
+ row = f" S{i+1} "
72
+ for j in range(n):
73
+ a = int(alloc[i, j]) if alloc[i, j] == int(alloc[i, j]) else alloc[i, j]
74
+ row += f" {a:<4} "
75
+ print(row)
76
+ print(f"\n Total Transportation Cost = {_total_cost(alloc, cost):.4g}")
77
+ print("=" * 60)
78
+
79
+
80
+ # ──────────────────────────────────────────────────────────────────────
81
+ # 1. North-West Corner Method
82
+ # ──────────────────────────────────────────────────────────────────────
83
+
84
+ def north_west_corner(
85
+ cost: List[List[float]],
86
+ supply: List[float],
87
+ demand: List[float],
88
+ display: bool = True,
89
+ ) -> dict:
90
+ """
91
+ AIM: Find an initial Basic Feasible Solution using the North-West
92
+ Corner Method. Allocations are made starting from cell (0,0)
93
+ and moving right or down as supply/demand is satisfied.
94
+
95
+ Parameters
96
+ ----------
97
+ cost : m×n cost matrix.
98
+ supply : Supply vector (length m).
99
+ demand : Demand vector (length n).
100
+ display : Print the allocation table (default True).
101
+
102
+ Returns
103
+ -------
104
+ dict with keys:
105
+ allocation : m×n allocation matrix (np.ndarray)
106
+ total_cost : Total transportation cost
107
+ cost : (possibly expanded) cost matrix used
108
+ supply : (possibly expanded) supply
109
+ demand : (possibly expanded) demand
110
+ """
111
+ cost, supply, demand = _balance(
112
+ np.array(cost, dtype=float),
113
+ np.array(supply, dtype=float),
114
+ np.array(demand, dtype=float),
115
+ )
116
+ m, n = cost.shape
117
+ supply = supply.copy()
118
+ demand = demand.copy()
119
+ alloc = np.zeros((m, n))
120
+
121
+ i, j = 0, 0
122
+ while i < m and j < n:
123
+ qty = min(supply[i], demand[j])
124
+ alloc[i, j] = qty
125
+ supply[i] -= qty
126
+ demand[j] -= qty
127
+ if supply[i] == 0 and demand[j] == 0:
128
+ i += 1
129
+ if i < m: j += 1 # small nudge to avoid same-row-col step
130
+ elif supply[i] == 0:
131
+ i += 1
132
+ else:
133
+ j += 1
134
+
135
+ result = {
136
+ "allocation": alloc,
137
+ "total_cost": _total_cost(alloc, cost),
138
+ "cost" : cost,
139
+ "supply" : supply,
140
+ "demand" : demand,
141
+ }
142
+ if display:
143
+ _display_solution(alloc, cost, "North-West Corner Method (Initial BFS)")
144
+ return result
145
+
146
+
147
+ # ──────────────────────────────────────────────────────────────────────
148
+ # 2. Least Cost Method
149
+ # ──────────────────────────────────────────────────────────────────────
150
+
151
+ def least_cost_method(
152
+ cost: List[List[float]],
153
+ supply: List[float],
154
+ demand: List[float],
155
+ display: bool = True,
156
+ ) -> dict:
157
+ """
158
+ AIM: Find an initial Basic Feasible Solution using the Least Cost
159
+ (Matrix Minima) Method. At each step allocate as much as
160
+ possible to the cell with the globally lowest cost.
161
+
162
+ Parameters
163
+ ----------
164
+ cost : m×n cost matrix.
165
+ supply : Supply vector.
166
+ demand : Demand vector.
167
+ display : Print allocation table.
168
+
169
+ Returns
170
+ -------
171
+ dict — same structure as north_west_corner.
172
+ """
173
+ cost_orig, supply, demand = _balance(
174
+ np.array(cost, dtype=float),
175
+ np.array(supply, dtype=float),
176
+ np.array(demand, dtype=float),
177
+ )
178
+ m, n = cost_orig.shape
179
+ supply = supply.copy()
180
+ demand = demand.copy()
181
+ alloc = np.zeros((m, n))
182
+ cost_w = cost_orig.copy()
183
+
184
+ INF = np.inf
185
+ finished_rows = set()
186
+ finished_cols = set()
187
+
188
+ while True:
189
+ # Mask exhausted rows/cols
190
+ masked = cost_w.copy()
191
+ masked[list(finished_rows), :] = INF
192
+ masked[:, list(finished_cols)] = INF
193
+
194
+ if masked.min() == INF:
195
+ break
196
+
197
+ idx = np.unravel_index(np.argmin(masked), masked.shape)
198
+ i, j = int(idx[0]), int(idx[1])
199
+ qty = min(supply[i], demand[j])
200
+ alloc[i, j] += qty
201
+ supply[i] -= qty
202
+ demand[j] -= qty
203
+
204
+ if supply[i] <= 1e-9:
205
+ finished_rows.add(i)
206
+ if demand[j] <= 1e-9:
207
+ finished_cols.add(j)
208
+
209
+ result = {
210
+ "allocation": alloc,
211
+ "total_cost": _total_cost(alloc, cost_orig),
212
+ "cost" : cost_orig,
213
+ "supply" : supply,
214
+ "demand" : demand,
215
+ }
216
+ if display:
217
+ _display_solution(alloc, cost_orig, "Least Cost Method (Initial BFS)")
218
+ return result
219
+
220
+
221
+ # ──────────────────────────────────────────────────────────────────────
222
+ # 3. Vogel's Approximation Method
223
+ # ──────────────────────────────────────────────────────────────────────
224
+
225
+ def vogel_approximation(
226
+ cost: List[List[float]],
227
+ supply: List[float],
228
+ demand: List[float],
229
+ display: bool = True,
230
+ ) -> dict:
231
+ """
232
+ AIM: Find an initial Basic Feasible Solution using Vogel's
233
+ Approximation Method (VAM). Computes row/column penalties
234
+ (difference between two smallest costs) and allocates to the
235
+ minimum-cost cell in the row/column with the largest penalty.
236
+
237
+ Parameters
238
+ ----------
239
+ cost : m×n cost matrix.
240
+ supply : Supply vector.
241
+ demand : Demand vector.
242
+ display : Print allocation table.
243
+
244
+ Returns
245
+ -------
246
+ dict — same structure as north_west_corner.
247
+ """
248
+ cost_orig, supply, demand = _balance(
249
+ np.array(cost, dtype=float),
250
+ np.array(supply, dtype=float),
251
+ np.array(demand, dtype=float),
252
+ )
253
+ m, n = cost_orig.shape
254
+ supply = supply.copy()
255
+ demand = demand.copy()
256
+ alloc = np.zeros((m, n))
257
+ cost_w = cost_orig.copy()
258
+
259
+ row_done = [False] * m
260
+ col_done = [False] * n
261
+ INF = np.inf
262
+
263
+ def _penalty(arr):
264
+ valid = sorted([x for x in arr if x < INF])
265
+ if len(valid) < 2: return 0
266
+ return valid[1] - valid[0]
267
+
268
+ total_alloc = 0
269
+ required = m + n - 1 # BFS requirement
270
+
271
+ while total_alloc < required:
272
+ active_rows = [i for i in range(m) if not row_done[i]]
273
+ active_cols = [j for j in range(n) if not col_done[j]]
274
+ if not active_rows or not active_cols:
275
+ break
276
+
277
+ # Compute row penalties
278
+ row_penalties = {}
279
+ for i in active_rows:
280
+ row_costs = [cost_w[i, j] for j in active_cols]
281
+ row_penalties[i] = _penalty(row_costs)
282
+
283
+ # Compute column penalties
284
+ col_penalties = {}
285
+ for j in active_cols:
286
+ col_costs = [cost_w[i, j] for i in active_rows]
287
+ col_penalties[j] = _penalty(col_costs)
288
+
289
+ max_row_pen = max(row_penalties.values()) if row_penalties else -1
290
+ max_col_pen = max(col_penalties.values()) if col_penalties else -1
291
+
292
+ if max_row_pen >= max_col_pen:
293
+ # Choose row with highest penalty
294
+ i = max(row_penalties, key=row_penalties.get)
295
+ j = min(active_cols, key=lambda jj: cost_w[i, jj])
296
+ else:
297
+ j = max(col_penalties, key=col_penalties.get)
298
+ i = min(active_rows, key=lambda ii: cost_w[ii, j])
299
+
300
+ qty = min(supply[i], demand[j])
301
+ alloc[i, j] += qty
302
+ supply[i] -= qty
303
+ demand[j] -= qty
304
+ total_alloc += 1
305
+
306
+ if supply[i] <= 1e-9:
307
+ row_done[i] = True
308
+ cost_w[i, :] = INF
309
+ if demand[j] <= 1e-9:
310
+ col_done[j] = True
311
+ cost_w[:, j] = INF
312
+
313
+ result = {
314
+ "allocation": alloc,
315
+ "total_cost": _total_cost(alloc, cost_orig),
316
+ "cost" : cost_orig,
317
+ "supply" : supply,
318
+ "demand" : demand,
319
+ }
320
+ if display:
321
+ _display_solution(alloc, cost_orig,
322
+ "Vogel's Approximation Method (Initial BFS)")
323
+ return result
324
+
325
+
326
+ # ──────────────────────────────────────────────────────────────────────
327
+ # 4. MODI (Modified Distribution) Method
328
+ # ──────────────────────────────────────────────────────────────────────
329
+
330
+ def modi_method(
331
+ cost: List[List[float]],
332
+ supply: List[float],
333
+ demand: List[float],
334
+ initial_method: str = "vam",
335
+ display: bool = True,
336
+ max_iter: int = 500,
337
+ ) -> dict:
338
+ """
339
+ AIM: Test and improve a Basic Feasible Solution for optimality using
340
+ the MODI (u-v / stepping-stone) Method.
341
+
342
+ The method:
343
+ 1. Starts from an initial BFS (NW Corner / Least Cost / VAM).
344
+ 2. Computes u_i and v_j potentials for basic cells.
345
+ 3. Computes reduced costs d_ij = c_ij - u_i - v_j for
346
+ non-basic cells.
347
+ 4. If all d_ij >= 0, the solution is optimal.
348
+ 5. Otherwise, the most negative d_ij cell enters the basis;
349
+ a loop (stepping-stone path) is traced to find the leaving
350
+ cell and update allocations.
351
+
352
+ Parameters
353
+ ----------
354
+ cost : m×n cost matrix.
355
+ supply : Supply vector.
356
+ demand : Demand vector.
357
+ initial_method : 'nwc' | 'lcm' | 'vam' (default 'vam').
358
+ display : Print step-by-step and final result.
359
+ max_iter : Maximum MODI iterations.
360
+
361
+ Returns
362
+ -------
363
+ dict with keys:
364
+ allocation : Optimal allocation matrix
365
+ total_cost : Optimal total cost
366
+ u : u-potentials
367
+ v : v-potentials
368
+ iterations : Number of MODI iterations
369
+ status : 'Optimal' | 'Error'
370
+ """
371
+ # Step 1: Get initial BFS
372
+ if initial_method.lower() in ("nwc", "northwest", "north_west"):
373
+ init = north_west_corner(cost, supply, demand, display=False)
374
+ elif initial_method.lower() in ("lcm", "least_cost"):
375
+ init = least_cost_method(cost, supply, demand, display=False)
376
+ else:
377
+ init = vogel_approximation(cost, supply, demand, display=False)
378
+
379
+ alloc = init["allocation"].copy()
380
+ C = init["cost"].copy()
381
+ m, n = C.shape
382
+
383
+ # Handle degeneracy: need exactly m+n-1 basic cells
384
+ _fix_degeneracy(alloc, C, m, n)
385
+
386
+ for iteration in range(max_iter):
387
+ # Step 2: Compute u and v potentials
388
+ u = np.full(m, np.nan)
389
+ v = np.full(n, np.nan)
390
+ u[0] = 0.0 # Set u[0] = 0 (free variable)
391
+
392
+ basic_cells = [(i, j) for i in range(m) for j in range(n)
393
+ if alloc[i, j] > 1e-9]
394
+
395
+ changed = True
396
+ while changed:
397
+ changed = False
398
+ for (i, j) in basic_cells:
399
+ if not np.isnan(u[i]) and np.isnan(v[j]):
400
+ v[j] = C[i, j] - u[i]
401
+ changed = True
402
+ elif not np.isnan(v[j]) and np.isnan(u[i]):
403
+ u[i] = C[i, j] - v[j]
404
+ changed = True
405
+
406
+ if np.any(np.isnan(u)) or np.any(np.isnan(v)):
407
+ # Disconnect — fix and retry
408
+ _fix_degeneracy(alloc, C, m, n)
409
+ continue
410
+
411
+ # Step 3: Compute reduced costs for non-basic cells
412
+ d = np.full((m, n), np.nan)
413
+ non_basic = []
414
+ for i in range(m):
415
+ for j in range(n):
416
+ if alloc[i, j] <= 1e-9:
417
+ d[i, j] = C[i, j] - u[i] - v[j]
418
+ non_basic.append((d[i, j], i, j))
419
+
420
+ # Step 4: Optimality check
421
+ if not non_basic or min(x[0] for x in non_basic) >= -1e-9:
422
+ break
423
+
424
+ # Step 5: Select entering cell (most negative d)
425
+ non_basic.sort()
426
+ _, ei, ej = non_basic[0]
427
+
428
+ # Step 6: Trace stepping-stone loop
429
+ loop = _find_loop(alloc, ei, ej, m, n)
430
+ if loop is None:
431
+ break # No loop found (degenerate)
432
+
433
+ # Determine theta (min allocation at minus positions)
434
+ minus_cells = loop[1::2] # alternating + / - starting with +
435
+ theta = min(alloc[r, c] for (r, c) in minus_cells)
436
+
437
+ # Update allocations
438
+ for k, (r, c) in enumerate(loop):
439
+ if k % 2 == 0:
440
+ alloc[r, c] += theta
441
+ else:
442
+ alloc[r, c] -= theta
443
+
444
+ # Clean up near-zero allocations
445
+ alloc[alloc < 1e-9] = 0.0
446
+ _fix_degeneracy(alloc, C, m, n)
447
+
448
+ optimal_cost = _total_cost(alloc, C)
449
+
450
+ result = {
451
+ "status" : "Optimal",
452
+ "allocation": alloc,
453
+ "total_cost": optimal_cost,
454
+ "u" : u,
455
+ "v" : v,
456
+ "iterations": iteration + 1,
457
+ "cost" : C,
458
+ }
459
+
460
+ if display:
461
+ print("=" * 60)
462
+ print(" MODI Method — Optimal Transportation Solution")
463
+ print("=" * 60)
464
+ _display_solution(alloc, C, "MODI (u-v) Optimal Allocation")
465
+ print(f" u-potentials : {np.round(u, 4)}")
466
+ print(f" v-potentials : {np.round(v, 4)}")
467
+ print(f" Iterations : {iteration + 1}")
468
+
469
+ return result
470
+
471
+
472
+ # ──────────────────────────────────────────────────────────────────────
473
+ # MODI helpers
474
+ # ──────────────────────────────────────────────────────────────────────
475
+
476
+ def _fix_degeneracy(alloc: np.ndarray, cost: np.ndarray,
477
+ m: int, n: int, eps: float = 1e-8) -> None:
478
+ """Add epsilon to cells to maintain m+n-1 basic cells if degenerate."""
479
+ basic = [(i, j) for i in range(m) for j in range(n) if alloc[i, j] > 0]
480
+ required = m + n - 1
481
+ if len(basic) >= required:
482
+ return
483
+ # Add epsilon allocations to independent cells
484
+ for i in range(m):
485
+ for j in range(n):
486
+ if len(basic) >= required:
487
+ return
488
+ if (i, j) not in basic:
489
+ alloc[i, j] = eps
490
+ basic.append((i, j))
491
+
492
+
493
+ def _find_loop(alloc: np.ndarray, ei: int, ej: int,
494
+ m: int, n: int) -> Optional[List[Tuple[int, int]]]:
495
+ """
496
+ Find a closed loop for the stepping-stone path starting at (ei, ej).
497
+ Uses backtracking DFS. Returns list of cells in loop order or None.
498
+ """
499
+ basic = {(i, j) for i in range(m) for j in range(n) if alloc[i, j] > 1e-9}
500
+ start = (ei, ej)
501
+
502
+ def dfs(path, last_turn):
503
+ cur = path[-1]
504
+ if len(path) > 1 and cur == start:
505
+ return path[:]
506
+ if len(path) > 2 * (m + n):
507
+ return None
508
+
509
+ i, j = cur
510
+ # alternate: even-length path → change column; odd → change row
511
+ if len(path) % 2 == 1: # move along column (fix j, change i)
512
+ candidates = [(r, j) for r in range(m)
513
+ if (r, j) in basic or (r == ei and j == ej)]
514
+ else: # move along row (fix i, change j)
515
+ candidates = [(i, c) for c in range(n)
516
+ if (i, c) in basic or (i == ei and c == ej)]
517
+
518
+ for nxt in candidates:
519
+ if nxt == start and len(path) >= 4:
520
+ return path + [start]
521
+ if nxt not in path:
522
+ res = dfs(path + [nxt], nxt)
523
+ if res:
524
+ return res
525
+ return None
526
+
527
+ return dfs([start], start)