PyOR 1.0.0__tar.gz → 1.1.1__tar.gz

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.
Files changed (31) hide show
  1. {pyor-1.0.0 → pyor-1.1.1}/PKG-INFO +22 -2
  2. {pyor-1.0.0 → pyor-1.1.1}/PyOR.egg-info/PKG-INFO +22 -2
  3. {pyor-1.0.0 → pyor-1.1.1}/PyOR.egg-info/SOURCES.txt +9 -1
  4. {pyor-1.0.0 → pyor-1.1.1}/README.md +20 -0
  5. pyor-1.1.1/pyOR/__init__.py +98 -0
  6. pyor-1.1.1/pyOR/_utils.py +45 -0
  7. pyor-1.1.1/pyOR/dynamic_programming.py +150 -0
  8. pyor-1.1.1/pyOR/game_theory.py +220 -0
  9. pyor-1.1.1/pyOR/gradient_methods.py +147 -0
  10. pyor-1.1.1/pyOR/q_simul.py +152 -0
  11. pyor-1.1.1/pyOR/q_theory.py +124 -0
  12. {pyor-1.0.0 → pyor-1.1.1}/pyproject.toml +3 -2
  13. {pyor-1.0.0 → pyor-1.1.1}/setup.py +1 -1
  14. pyor-1.1.1/tests/test_lab_modules.py +54 -0
  15. pyor-1.0.0/pyOR/__init__.py +0 -55
  16. {pyor-1.0.0 → pyor-1.1.1}/LICENSE +0 -0
  17. {pyor-1.0.0 → pyor-1.1.1}/MANIFEST.in +0 -0
  18. {pyor-1.0.0 → pyor-1.1.1}/PyOR.egg-info/dependency_links.txt +0 -0
  19. {pyor-1.0.0 → pyor-1.1.1}/PyOR.egg-info/requires.txt +0 -0
  20. {pyor-1.0.0 → pyor-1.1.1}/PyOR.egg-info/top_level.txt +0 -0
  21. {pyor-1.0.0 → pyor-1.1.1}/pyOR/assignment.py +0 -0
  22. {pyor-1.0.0 → pyor-1.1.1}/pyOR/big_m.py +0 -0
  23. {pyor-1.0.0 → pyor-1.1.1}/pyOR/curve_fitting.py +0 -0
  24. {pyor-1.0.0 → pyor-1.1.1}/pyOR/dual_simplex.py +0 -0
  25. {pyor-1.0.0 → pyor-1.1.1}/pyOR/graphical_method.py +0 -0
  26. {pyor-1.0.0 → pyor-1.1.1}/pyOR/linear_programming.py +0 -0
  27. {pyor-1.0.0 → pyor-1.1.1}/pyOR/project_management.py +0 -0
  28. {pyor-1.0.0 → pyor-1.1.1}/pyOR/simplex.py +0 -0
  29. {pyor-1.0.0 → pyor-1.1.1}/pyOR/spline_fitting.py +0 -0
  30. {pyor-1.0.0 → pyor-1.1.1}/pyOR/transportation.py +0 -0
  31. {pyor-1.0.0 → pyor-1.1.1}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: PyOR
3
- Version: 1.0.0
3
+ Version: 1.1.1
4
4
  Summary: Python Operations Research — LP, Simplex, Transportation, Assignment, PERT/CPM, Curve Fitting & more
5
5
  Author: PyOR Contributors
6
6
  License: MIT License
@@ -28,7 +28,7 @@ License: MIT License
28
28
  Project-URL: Homepage, https://github.com/PyOR-dev/PyOR
29
29
  Project-URL: Documentation, https://github.com/PyOR-dev/PyOR#readme
30
30
  Project-URL: Issues, https://github.com/PyOR-dev/PyOR/issues
31
- Keywords: operations research,linear programming,simplex,transportation,assignment,PERT,CPM,curve fitting,spline,optimization
31
+ Keywords: operations research,linear programming,simplex,transportation,assignment,PERT,CPM,curve fitting,spline,optimization,game theory,queueing,simulation,dynamic programming,gradient descent
32
32
  Classifier: Development Status :: 4 - Beta
33
33
  Classifier: Intended Audience :: Science/Research
34
34
  Classifier: Intended Audience :: Education
@@ -94,6 +94,26 @@ pip install PyOR[plot]
94
94
  | 11 | Project Management (PERT / CPM) | `PERTCPMNetwork` |
95
95
  | 12 | Curve Fitting — Least Squares | `CurveFitter` |
96
96
  | 13 | Cubic Spline Interpolation | `CubicSplineFitter` |
97
+ | 14 | Game Theory (saddle, 2x2, graphical, LP) — *new in 1.1.0* | `pyOR.game_theory` · `MatrixGame` |
98
+ | 15 | Queueing theory M/M/1, M/M/k (Erlang-C vs simulation) — *new* | `pyOR.q_theory` |
99
+ | 16 | Airport queue simulation & staffing optimisation — *new* | `pyOR.q_simul` |
100
+ | 17 | Gradient descent, Newton, BFGS — *new* | `pyOR.gradient_methods` |
101
+ | 18 | Multi-stage resource allocation (DP) — *new* | `pyOR.dynamic_programming` · `ResourceAllocationDP` |
102
+
103
+ ### New in 1.1.0 — printing the complete code
104
+
105
+ Each new module has `demo()` (runs the lab example) and `code()` (prints the
106
+ module's complete source):
107
+
108
+ ```python
109
+ import pyOR
110
+ from pyOR import q_theory, q_simul, game_theory, gradient_methods, dynamic_programming
111
+
112
+ q_theory.demo() # run the M/M/k experiment
113
+ q_theory.code() # print the complete source code
114
+ pyOR.code("q_simul") # same thing, by name
115
+ pyOR.list_modules()
116
+ ```
97
117
 
98
118
  ---
99
119
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: PyOR
3
- Version: 1.0.0
3
+ Version: 1.1.1
4
4
  Summary: Python Operations Research — LP, Simplex, Transportation, Assignment, PERT/CPM, Curve Fitting & more
5
5
  Author: PyOR Contributors
6
6
  License: MIT License
@@ -28,7 +28,7 @@ License: MIT License
28
28
  Project-URL: Homepage, https://github.com/PyOR-dev/PyOR
29
29
  Project-URL: Documentation, https://github.com/PyOR-dev/PyOR#readme
30
30
  Project-URL: Issues, https://github.com/PyOR-dev/PyOR/issues
31
- Keywords: operations research,linear programming,simplex,transportation,assignment,PERT,CPM,curve fitting,spline,optimization
31
+ Keywords: operations research,linear programming,simplex,transportation,assignment,PERT,CPM,curve fitting,spline,optimization,game theory,queueing,simulation,dynamic programming,gradient descent
32
32
  Classifier: Development Status :: 4 - Beta
33
33
  Classifier: Intended Audience :: Science/Research
34
34
  Classifier: Intended Audience :: Education
@@ -94,6 +94,26 @@ pip install PyOR[plot]
94
94
  | 11 | Project Management (PERT / CPM) | `PERTCPMNetwork` |
95
95
  | 12 | Curve Fitting — Least Squares | `CurveFitter` |
96
96
  | 13 | Cubic Spline Interpolation | `CubicSplineFitter` |
97
+ | 14 | Game Theory (saddle, 2x2, graphical, LP) — *new in 1.1.0* | `pyOR.game_theory` · `MatrixGame` |
98
+ | 15 | Queueing theory M/M/1, M/M/k (Erlang-C vs simulation) — *new* | `pyOR.q_theory` |
99
+ | 16 | Airport queue simulation & staffing optimisation — *new* | `pyOR.q_simul` |
100
+ | 17 | Gradient descent, Newton, BFGS — *new* | `pyOR.gradient_methods` |
101
+ | 18 | Multi-stage resource allocation (DP) — *new* | `pyOR.dynamic_programming` · `ResourceAllocationDP` |
102
+
103
+ ### New in 1.1.0 — printing the complete code
104
+
105
+ Each new module has `demo()` (runs the lab example) and `code()` (prints the
106
+ module's complete source):
107
+
108
+ ```python
109
+ import pyOR
110
+ from pyOR import q_theory, q_simul, game_theory, gradient_methods, dynamic_programming
111
+
112
+ q_theory.demo() # run the M/M/k experiment
113
+ q_theory.code() # print the complete source code
114
+ pyOR.code("q_simul") # same thing, by name
115
+ pyOR.list_modules()
116
+ ```
97
117
 
98
118
  ---
99
119
 
@@ -2,6 +2,7 @@ LICENSE
2
2
  MANIFEST.in
3
3
  README.md
4
4
  pyproject.toml
5
+ setup.cfg
5
6
  setup.py
6
7
  PyOR.egg-info/PKG-INFO
7
8
  PyOR.egg-info/SOURCES.txt
@@ -9,13 +10,20 @@ PyOR.egg-info/dependency_links.txt
9
10
  PyOR.egg-info/requires.txt
10
11
  PyOR.egg-info/top_level.txt
11
12
  pyOR/__init__.py
13
+ pyOR/_utils.py
12
14
  pyOR/assignment.py
13
15
  pyOR/big_m.py
14
16
  pyOR/curve_fitting.py
15
17
  pyOR/dual_simplex.py
18
+ pyOR/dynamic_programming.py
19
+ pyOR/game_theory.py
20
+ pyOR/gradient_methods.py
16
21
  pyOR/graphical_method.py
17
22
  pyOR/linear_programming.py
18
23
  pyOR/project_management.py
24
+ pyOR/q_simul.py
25
+ pyOR/q_theory.py
19
26
  pyOR/simplex.py
20
27
  pyOR/spline_fitting.py
21
- pyOR/transportation.py
28
+ pyOR/transportation.py
29
+ tests/test_lab_modules.py
@@ -36,6 +36,26 @@ pip install PyOR[plot]
36
36
  | 11 | Project Management (PERT / CPM) | `PERTCPMNetwork` |
37
37
  | 12 | Curve Fitting — Least Squares | `CurveFitter` |
38
38
  | 13 | Cubic Spline Interpolation | `CubicSplineFitter` |
39
+ | 14 | Game Theory (saddle, 2x2, graphical, LP) — *new in 1.1.0* | `pyOR.game_theory` · `MatrixGame` |
40
+ | 15 | Queueing theory M/M/1, M/M/k (Erlang-C vs simulation) — *new* | `pyOR.q_theory` |
41
+ | 16 | Airport queue simulation & staffing optimisation — *new* | `pyOR.q_simul` |
42
+ | 17 | Gradient descent, Newton, BFGS — *new* | `pyOR.gradient_methods` |
43
+ | 18 | Multi-stage resource allocation (DP) — *new* | `pyOR.dynamic_programming` · `ResourceAllocationDP` |
44
+
45
+ ### New in 1.1.0 — printing the complete code
46
+
47
+ Each new module has `demo()` (runs the lab example) and `code()` (prints the
48
+ module's complete source):
49
+
50
+ ```python
51
+ import pyOR
52
+ from pyOR import q_theory, q_simul, game_theory, gradient_methods, dynamic_programming
53
+
54
+ q_theory.demo() # run the M/M/k experiment
55
+ q_theory.code() # print the complete source code
56
+ pyOR.code("q_simul") # same thing, by name
57
+ pyOR.list_modules()
58
+ ```
39
59
 
40
60
  ---
41
61
 
@@ -0,0 +1,98 @@
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
+ - game_theory : Zero-sum games (saddle, 2x2, graphical, LP) [v1.1.0]
18
+ - q_theory : M/M/1 & M/M/k queues - Erlang-C vs simulation [v1.1.0]
19
+ - q_simul : Airport queue simulation + staffing optimisation [v1.1.0]
20
+ - gradient_methods : Gradient descent, Newton, BFGS [v1.1.0]
21
+ - dynamic_programming : Multi-stage resource allocation (DP) [v1.1.0]
22
+
23
+ Every new module has ``demo()`` and ``code()``; ``code()`` prints the
24
+ complete source code of the module. ``pyOR.code('q_theory')`` does the same.
25
+
26
+ Author : PyOR Contributors
27
+ License : MIT
28
+ """
29
+
30
+ from .linear_programming import LinearProgram
31
+ from .graphical_method import GraphicalMethod
32
+ from .simplex import SimplexMethod
33
+ from .dual_simplex import DualSimplex
34
+ from .big_m import BigMMethod
35
+ from .transportation import (
36
+ north_west_corner,
37
+ least_cost_method,
38
+ vogel_approximation,
39
+ modi_method,
40
+ )
41
+ from .assignment import AssignmentProblem
42
+ from .project_management import PERTCPMNetwork
43
+ from .curve_fitting import CurveFitter
44
+ from .spline_fitting import CubicSplineFitter
45
+ from . import game_theory, q_theory, q_simul, gradient_methods, dynamic_programming
46
+ from .game_theory import MatrixGame
47
+ from .dynamic_programming import ResourceAllocationDP
48
+
49
+ __all__ = [
50
+ "LinearProgram",
51
+ "GraphicalMethod",
52
+ "SimplexMethod",
53
+ "DualSimplex",
54
+ "BigMMethod",
55
+ "north_west_corner",
56
+ "least_cost_method",
57
+ "vogel_approximation",
58
+ "modi_method",
59
+ "AssignmentProblem",
60
+ "PERTCPMNetwork",
61
+ "CurveFitter",
62
+ "CubicSplineFitter",
63
+ "MatrixGame",
64
+ "ResourceAllocationDP",
65
+ "game_theory",
66
+ "q_theory",
67
+ "q_simul",
68
+ "gradient_methods",
69
+ "dynamic_programming",
70
+ "code",
71
+ "list_modules",
72
+ ]
73
+
74
+ _LAB_MODULES = {
75
+ "game_theory": game_theory,
76
+ "q_theory": q_theory,
77
+ "q_simul": q_simul,
78
+ "gradient_methods": gradient_methods,
79
+ "dynamic_programming": dynamic_programming,
80
+ }
81
+
82
+
83
+ def list_modules():
84
+ """Print the lab modules added in v1.1.0."""
85
+ for name, mod in _LAB_MODULES.items():
86
+ first = (mod.__doc__ or "").split("AIM:")[1].strip().splitlines()[0]
87
+ print(f"{name:20s} {first}")
88
+
89
+
90
+ def code(name):
91
+ """Print the complete source code of a lab module, e.g. ``pyOR.code('q_theory')``."""
92
+ if name not in _LAB_MODULES:
93
+ raise ValueError(f"Unknown module {name!r}. Choose from {list(_LAB_MODULES)}.")
94
+ _LAB_MODULES[name].code()
95
+
96
+
97
+ __version__ = "1.1.1"
98
+ __author__ = "PyOR Contributors"
@@ -0,0 +1,45 @@
1
+ """
2
+ Module: _utils.py
3
+ =================
4
+ Internal helpers shared by the PyOR lab modules (v1.1.0+).
5
+ """
6
+
7
+ from __future__ import annotations
8
+ import inspect
9
+ import sys
10
+
11
+
12
+ def print_source(module) -> None:
13
+ """Print the complete source code of ``module`` (a module object)."""
14
+ try:
15
+ src = inspect.getsource(module)
16
+ except (OSError, TypeError):
17
+ with open(module.__file__, encoding="utf-8") as fh:
18
+ src = fh.read()
19
+ print(src)
20
+
21
+
22
+ def import_pyplot():
23
+ """Import matplotlib.pyplot lazily with a helpful error message."""
24
+ try:
25
+ import matplotlib.pyplot as plt
26
+ except ImportError as exc: # pragma: no cover
27
+ raise ImportError(
28
+ "Plotting needs matplotlib. Install it with: pip install PyOR[plot]"
29
+ ) from exc
30
+ return plt
31
+
32
+
33
+ def table(headers, rows, fmt="{:.4f}") -> str:
34
+ """Return a simple aligned text table."""
35
+ def cell(v):
36
+ if isinstance(v, float):
37
+ return fmt.format(v)
38
+ return str(v)
39
+
40
+ body = [[cell(v) for v in r] for r in rows]
41
+ widths = [max(len(str(h)), *(len(r[i]) for r in body)) for i, h in enumerate(headers)]
42
+ line = " ".join(str(h).rjust(w) for h, w in zip(headers, widths))
43
+ out = [line, "-" * len(line)]
44
+ out += [" ".join(c.rjust(w) for c, w in zip(r, widths)) for r in body]
45
+ return "\n".join(out)
@@ -0,0 +1,150 @@
1
+ """
2
+ Module: dynamic_programming.py
3
+ ===============================
4
+ AIM:
5
+ Multi-stage RESOURCE ALLOCATION by Dynamic Programming.
6
+
7
+ Allocate S units among N activities (stages). r[n][x] is the return
8
+ from giving x units to activity n.
9
+
10
+ Backward recursion: f_n(s) = max_{0<=x<=s} { r_n(x) + f_{n+1}(s-x) },
11
+ f_{N+1}(s) = 0
12
+
13
+ The optimal allocation is recovered going forward from s = S.
14
+
15
+ Call ``code()`` to print the complete source code of this module.
16
+ """
17
+
18
+ from __future__ import annotations
19
+ import sys
20
+ from itertools import product
21
+ from typing import List
22
+
23
+ import numpy as np
24
+
25
+ from ._utils import print_source, import_pyplot, table
26
+
27
+ DEFAULT_RETURNS = [[0, 5, 9, 12, 14, 15, 15],
28
+ [0, 4, 8, 11, 13, 14, 14],
29
+ [0, 6, 10, 13, 15, 16, 16],
30
+ [0, 3, 7, 10, 12, 13, 13]]
31
+
32
+
33
+ class ResourceAllocationDP:
34
+ """
35
+ Parameters
36
+ ----------
37
+ returns : N x (S+1) array, returns[n][x] = return of x units on activity n.
38
+
39
+ Examples
40
+ --------
41
+ >>> dp = ResourceAllocationDP() # Lab-10 data
42
+ >>> dp.solve()
43
+ >>> dp.display()
44
+ >>> dp.sensitivity()
45
+ """
46
+
47
+ def __init__(self, returns=None):
48
+ self.r = np.asarray(DEFAULT_RETURNS if returns is None else returns, float)
49
+ self.N, self.S = self.r.shape[0], self.r.shape[1] - 1
50
+ self.f = None
51
+ self.policy = None
52
+
53
+ # -- DP recursion ---------------------------------------------------
54
+ def solve(self):
55
+ """Backward recursion. Returns (f, policy)."""
56
+ N, S, r = self.N, self.S, self.r
57
+ f = np.zeros((N + 1, S + 1))
58
+ policy = np.zeros((N, S + 1), int)
59
+ for n in range(N - 1, -1, -1):
60
+ for s in range(S + 1):
61
+ vals = [r[n, x] + f[n + 1, s - x] for x in range(s + 1)]
62
+ f[n, s] = max(vals)
63
+ policy[n, s] = int(np.argmax(vals))
64
+ self.f, self.policy = f, policy
65
+ return f, policy
66
+
67
+ def _ensure(self):
68
+ if self.f is None:
69
+ self.solve()
70
+
71
+ # -- optimal allocation --------------------------------------------
72
+ def allocation(self, budget: int = None) -> List[int]:
73
+ """Forward recovery of the optimal allocation for ``budget`` units."""
74
+ self._ensure()
75
+ s = self.S if budget is None else int(budget)
76
+ alloc = []
77
+ for n in range(self.N):
78
+ x = int(self.policy[n, s])
79
+ alloc.append(x)
80
+ s -= x
81
+ return alloc
82
+
83
+ def max_return(self, budget: int = None) -> float:
84
+ self._ensure()
85
+ return float(self.f[0, self.S if budget is None else int(budget)])
86
+
87
+ def brute_force(self):
88
+ """Exhaustive check. Returns (best value, best allocation)."""
89
+ best = max((sum(self.r[n, c[n]] for n in range(self.N)), c)
90
+ for c in product(range(self.S + 1), repeat=self.N)
91
+ if sum(c) == self.S)
92
+ return float(best[0]), list(best[1])
93
+
94
+ def sensitivity(self, plot: bool = False, verbose: bool = True):
95
+ """Max return and allocation for every budget 0..S."""
96
+ self._ensure()
97
+ rows = [[B, int(self.f[0, B]), self.allocation(B)] for B in range(self.S + 1)]
98
+ if verbose:
99
+ print(table(["Budget", "Max return", "Allocation"], rows))
100
+ if plot:
101
+ plt = import_pyplot()
102
+ plt.plot(range(self.S + 1), self.f[0], "o-")
103
+ plt.xlabel("Total units available")
104
+ plt.ylabel("Maximum return")
105
+ plt.title("Value of additional resource")
106
+ plt.grid(alpha=0.3)
107
+ plt.show()
108
+ return rows
109
+
110
+ def plot_policy(self):
111
+ """Heat map of the optimal policy x_n*(s)."""
112
+ self._ensure()
113
+ plt = import_pyplot()
114
+ fig, ax = plt.subplots(figsize=(7, 3.5))
115
+ im = ax.imshow(self.policy, cmap="Blues")
116
+ for n in range(self.N):
117
+ for s in range(self.S + 1):
118
+ ax.text(s, n, self.policy[n, s], ha="center", va="center")
119
+ ax.set_xticks(range(self.S + 1))
120
+ ax.set_yticks(range(self.N))
121
+ ax.set_yticklabels([f"Stage {n + 1}" for n in range(self.N)])
122
+ ax.set_xlabel("Units remaining s")
123
+ ax.set_title("Optimal units x_n*(s) to allocate")
124
+ plt.colorbar(im)
125
+ plt.show()
126
+
127
+ def display(self) -> None:
128
+ self._ensure()
129
+ print("f_n(s) table (rows = stage 1..%d, cols = s = 0..%d)" % (self.N, self.S))
130
+ print(self.f[:self.N].astype(int), "\n")
131
+ alloc = self.allocation()
132
+ print("Optimal allocation:", alloc)
133
+ print("Maximum total return =", int(self.max_return()))
134
+ print("Check:", int(sum(self.r[n, alloc[n]] for n in range(self.N))))
135
+ bf = self.brute_force()
136
+ print("Brute force best :", int(bf[0]), bf[1], "\n")
137
+
138
+
139
+ def demo(plot: bool = False) -> None:
140
+ """Run the Lab-10 example."""
141
+ dp = ResourceAllocationDP()
142
+ dp.display()
143
+ dp.sensitivity(plot=plot)
144
+ if plot:
145
+ dp.plot_policy()
146
+
147
+
148
+ def code() -> None:
149
+ """Print the complete source code of this module."""
150
+ print_source(sys.modules[__name__])
@@ -0,0 +1,220 @@
1
+ """
2
+ Module: game_theory.py
3
+ =======================
4
+ AIM:
5
+ To solve two-person zero-sum matrix games.
6
+
7
+ Methods implemented
8
+ 1. Maximin / Minimax test for a saddle point.
9
+ 2. Analytical formula for a 2 x 2 game (mixed strategies).
10
+ 3. Graphical method for 2 x n and m x 2 games.
11
+ 4. Linear-programming method for a general m x n game.
12
+
13
+ The payoff matrix A holds the payoffs to the ROW player (maximiser);
14
+ the COLUMN player (minimiser) pays them.
15
+
16
+ Call ``code()`` to print the complete source code of this module.
17
+ """
18
+
19
+ from __future__ import annotations
20
+ import sys
21
+ from typing import Sequence, Tuple
22
+
23
+ import numpy as np
24
+ from scipy.optimize import linprog
25
+
26
+ from ._utils import print_source, import_pyplot
27
+
28
+
29
+ # ----------------------------------------------------------------------
30
+ # 1. Saddle point test
31
+ # ----------------------------------------------------------------------
32
+ def saddle_point(A) -> dict:
33
+ """
34
+ Maximin / minimax test.
35
+
36
+ Returns
37
+ -------
38
+ dict with keys ``maximin``, ``minimax``, ``has_saddle``.
39
+ """
40
+ A = np.asarray(A, float)
41
+ maximin = A.min(axis=1).max() # row player's best worst-case
42
+ minimax = A.max(axis=0).min() # column player's best worst-case
43
+ return {"maximin": maximin, "minimax": minimax,
44
+ "has_saddle": bool(np.isclose(maximin, minimax))}
45
+
46
+
47
+ # ----------------------------------------------------------------------
48
+ # 2. 2 x 2 analytical solution
49
+ # ----------------------------------------------------------------------
50
+ def solve_2x2(A) -> dict:
51
+ """
52
+ Closed-form mixed-strategy solution of a 2 x 2 game with no saddle point.
53
+
54
+ Returns dict(p, q, value) with p = P(row 1), q = P(col 1).
55
+ """
56
+ A = np.asarray(A, float)
57
+ if A.shape != (2, 2):
58
+ raise ValueError("solve_2x2 needs a 2 x 2 matrix.")
59
+ sp = saddle_point(A)
60
+ if sp["has_saddle"]:
61
+ raise ValueError("The game has a saddle point (value = %g); "
62
+ "pure strategies are optimal." % sp["maximin"])
63
+ (a, b), (c, d) = A
64
+ den = a + d - b - c
65
+ p = (d - c) / den
66
+ q = (d - b) / den
67
+ v = (a * d - b * c) / den
68
+ return {"p": p, "q": q, "value": v}
69
+
70
+
71
+ # ----------------------------------------------------------------------
72
+ # 3. Graphical methods
73
+ # ----------------------------------------------------------------------
74
+ def graph_2xn(A, plot: bool = True) -> Tuple[float, float]:
75
+ """
76
+ Row player has 2 strategies. Take the LOWER envelope of the expected
77
+ payoff lines (one per column) and pick its highest point.
78
+
79
+ Returns (p, value) where p = P(row player plays row 1).
80
+ """
81
+ A = np.asarray(A, float)
82
+ p = np.linspace(0, 1, 201)
83
+ lines = np.array([p * A[0, j] + (1 - p) * A[1, j] for j in range(A.shape[1])])
84
+ env = lines.min(axis=0)
85
+ i = int(env.argmax())
86
+
87
+ if plot:
88
+ plt = import_pyplot()
89
+ for j, l in enumerate(lines):
90
+ plt.plot(p, l, label=f"B plays col {j + 1}")
91
+ plt.plot(p, env, "k", lw=3, label="Lower envelope")
92
+ plt.plot(p[i], env[i], "ro")
93
+ plt.xlabel("p = P(A plays row 1)")
94
+ plt.ylabel("Expected payoff")
95
+ plt.title(f"2xn graphical solution: p = {p[i]:.2f}, value = {env[i]:.2f}")
96
+ plt.legend()
97
+ plt.show()
98
+ return float(p[i]), float(env[i])
99
+
100
+
101
+ def graph_mx2(A, plot: bool = True) -> Tuple[float, float]:
102
+ """
103
+ Column player has 2 strategies. Take the UPPER envelope of the expected
104
+ loss lines (one per row) and pick its lowest point.
105
+
106
+ Returns (q, value) where q = P(column player plays col 1).
107
+ """
108
+ A = np.asarray(A, float)
109
+ q = np.linspace(0, 1, 201)
110
+ lines = np.array([q * A[i, 0] + (1 - q) * A[i, 1] for i in range(A.shape[0])])
111
+ env = lines.max(axis=0)
112
+ i = int(env.argmin())
113
+
114
+ if plot:
115
+ plt = import_pyplot()
116
+ for r, l in enumerate(lines):
117
+ plt.plot(q, l, label=f"A plays row {r + 1}")
118
+ plt.plot(q, env, "k", lw=3, label="Upper envelope")
119
+ plt.plot(q[i], env[i], "ro")
120
+ plt.xlabel("q = P(B plays col 1)")
121
+ plt.ylabel("Expected payoff")
122
+ plt.title(f"mx2 graphical solution: q = {q[i]:.2f}, value = {env[i]:.2f}")
123
+ plt.legend()
124
+ plt.show()
125
+ return float(q[i]), float(env[i])
126
+
127
+
128
+ # ----------------------------------------------------------------------
129
+ # 4. m x n game via linear programming
130
+ # ----------------------------------------------------------------------
131
+ def solve_game(A) -> Tuple[np.ndarray, float]:
132
+ """
133
+ Maximise v s.t. A^T x >= v, sum(x) = 1, x >= 0.
134
+
135
+ Returns (optimal strategy x of the row player, game value v).
136
+ """
137
+ A = np.asarray(A, float)
138
+ m, n = A.shape
139
+ c = np.r_[np.zeros(m), -1] # minimise -v
140
+ A_ub = np.c_[-A.T, np.ones(n)]
141
+ b_ub = np.zeros(n)
142
+ A_eq = np.r_[np.ones(m), 0][None, :]
143
+ b_eq = [1]
144
+ res = linprog(c, A_ub=A_ub, b_ub=b_ub, A_eq=A_eq, b_eq=b_eq,
145
+ bounds=[(0, None)] * m + [(None, None)])
146
+ if not res.success:
147
+ raise RuntimeError("LP failed: " + res.message)
148
+ return res.x[:m], float(res.x[-1])
149
+
150
+
151
+ class MatrixGame:
152
+ """
153
+ Two-person zero-sum game.
154
+
155
+ Examples
156
+ --------
157
+ >>> g = MatrixGame([[3, -1], [-2, 4]])
158
+ >>> g.solve()
159
+ >>> g.display()
160
+ """
161
+
162
+ def __init__(self, payoff):
163
+ self.A = np.asarray(payoff, float)
164
+ self.result: dict | None = None
165
+
166
+ def solve(self) -> dict:
167
+ A = self.A
168
+ sp = saddle_point(A)
169
+ x, v = solve_game(A) # row player
170
+ y, negv = solve_game(-A.T) # column player (same LP on -A^T)
171
+ self.result = {"maximin": sp["maximin"], "minimax": sp["minimax"],
172
+ "has_saddle": sp["has_saddle"],
173
+ "row_strategy": x, "col_strategy": y, "value": v}
174
+ if A.shape == (2, 2) and not sp["has_saddle"]:
175
+ self.result["analytical"] = solve_2x2(A)
176
+ return self.result
177
+
178
+ def display(self) -> None:
179
+ if self.result is None:
180
+ self.solve()
181
+ r = self.result
182
+ print("Maximin =", r["maximin"], "| Minimax =", r["minimax"], "->",
183
+ "Saddle point exists" if r["has_saddle"]
184
+ else "No saddle point: use mixed strategies")
185
+ print("A's strategy :", np.round(r["row_strategy"], 3))
186
+ print("B's strategy :", np.round(r["col_strategy"], 3))
187
+ print("Value of game:", round(r["value"], 3))
188
+
189
+ def plot(self) -> None:
190
+ """Graphical solution (only for 2 x n or m x 2 games)."""
191
+ m, n = self.A.shape
192
+ if m == 2:
193
+ graph_2xn(self.A)
194
+ elif n == 2:
195
+ graph_mx2(self.A)
196
+ else:
197
+ raise ValueError("Graphical method needs 2 rows or 2 columns.")
198
+
199
+
200
+ # ----------------------------------------------------------------------
201
+ # Demo + source listing
202
+ # ----------------------------------------------------------------------
203
+ def demo(plot: bool = False) -> None:
204
+ """Run the Lab-1 examples."""
205
+ A = [[3, -1], [-2, 4]]
206
+ sp = saddle_point(A)
207
+ print("Maximin =", sp["maximin"], "| Minimax =", sp["minimax"],
208
+ "->", "Saddle point exists" if sp["has_saddle"]
209
+ else "No saddle point: use mixed strategies")
210
+ s = solve_2x2(A)
211
+ print(f"A: ({s['p']:.3f}, {1 - s['p']:.3f}) B: ({s['q']:.3f}, {1 - s['q']:.3f}) "
212
+ f"Value = {s['value']:.3f}\n")
213
+ print("2x3 game :", graph_2xn([[1, 3, 11], [8, 5, 2]], plot=plot))
214
+ print("4x2 game :", graph_mx2([[2, 4], [2, 3], [3, 2], [-2, 6]], plot=plot), "\n")
215
+ MatrixGame([[3, -1, -3], [-2, 4, -1], [-5, -6, 2]]).display()
216
+
217
+
218
+ def code() -> None:
219
+ """Print the complete source code of this module."""
220
+ print_source(sys.modules[__name__])
@@ -0,0 +1,147 @@
1
+ """
2
+ Module: gradient_methods.py
3
+ ============================
4
+ AIM:
5
+ Unconstrained NON-LINEAR optimisation with
6
+ 1. Gradient (steepest) descent - linear convergence
7
+ 2. Newton's method - quadratic convergence
8
+ 3. BFGS (quasi-Newton) - super-linear convergence
9
+ All with Armijo back-tracking line search. The default test problem
10
+ is the Rosenbrock function (minimum f = 0 at (1, 1)).
11
+
12
+ Call ``code()`` to print the complete source code of this module.
13
+ """
14
+
15
+ from __future__ import annotations
16
+ import sys
17
+ from typing import Callable, Dict, List, Optional, Tuple
18
+
19
+ import numpy as np
20
+ from scipy.optimize import minimize
21
+
22
+ from ._utils import print_source, import_pyplot, table
23
+
24
+
25
+ # ----------------------------------------------------------------------
26
+ # Rosenbrock test function
27
+ # ----------------------------------------------------------------------
28
+ def rosenbrock(x):
29
+ return (1 - x[0]) ** 2 + 100 * (x[1] - x[0] ** 2) ** 2
30
+
31
+
32
+ def rosenbrock_grad(x):
33
+ return np.array([-2 * (1 - x[0]) - 400 * x[0] * (x[1] - x[0] ** 2),
34
+ 200 * (x[1] - x[0] ** 2)])
35
+
36
+
37
+ def rosenbrock_hess(x):
38
+ return np.array([[2 - 400 * x[1] + 1200 * x[0] ** 2, -400 * x[0]],
39
+ [-400 * x[0], 200]])
40
+
41
+
42
+ # ----------------------------------------------------------------------
43
+ # Line search
44
+ # ----------------------------------------------------------------------
45
+ def backtrack(f, x, g, d, a: float = 1.0, c: float = 1e-4, rho: float = 0.5) -> float:
46
+ """Armijo back-tracking line search."""
47
+ fx, slope = f(x), g @ d
48
+ for _ in range(100):
49
+ if f(x + a * d) <= fx + c * a * slope:
50
+ break
51
+ a *= rho
52
+ return a
53
+
54
+
55
+ # ----------------------------------------------------------------------
56
+ # Solvers
57
+ # ----------------------------------------------------------------------
58
+ def gradient_descent(x0, f=rosenbrock, grad=rosenbrock_grad,
59
+ iters: int = 20000, tol: float = 1e-6):
60
+ """Steepest descent. Returns (x, history of f)."""
61
+ x = np.asarray(x0, float)
62
+ hist = [f(x)]
63
+ for _ in range(iters):
64
+ g = grad(x)
65
+ if np.linalg.norm(g) < tol:
66
+ break
67
+ d = -g
68
+ x = x + backtrack(f, x, g, d) * d
69
+ hist.append(f(x))
70
+ return x, hist
71
+
72
+
73
+ def newton(x0, f=rosenbrock, grad=rosenbrock_grad, hess=rosenbrock_hess,
74
+ iters: int = 100, tol: float = 1e-6):
75
+ """Newton's method (falls back to -grad if not a descent direction)."""
76
+ x = np.asarray(x0, float)
77
+ hist = [f(x)]
78
+ for _ in range(iters):
79
+ g = grad(x)
80
+ if np.linalg.norm(g) < tol:
81
+ break
82
+ try:
83
+ d = -np.linalg.solve(hess(x), g)
84
+ except np.linalg.LinAlgError:
85
+ d = -g
86
+ if g @ d >= 0: # safeguard: use descent direction
87
+ d = -g
88
+ x = x + backtrack(f, x, g, d) * d
89
+ hist.append(f(x))
90
+ return x, hist
91
+
92
+
93
+ def bfgs(x0, f=rosenbrock, grad=rosenbrock_grad, tol: float = 1e-6):
94
+ """Quasi-Newton BFGS via SciPy. Returns (x, history of f, result)."""
95
+ x0 = np.asarray(x0, float)
96
+ hist = [f(x0)]
97
+ res = minimize(f, x0, jac=grad, method="BFGS",
98
+ callback=lambda xk: hist.append(f(xk)),
99
+ options={"gtol": tol})
100
+ return res.x, hist, res
101
+
102
+
103
+ def compare_methods(x0=(-1.2, 1.0), f=rosenbrock, grad=rosenbrock_grad,
104
+ hess=rosenbrock_hess, f_star: float = 0.0,
105
+ plot: bool = True, verbose: bool = True) -> Dict:
106
+ """
107
+ Run all three methods from x0, print a summary and (optionally) plot
108
+ the convergence of f(x) - f*.
109
+ """
110
+ x0 = np.asarray(x0, float)
111
+ xg, hg = gradient_descent(x0, f, grad)
112
+ xn, hn = newton(x0, f, grad, hess)
113
+ xb, hb, rb = bfgs(x0, f, grad)
114
+
115
+ out = {"Gradient descent": (xg, hg), "Newton": (xn, hn),
116
+ "BFGS (quasi-Newton)": (xb, hb)}
117
+ if verbose:
118
+ rows = [[name, len(h) - 1, h[-1], np.round(x, 4).tolist()]
119
+ for name, (x, h) in out.items()]
120
+ print(table(["Method", "Iterations", "Final f(x)", "Solution"], rows,
121
+ fmt="{:.3e}"))
122
+ if plot:
123
+ plt = import_pyplot()
124
+ plt.figure(figsize=(8, 4.5))
125
+ labels = {"Gradient descent": "Gradient descent (linear)",
126
+ "Newton": "Newton (quadratic)",
127
+ "BFGS (quasi-Newton)": "BFGS (superlinear)"}
128
+ for name, (x, h) in out.items():
129
+ plt.semilogy(np.maximum(np.array(h) - f_star, 0) + 1e-20, label=labels[name])
130
+ plt.xscale("log")
131
+ plt.xlabel("Iteration (log scale)")
132
+ plt.ylabel("f(x) - f*")
133
+ plt.legend()
134
+ plt.title("Convergence comparison")
135
+ plt.grid(alpha=0.3)
136
+ plt.show()
137
+ return out
138
+
139
+
140
+ def demo(plot: bool = False) -> None:
141
+ """Run the Lab-6 example (Rosenbrock from (-1.2, 1))."""
142
+ compare_methods(plot=plot)
143
+
144
+
145
+ def code() -> None:
146
+ """Print the complete source code of this module."""
147
+ print_source(sys.modules[__name__])
@@ -0,0 +1,152 @@
1
+ """
2
+ Module: q_simul.py
3
+ ===================
4
+ AIM:
5
+ Discrete-event SIMULATION of a multi-server queue with realistic
6
+ passenger behaviour (airport check-in counters), plus cost-based
7
+ staffing optimisation.
8
+
9
+ Behaviours modelled
10
+ * finite capacity - arrival is BLOCKED if queue + in service >= cap
11
+ * balking - join probability falls as the queue grows
12
+ (balk prob = min(1, queue_length / balk_scale))
13
+ * reneging - passenger leaves after an Exp(patience) wait
14
+
15
+ Pure Python / NumPy (event-heap) - no extra dependency such as simpy.
16
+
17
+ Total cost per shift = k*cost_counter + cost_wait*(total waiting minutes)
18
+ + cost_lost*(balked + blocked + reneged)
19
+
20
+ Call ``code()`` to print the complete source code of this module.
21
+ """
22
+
23
+ from __future__ import annotations
24
+ import heapq
25
+ import sys
26
+ from collections import deque
27
+ from typing import Dict, List
28
+
29
+ import numpy as np
30
+
31
+ from ._utils import print_source, import_pyplot, table
32
+
33
+ _ARRIVE, _DEPART, _RENEGE = 0, 1, 2
34
+
35
+
36
+ def airport(k: int, lam: float = 1.0, svc_mean: float = 4.0, cap: int = 25,
37
+ patience: float = 12.0, T: float = 480.0, balk_scale: float = 20.0,
38
+ seed: int = 0) -> Dict:
39
+ """
40
+ Simulate one shift of length T minutes with k counters.
41
+
42
+ Returns dict(served, balked, blocked, reneged, wait=[...]).
43
+ """
44
+ rng = np.random.default_rng(seed)
45
+ st = dict(served=0, balked=0, blocked=0, reneged=0, wait=[])
46
+ events: list = []
47
+ seq = 0
48
+
49
+ def push(t, kind, pid=None):
50
+ nonlocal seq
51
+ heapq.heappush(events, (t, seq, kind, pid))
52
+ seq += 1
53
+
54
+ busy = 0
55
+ queue: deque = deque() # waiting passenger ids (FIFO, lazy deletion)
56
+ waiting: Dict[int, float] = {} # id -> arrival time (only genuinely waiting)
57
+ next_id = 0
58
+
59
+ push(rng.exponential(1 / lam), _ARRIVE)
60
+
61
+ while events:
62
+ t, _, kind, pid = heapq.heappop(events)
63
+ if t > T:
64
+ break
65
+
66
+ if kind == _ARRIVE:
67
+ push(t + rng.exponential(1 / lam), _ARRIVE)
68
+ qlen = len(waiting)
69
+ if qlen + busy >= cap: # finite capacity
70
+ st["blocked"] += 1
71
+ elif rng.random() < min(1.0, qlen / balk_scale): # balking
72
+ st["balked"] += 1
73
+ elif busy < k: # free counter: no wait
74
+ busy += 1
75
+ st["wait"].append(0.0)
76
+ push(t + rng.exponential(svc_mean), _DEPART)
77
+ else: # join the queue
78
+ next_id += 1
79
+ waiting[next_id] = t
80
+ queue.append(next_id)
81
+ push(t + rng.exponential(patience), _RENEGE, next_id)
82
+
83
+ elif kind == _RENEGE:
84
+ if pid in waiting: # ran out of patience
85
+ del waiting[pid]
86
+ st["reneged"] += 1
87
+
88
+ else: # _DEPART
89
+ st["served"] += 1
90
+ busy -= 1
91
+ while queue:
92
+ nid = queue.popleft()
93
+ if nid in waiting: # next live passenger
94
+ st["wait"].append(t - waiting.pop(nid))
95
+ busy += 1
96
+ push(t + rng.exponential(svc_mean), _DEPART)
97
+ break
98
+ return st
99
+
100
+
101
+ def summarise(st: Dict) -> Dict:
102
+ """Same dict but with ``wait`` replaced by its mean (rounded)."""
103
+ return {k_: (round(float(np.mean(v_)), 2) if (k_ == "wait" and v_) else
104
+ (0.0 if k_ == "wait" else v_)) for k_, v_ in st.items()}
105
+
106
+
107
+ def optimise_counters(k_range=range(2, 11), n_runs: int = 20,
108
+ cost_counter: float = 160, cost_wait: float = 0.5,
109
+ cost_lost: float = 30, plot: bool = True,
110
+ verbose: bool = True, **airport_kwargs):
111
+ """
112
+ Choose the number of counters that minimises expected total cost.
113
+
114
+ Returns (best_k, rows) with
115
+ rows = [[k, served, avg wait, lost, total cost], ...].
116
+ """
117
+ rows: List[list] = []
118
+ for k in k_range:
119
+ runs = [airport(k, seed=s, **airport_kwargs) for s in range(n_runs)]
120
+ avg = lambda f: float(np.mean([f(r) for r in runs]))
121
+ lost = avg(lambda r: r["balked"] + r["blocked"] + r["reneged"])
122
+ wait_min = avg(lambda r: sum(r["wait"]))
123
+ total = k * cost_counter + cost_wait * wait_min + cost_lost * lost
124
+ rows.append([k, avg(lambda r: r["served"]),
125
+ avg(lambda r: np.mean(r["wait"]) if r["wait"] else 0.0),
126
+ lost, total])
127
+ best = int(min(rows, key=lambda r: r[-1])[0])
128
+
129
+ if verbose:
130
+ print(table(["Counters", "Served", "Avg wait (min)", "Lost passengers",
131
+ "Total cost"], rows, fmt="{:.2f}"))
132
+ print("\nOptimal number of counters:", best)
133
+ if plot:
134
+ plt = import_pyplot()
135
+ plt.plot([r[0] for r in rows], [r[-1] for r in rows], "o-")
136
+ plt.axvline(best, color="r", ls="--")
137
+ plt.xlabel("Number of counters")
138
+ plt.ylabel("Total cost per shift")
139
+ plt.title("Staffing optimisation")
140
+ plt.show()
141
+ return best, rows
142
+
143
+
144
+ def demo(plot: bool = False) -> None:
145
+ """Run the Lab-4 examples."""
146
+ print(summarise(airport(k=5)), "\n")
147
+ optimise_counters(plot=plot)
148
+
149
+
150
+ def code() -> None:
151
+ """Print the complete source code of this module."""
152
+ print_source(sys.modules[__name__])
@@ -0,0 +1,124 @@
1
+ """
2
+ Module: q_theory.py
3
+ ====================
4
+ AIM:
5
+ Queueing THEORY and a quick Monte-Carlo check for M/M/1 and M/M/c
6
+ (M/M/k) systems.
7
+
8
+ * ``simulate_mmc`` - FCFS simulation (Poisson arrivals rate lam,
9
+ exponential service rate mu, c servers).
10
+ * ``theory_mmc`` - exact Erlang-C formulas (c = 1 gives M/M/1).
11
+ * ``compare_mmc`` - side-by-side table of simulation vs theory.
12
+ * ``utilisation_sweep`` - effect of utilisation rho on waiting time.
13
+
14
+ Little's law: Lq = lam * Wq, L = lam * W, W = Wq + 1/mu
15
+
16
+ Call ``code()`` to print the complete source code of this module.
17
+ """
18
+
19
+ from __future__ import annotations
20
+ import heapq
21
+ import sys
22
+ from math import factorial
23
+ from typing import Iterable, List, Tuple
24
+
25
+ import numpy as np
26
+
27
+ from ._utils import print_source, import_pyplot, table
28
+
29
+
30
+ def simulate_mmc(lam: float, mu: float, c: int, n: int = 100000,
31
+ seed: int = 0) -> Tuple[float, float, float, float]:
32
+ """
33
+ FCFS queue, Poisson arrivals (rate lam), exponential service (rate mu),
34
+ c servers.
35
+
36
+ Returns (Wq, Lq, W, L).
37
+ """
38
+ rng = np.random.default_rng(seed)
39
+ arrival = np.cumsum(rng.exponential(1 / lam, n))
40
+ service = rng.exponential(1 / mu, n)
41
+
42
+ free = [0.0] * c # time when each server becomes free
43
+ wait = np.empty(n)
44
+ for i in range(n):
45
+ s = heapq.heappop(free) # earliest available server
46
+ start = max(arrival[i], s)
47
+ wait[i] = start - arrival[i]
48
+ heapq.heappush(free, start + service[i])
49
+
50
+ Wq = float(wait.mean())
51
+ Lq = lam * Wq # Little's law
52
+ return Wq, Lq, Wq + 1 / mu, lam * (Wq + 1 / mu)
53
+
54
+
55
+ def theory_mmc(lam: float, mu: float, c: int) -> Tuple[float, float, float, float]:
56
+ """
57
+ Erlang-C formulas (c = 1 gives M/M/1). Requires rho = lam/(c*mu) < 1.
58
+
59
+ Returns (Wq, Lq, W, L).
60
+ """
61
+ a = lam / mu
62
+ rho = a / c
63
+ if rho >= 1:
64
+ raise ValueError(f"Unstable queue: rho = {rho:.3f} >= 1.")
65
+ top = (a ** c) / factorial(c) / (1 - rho)
66
+ Pw = top / (sum((a ** k) / factorial(k) for k in range(c)) + top) # P(wait)
67
+ Lq = Pw * rho / (1 - rho)
68
+ Wq = Lq / lam
69
+ return Wq, Lq, Wq + 1 / mu, lam * (Wq + 1 / mu)
70
+
71
+
72
+ def compare_mmc(systems=None, n: int = 100000, seed: int = 0,
73
+ verbose: bool = True) -> List[list]:
74
+ """
75
+ Simulation vs theory for a list of (name, lam, mu, c).
76
+ Defaults to the Lab-2 systems M/M/1, M/M/2, M/M/3.
77
+ """
78
+ if systems is None:
79
+ systems = [("M/M/1", 8, 10, 1), ("M/M/2", 16, 10, 2), ("M/M/3", 24, 10, 3)]
80
+ rows = []
81
+ for name, lam, mu, c in systems:
82
+ sim = simulate_mmc(lam, mu, c, n=n, seed=seed)
83
+ th = theory_mmc(lam, mu, c)
84
+ rows.append([name, lam, mu, c, lam / (c * mu), *sim, *th])
85
+ if verbose:
86
+ cols = ["Model", "lambda", "mu", "k", "rho",
87
+ "Wq sim", "Lq sim", "W sim", "L sim",
88
+ "Wq theory", "Lq theory", "W theory", "L theory"]
89
+ print(table(cols, rows))
90
+ return rows
91
+
92
+
93
+ def utilisation_sweep(mu: float = 10.0, rhos: Iterable[float] = None,
94
+ n: int = 50000, plot: bool = True):
95
+ """
96
+ M/M/1 waiting time vs utilisation (simulation and theory).
97
+
98
+ Returns (rhos, Wq_sim, Wq_theory).
99
+ """
100
+ rhos = np.arange(0.1, 0.96, 0.05) if rhos is None else np.asarray(list(rhos), float)
101
+ sim = [simulate_mmc(r * mu, mu, 1, n=n)[0] for r in rhos]
102
+ th = [theory_mmc(r * mu, mu, 1)[0] for r in rhos]
103
+ if plot:
104
+ plt = import_pyplot()
105
+ plt.plot(rhos, sim, "o", label="Simulation")
106
+ plt.plot(rhos, th, "-", label="Theory")
107
+ plt.xlabel("Utilisation (rho)")
108
+ plt.ylabel("Average wait Wq")
109
+ plt.legend()
110
+ plt.title("M/M/1: waiting time vs load")
111
+ plt.show()
112
+ return rhos, sim, th
113
+
114
+
115
+ def demo(plot: bool = False) -> None:
116
+ """Run the Lab-2 examples."""
117
+ compare_mmc()
118
+ if plot:
119
+ utilisation_sweep()
120
+
121
+
122
+ def code() -> None:
123
+ """Print the complete source code of this module."""
124
+ print_source(sys.modules[__name__])
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "PyOR"
7
- version = "1.0.0"
7
+ version = "1.1.1"
8
8
  description = "Python Operations Research — LP, Simplex, Transportation, Assignment, PERT/CPM, Curve Fitting & more"
9
9
  readme = "README.md"
10
10
  license = { file = "LICENSE" }
@@ -13,7 +13,8 @@ authors = [{ name = "PyOR Contributors" }]
13
13
  keywords = [
14
14
  "operations research", "linear programming", "simplex",
15
15
  "transportation", "assignment", "PERT", "CPM",
16
- "curve fitting", "spline", "optimization"
16
+ "curve fitting", "spline", "optimization",
17
+ "game theory", "queueing", "simulation", "dynamic programming", "gradient descent"
17
18
  ]
18
19
  classifiers = [
19
20
  "Development Status :: 4 - Beta",
@@ -7,7 +7,7 @@ from setuptools import setup, find_packages
7
7
 
8
8
  setup(
9
9
  name = "PyOR",
10
- version = "1.0.0",
10
+ version = "1.1.1",
11
11
  packages = find_packages(),
12
12
  python_requires = ">=3.8",
13
13
  install_requires = [
@@ -0,0 +1,54 @@
1
+ import numpy as np, pytest, matplotlib
2
+ matplotlib.use("Agg")
3
+ import pyOR
4
+ from pyOR import game_theory as gt, q_theory as qt, q_simul as qs
5
+ from pyOR import gradient_methods as gm, dynamic_programming as dp
6
+
7
+
8
+ def test_version():
9
+ assert pyOR.__version__ == "1.1.1"
10
+
11
+ def test_game_2x2():
12
+ s = gt.solve_2x2([[3, -1], [-2, 4]])
13
+ x, v = gt.solve_game([[3, -1], [-2, 4]])
14
+ assert np.isclose(v, s["value"]) and np.isclose(x[0], s["p"])
15
+
16
+ def test_game_lp():
17
+ G = [[3, -1, -3], [-2, 4, -1], [-5, -6, 2]]
18
+ g = gt.MatrixGame(G); r = g.solve()
19
+ assert np.isclose(r["row_strategy"].sum(), 1)
20
+ assert np.isclose(r["value"], -r["value"] * 0 + r["value"])
21
+ assert np.isclose(gt.solve_game(-np.array(G).T)[1], -r["value"])
22
+
23
+ def test_graphical():
24
+ p, v = gt.graph_2xn([[3, -1], [-2, 4]], plot=False)
25
+ assert abs(v - gt.solve_2x2([[3, -1], [-2, 4]])["value"]) < 0.05
26
+
27
+ def test_qtheory():
28
+ sim = qt.simulate_mmc(8, 10, 1, n=200000)
29
+ th = qt.theory_mmc(8, 10, 1)
30
+ assert abs(sim[0] - th[0]) / th[0] < 0.1
31
+ assert np.isclose(th[0], 0.4)
32
+ with pytest.raises(ValueError):
33
+ qt.theory_mmc(10, 10, 1)
34
+
35
+ def test_qsimul():
36
+ st = qs.airport(5)
37
+ assert st["served"] > 0 and len(st["wait"]) >= st["served"]
38
+ best, rows = qs.optimise_counters(range(2, 6), n_runs=3, plot=False, verbose=False)
39
+ assert best in range(2, 6)
40
+
41
+ def test_gradient():
42
+ out = gm.compare_methods(plot=False, verbose=False)
43
+ for name, (x, h) in out.items():
44
+ assert np.allclose(x, [1, 1], atol=1e-2), name
45
+
46
+ def test_dp():
47
+ d = dp.ResourceAllocationDP(); d.solve()
48
+ assert d.max_return() == d.brute_force()[0]
49
+ assert sum(d.allocation()) == 6
50
+
51
+ def test_code(capsys):
52
+ for n in ["game_theory", "q_theory", "q_simul", "gradient_methods", "dynamic_programming"]:
53
+ pyOR.code(n)
54
+ assert "def code" in capsys.readouterr().out
@@ -1,55 +0,0 @@
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"
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes