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/simplex.py ADDED
@@ -0,0 +1,248 @@
1
+ """
2
+ Module: simplex.py
3
+ ===================
4
+ AIM:
5
+ To solve a Linear Programming Problem using the standard Simplex Method
6
+ (primal simplex with full tableau bookkeeping).
7
+
8
+ Handles:
9
+ - Maximisation and Minimisation
10
+ - <= constraints (introduces slack variables)
11
+ - Cycling prevention via Bland's rule (optional)
12
+ - Degeneracy detection
13
+ - Infeasible / Unbounded detection
14
+ - Full tableau display at each iteration
15
+
16
+ Note:
17
+ For >= or = constraints, use BigMMethod or DualSimplex instead.
18
+ SimplexMethod expects a problem already in standard maximisation
19
+ form (all constraints <=, all RHS >= 0, all variables >= 0).
20
+ """
21
+
22
+ from __future__ import annotations
23
+ import numpy as np
24
+ from typing import List, Optional, Tuple
25
+
26
+
27
+ class SimplexMethod:
28
+ """
29
+ Primal Simplex Method with full tableau.
30
+
31
+ Parameters
32
+ ----------
33
+ c : Objective coefficients (maximise c·x by default).
34
+ A : Constraint matrix (each row is one <= constraint).
35
+ b : RHS vector (must be >= 0).
36
+ objective : 'max' (default) or 'min'.
37
+ var_names : Optional list of variable names.
38
+ blands_rule: Use Bland's rule to avoid cycling (default True).
39
+
40
+ Examples
41
+ --------
42
+ >>> sm = SimplexMethod(
43
+ ... c = [5, 4, 3],
44
+ ... A = [[6, 4, 2], [3, 2, 5], [5, 6, 5]],
45
+ ... b = [240, 270, 420],
46
+ ... objective='max'
47
+ ... )
48
+ >>> result = sm.solve()
49
+ >>> sm.display()
50
+ """
51
+
52
+ def __init__(
53
+ self,
54
+ c: List[float],
55
+ A: List[List[float]],
56
+ b: List[float],
57
+ objective: str = "max",
58
+ var_names: Optional[List[str]] = None,
59
+ blands_rule: bool = True,
60
+ ):
61
+ self.objective = objective.lower()
62
+ self.A_orig = np.array(A, dtype=float)
63
+ self.b_orig = np.array(b, dtype=float)
64
+ self.blands = blands_rule
65
+
66
+ m, n = self.A_orig.shape
67
+ if len(b) != m:
68
+ raise ValueError("Rows of A must equal length of b.")
69
+ if any(self.b_orig < 0):
70
+ raise ValueError("All RHS values (b) must be >= 0 for standard "
71
+ "Simplex. Use BigMMethod for >= constraints.")
72
+
73
+ self.m = m
74
+ self.n = n
75
+
76
+ # Convert minimisation → maximisation
77
+ c_arr = np.array(c, dtype=float)
78
+ if self.objective == "min":
79
+ self.c_internal = -c_arr
80
+ else:
81
+ self.c_internal = c_arr.copy()
82
+ self.c_orig = c_arr
83
+
84
+ # Variable names
85
+ if var_names:
86
+ self.var_names = var_names + [f"s{i+1}" for i in range(m)]
87
+ else:
88
+ self.var_names = ([f"x{i+1}" for i in range(n)]
89
+ + [f"s{i+1}" for i in range(m)])
90
+
91
+ self.result = None
92
+ self.tableau_log = []
93
+
94
+ # ------------------------------------------------------------------
95
+ def _build_initial_tableau(self) -> np.ndarray:
96
+ """
97
+ Build the initial simplex tableau.
98
+ Rows : m constraints + 1 objective row (last row).
99
+ Cols : n original vars + m slack vars + 1 RHS.
100
+ """
101
+ m, n = self.m, self.n
102
+ # [A | I | b]
103
+ T = np.zeros((m + 1, n + m + 1), dtype=float)
104
+ T[:m, :n] = self.A_orig
105
+ T[:m, n:n+m] = np.eye(m)
106
+ T[:m, -1] = self.b_orig
107
+ # Objective row (negative of c for maximisation, to use z-row form)
108
+ T[m, :n] = -self.c_internal
109
+ return T
110
+
111
+ # ------------------------------------------------------------------
112
+ def _pivot(self, T: np.ndarray, row: int, col: int) -> np.ndarray:
113
+ """Perform a pivot operation on tableau T."""
114
+ T = T.copy()
115
+ pivot = T[row, col]
116
+ T[row, :] /= pivot
117
+ for i in range(T.shape[0]):
118
+ if i != row:
119
+ T[i, :] -= T[i, col] * T[row, :]
120
+ return T
121
+
122
+ # ------------------------------------------------------------------
123
+ def solve(self, max_iter: int = 500) -> dict:
124
+ """
125
+ Run the simplex algorithm.
126
+
127
+ Returns
128
+ -------
129
+ dict with keys:
130
+ status : 'Optimal' | 'Unbounded' | 'Max iterations reached'
131
+ x : Solution vector (original vars)
132
+ obj_value : Optimal Z
133
+ iterations : Number of pivot steps
134
+ tableau : Final tableau
135
+ """
136
+ T = self._build_initial_tableau()
137
+ m, n = self.m, self.n
138
+ # Basis: initially slack variables
139
+ basis = list(range(n, n + m))
140
+
141
+ for iteration in range(max_iter):
142
+ self.tableau_log.append((T.copy(), basis.copy()))
143
+
144
+ obj_row = T[-1, :-1]
145
+ # --- Optimality check ---
146
+ if all(obj_row >= -1e-9):
147
+ break
148
+
149
+ # --- Select entering variable ---
150
+ if self.blands:
151
+ # Bland's rule: smallest index with negative reduced cost
152
+ col = int(np.argmax(obj_row < -1e-9))
153
+ else:
154
+ col = int(np.argmin(obj_row))
155
+
156
+ # --- Unboundedness check ---
157
+ ratios = []
158
+ for i in range(m):
159
+ if T[i, col] > 1e-9:
160
+ ratios.append((T[i, -1] / T[i, col], i))
161
+ if not ratios:
162
+ self.result = {
163
+ "status" : "Unbounded",
164
+ "x" : None,
165
+ "obj_value" : None,
166
+ "iterations": iteration,
167
+ "tableau" : T,
168
+ }
169
+ return self.result
170
+
171
+ # --- Select leaving variable (min ratio, Bland's for tie-break) ---
172
+ ratios.sort(key=lambda x: (round(x[0], 8), x[1]))
173
+ row = ratios[0][1]
174
+
175
+ basis[row] = col
176
+ T = self._pivot(T, row, col)
177
+
178
+ else:
179
+ self.result = {
180
+ "status" : "Max iterations reached",
181
+ "x" : None,
182
+ "obj_value" : None,
183
+ "iterations": max_iter,
184
+ "tableau" : T,
185
+ }
186
+ return self.result
187
+
188
+ # Extract solution
189
+ total_vars = n + m
190
+ x_full = np.zeros(total_vars)
191
+ for i, b in enumerate(basis):
192
+ x_full[b] = T[i, -1]
193
+
194
+ x_orig = x_full[:n]
195
+ z_internal = float(T[-1, -1])
196
+ z = z_internal if self.objective == "max" else -z_internal
197
+
198
+ self.result = {
199
+ "status" : "Optimal",
200
+ "x" : x_orig,
201
+ "slack" : x_full[n:],
202
+ "obj_value" : z,
203
+ "iterations": len(self.tableau_log),
204
+ "tableau" : T,
205
+ "basis" : basis,
206
+ }
207
+ return self.result
208
+
209
+ # ------------------------------------------------------------------
210
+ def display(self, show_tableaux: bool = False) -> None:
211
+ """Display solution and optionally all intermediate tableaux."""
212
+ if self.result is None:
213
+ self.solve()
214
+ r = self.result
215
+ print("=" * 55)
216
+ print(" Simplex Method Solution")
217
+ print("=" * 55)
218
+ print(f" Objective : {self.objective}imise Z = "
219
+ + " + ".join(f"{self.c_orig[i]:g}·{self.var_names[i]}"
220
+ for i in range(self.n)))
221
+ print(f" Status : {r['status']}")
222
+ if r["x"] is not None:
223
+ for i, xi in enumerate(r["x"]):
224
+ print(f" {self.var_names[i]:<10} = {xi:.6g}")
225
+ print(f" Z* = {r['obj_value']:.6g}")
226
+ print(f" Iterations: {r['iterations']}")
227
+ print("=" * 55)
228
+
229
+ if show_tableaux:
230
+ for it, (T, basis) in enumerate(self.tableau_log):
231
+ print(f"\n--- Iteration {it} ---")
232
+ self._print_tableau(T, basis)
233
+
234
+ # ------------------------------------------------------------------
235
+ def _print_tableau(self, T: np.ndarray, basis: List[int]) -> None:
236
+ """Print a single tableau."""
237
+ headers = self.var_names + ["RHS"]
238
+ col_w = 10
239
+ print(" Basis | " + " ".join(f"{h:>{col_w}}" for h in headers))
240
+ print(" " + "-" * (12 + col_w * len(headers)))
241
+ for i, b in enumerate(basis):
242
+ bname = self.var_names[b] if b < len(self.var_names) else f"?{b}"
243
+ row_str = " ".join(f"{T[i,j]:>{col_w}.4f}"
244
+ for j in range(T.shape[1]))
245
+ print(f" {bname:<10}| {row_str}")
246
+ row_str = " ".join(f"{T[-1,j]:>{col_w}.4f}"
247
+ for j in range(T.shape[1]))
248
+ print(f" {'Z':<10}| {row_str}")
pyOR/spline_fitting.py ADDED
@@ -0,0 +1,306 @@
1
+ """
2
+ Module: spline_fitting.py
3
+ ==========================
4
+ AIM:
5
+ To fit and evaluate a Cubic Spline interpolation to a given set of
6
+ data points.
7
+
8
+ A cubic spline is a piecewise polynomial of degree 3 that:
9
+ - Passes exactly through each data point (interpolation).
10
+ - Has continuous first and second derivatives at each interior
11
+ knot (smooth joints).
12
+
13
+ Boundary conditions supported:
14
+ 'natural' : Second derivative = 0 at endpoints (free ends).
15
+ 'clamped' : First derivative specified at endpoints.
16
+ 'not-a-knot': Third derivative is continuous at second and
17
+ second-to-last knots (scipy default).
18
+ 'periodic' : For periodic functions (y[0] = y[-1] required).
19
+
20
+ Features:
21
+ - Manual derivation of spline coefficients (natural spline) for
22
+ educational display.
23
+ - scipy CubicSpline integration for all boundary conditions.
24
+ - Evaluation at arbitrary x values.
25
+ - First and second derivative evaluation.
26
+ - Optional plot.
27
+ - Data validation (monotone x, duplicate detection).
28
+ """
29
+
30
+ from __future__ import annotations
31
+ import numpy as np
32
+ from typing import List, Optional, Union
33
+ import warnings
34
+
35
+
36
+ class CubicSplineFitter:
37
+ """
38
+ Cubic Spline interpolation with full coefficient display.
39
+
40
+ Parameters
41
+ ----------
42
+ x : Sorted x-values (must be strictly increasing).
43
+ y : Corresponding y-values.
44
+ bc_type : Boundary condition.
45
+ 'natural' | 'clamped' | 'not-a-knot' | 'periodic'
46
+ (default 'natural').
47
+ clamped_slopes : (dy/dx at x[0], dy/dx at x[-1]) — required for
48
+ bc_type='clamped'.
49
+
50
+ Examples
51
+ --------
52
+ >>> sf = CubicSplineFitter(
53
+ ... x=[0, 1, 2, 3, 4],
54
+ ... y=[0, 1, 0, 1, 0],
55
+ ... bc_type='natural'
56
+ ... )
57
+ >>> sf.fit()
58
+ >>> print(sf.evaluate(1.5))
59
+ >>> sf.display()
60
+ >>> sf.plot()
61
+
62
+ >>> # Evaluate derivative
63
+ >>> print(sf.derivative(2.0))
64
+ """
65
+
66
+ def __init__(
67
+ self,
68
+ x: List[float],
69
+ y: List[float],
70
+ bc_type: str = "natural",
71
+ clamped_slopes: Optional[tuple] = None,
72
+ ):
73
+ self.x_raw = np.array(x, dtype=float)
74
+ self.y_raw = np.array(y, dtype=float)
75
+
76
+ if len(self.x_raw) != len(self.y_raw):
77
+ raise ValueError("x and y must have the same length.")
78
+ if len(self.x_raw) < 2:
79
+ raise ValueError("At least 2 points required.")
80
+
81
+ # Sort by x
82
+ order = np.argsort(self.x_raw)
83
+ self.x = self.x_raw[order]
84
+ self.y = self.y_raw[order]
85
+
86
+ # Check strictly increasing
87
+ if np.any(np.diff(self.x) <= 0):
88
+ raise ValueError("x values must be strictly increasing (no duplicates).")
89
+
90
+ self.bc_type = bc_type.lower()
91
+ self.clamped_slopes = clamped_slopes
92
+ self._spline = None # scipy CubicSpline object
93
+ self._manual_coeffs = None # for natural spline display
94
+ self.result = None
95
+
96
+ # ------------------------------------------------------------------
97
+ def fit(self) -> dict:
98
+ """
99
+ Fit the cubic spline.
100
+
101
+ Returns
102
+ -------
103
+ dict with keys:
104
+ n_intervals : Number of polynomial intervals
105
+ coefficients : List of (a, b, c, d) per interval where
106
+ S_i(x) = a + b*(x-xi) + c*(x-xi)^2 + d*(x-xi)^3
107
+ breakpoints : x-values at interval boundaries
108
+ """
109
+ from scipy.interpolate import CubicSpline
110
+
111
+ x, y = self.x, self.y
112
+ n = len(x)
113
+
114
+ # --- Build scipy spline (handles all bc_types) ---
115
+ if self.bc_type == "natural":
116
+ bc = ((2, 0.0), (2, 0.0)) # second derivatives = 0 at ends
117
+ elif self.bc_type == "clamped":
118
+ if self.clamped_slopes is None:
119
+ raise ValueError("clamped_slopes=(f'(x0), f'(xn)) required.")
120
+ bc = ((1, self.clamped_slopes[0]), (1, self.clamped_slopes[1]))
121
+ elif self.bc_type == "not-a-knot":
122
+ bc = "not-a-knot"
123
+ elif self.bc_type == "periodic":
124
+ if abs(y[0] - y[-1]) > 1e-10:
125
+ warnings.warn("y[0] ≠ y[-1] — adjusting for periodic bc.")
126
+ bc = "periodic"
127
+ else:
128
+ raise ValueError(f"Unknown bc_type '{self.bc_type}'. Choose from "
129
+ "'natural', 'clamped', 'not-a-knot', 'periodic'.")
130
+
131
+ self._spline = CubicSpline(x, y, bc_type=bc)
132
+
133
+ # --- Extract coefficients in (a, b, c, d) form ---
134
+ # scipy stores as c[k, i] for degree k at interval i (descending)
135
+ c = self._spline.c # shape (4, n-1), highest degree first
136
+ intervals = []
137
+ for i in range(n - 1):
138
+ # scipy: S_i(t) = c[0,i]*t^3 + c[1,i]*t^2 + c[2,i]*t + c[3,i]
139
+ # where t = x - x[i]
140
+ d_coef = c[0, i]
141
+ c_coef = c[1, i]
142
+ b_coef = c[2, i]
143
+ a_coef = c[3, i]
144
+ intervals.append({
145
+ "xi" : float(x[i]),
146
+ "xi1" : float(x[i + 1]),
147
+ "a" : float(a_coef),
148
+ "b" : float(b_coef),
149
+ "c" : float(c_coef),
150
+ "d" : float(d_coef),
151
+ })
152
+
153
+ # --- Natural spline manual coefficients (for display) ---
154
+ if self.bc_type == "natural":
155
+ self._manual_coeffs = self._compute_natural_spline(x, y)
156
+
157
+ self.result = {
158
+ "n_intervals" : n - 1,
159
+ "coefficients" : intervals,
160
+ "breakpoints" : x.tolist(),
161
+ "bc_type" : self.bc_type,
162
+ }
163
+ return self.result
164
+
165
+ # ------------------------------------------------------------------
166
+ def _compute_natural_spline(self, x: np.ndarray,
167
+ y: np.ndarray) -> np.ndarray:
168
+ """
169
+ Manually compute natural cubic spline second derivatives (M values)
170
+ by solving the tridiagonal system. Returns array M of length n.
171
+ """
172
+ n = len(x)
173
+ h = np.diff(x)
174
+
175
+ # Build tridiagonal matrix for M (interior nodes 1..n-2)
176
+ ni = n - 2 # interior nodes
177
+ if ni <= 0:
178
+ return np.zeros(n)
179
+
180
+ diag = 2 * (h[:-1] + h[1:])
181
+ upper = h[1:-1].copy()
182
+ lower = h[1:-1].copy()
183
+ rhs = 6 * (np.diff(y)[1:] / h[1:] - np.diff(y)[:-1] / h[:-1])
184
+
185
+ # Solve tridiagonal using Thomas algorithm
186
+ M_int = self._thomas(lower, diag, upper, rhs)
187
+ M = np.zeros(n)
188
+ M[1:-1] = M_int
189
+ return M
190
+
191
+ # ------------------------------------------------------------------
192
+ @staticmethod
193
+ def _thomas(lower: np.ndarray, diag: np.ndarray,
194
+ upper: np.ndarray, rhs: np.ndarray) -> np.ndarray:
195
+ """Thomas algorithm for tridiagonal systems."""
196
+ n = len(diag)
197
+ c = upper.copy()
198
+ d = rhs.copy()
199
+ a = lower.copy()
200
+ w = diag.copy()
201
+
202
+ for i in range(1, n):
203
+ factor = a[i - 1] / w[i - 1]
204
+ w[i] -= factor * c[i - 1]
205
+ d[i] -= factor * d[i - 1]
206
+
207
+ x = np.zeros(n)
208
+ x[-1] = d[-1] / w[-1]
209
+ for i in range(n - 2, -1, -1):
210
+ x[i] = (d[i] - c[i] * x[i + 1]) / w[i]
211
+ return x
212
+
213
+ # ------------------------------------------------------------------
214
+ def evaluate(self, x_new: Union[float, List[float]],
215
+ extrapolate: bool = False) -> np.ndarray:
216
+ """
217
+ Evaluate the spline at new x values.
218
+
219
+ Parameters
220
+ ----------
221
+ x_new : Scalar or array of x values.
222
+ extrapolate : Allow extrapolation beyond data range.
223
+
224
+ Returns
225
+ -------
226
+ np.ndarray of interpolated y values.
227
+ """
228
+ if self._spline is None:
229
+ raise RuntimeError("Call .fit() first.")
230
+ x_new = np.atleast_1d(np.array(x_new, dtype=float))
231
+ if not extrapolate:
232
+ out_of_range = (x_new < self.x[0]) | (x_new > self.x[-1])
233
+ if np.any(out_of_range):
234
+ warnings.warn(
235
+ "Some x values are outside the data range. "
236
+ "Set extrapolate=True to allow extrapolation."
237
+ )
238
+ return self._spline(x_new, extrapolate=extrapolate)
239
+
240
+ # ------------------------------------------------------------------
241
+ def derivative(self, x_new: Union[float, List[float]],
242
+ order: int = 1) -> np.ndarray:
243
+ """
244
+ Evaluate the n-th derivative of the spline.
245
+
246
+ Parameters
247
+ ----------
248
+ x_new : x value(s).
249
+ order : Derivative order (1 or 2).
250
+ """
251
+ if self._spline is None:
252
+ raise RuntimeError("Call .fit() first.")
253
+ x_new = np.atleast_1d(np.array(x_new, dtype=float))
254
+ return self._spline(x_new, nu=order)
255
+
256
+ # ------------------------------------------------------------------
257
+ def display(self) -> None:
258
+ """Display spline coefficients for each interval."""
259
+ if self.result is None:
260
+ raise RuntimeError("Call .fit() first.")
261
+ r = self.result
262
+ print("=" * 75)
263
+ print(f" Cubic Spline Fitting [BC: {r['bc_type']}]")
264
+ print(" S_i(x) = a + b·(x-xᵢ) + c·(x-xᵢ)² + d·(x-xᵢ)³")
265
+ print("=" * 75)
266
+ print(f" {'Interval':<20} {'a':>12} {'b':>12} {'c':>12} {'d':>12}")
267
+ print(" " + "-" * 70)
268
+ for iv in r["coefficients"]:
269
+ label = f"[{iv['xi']:.4g}, {iv['xi1']:.4g}]"
270
+ print(f" {label:<20} {iv['a']:>12.6g} {iv['b']:>12.6g} "
271
+ f"{iv['c']:>12.6g} {iv['d']:>12.6g}")
272
+ print("=" * 75)
273
+
274
+ if self._manual_coeffs is not None:
275
+ print(" Natural Spline — Second Derivatives M:")
276
+ for i, m in enumerate(self._manual_coeffs):
277
+ print(f" M[{i}] = {m:.8g}")
278
+ print("=" * 75)
279
+
280
+ # ------------------------------------------------------------------
281
+ def plot(self, save_path: Optional[str] = None,
282
+ n_points: int = 500) -> None:
283
+ """Plot data points and the fitted cubic spline."""
284
+ try:
285
+ import matplotlib.pyplot as plt
286
+ except ImportError:
287
+ warnings.warn("matplotlib required for plotting.")
288
+ return
289
+
290
+ if self._spline is None:
291
+ raise RuntimeError("Call .fit() first.")
292
+
293
+ x_plot = np.linspace(self.x[0], self.x[-1], n_points)
294
+ y_plot = self._spline(x_plot)
295
+
296
+ fig, ax = plt.subplots(figsize=(8, 5))
297
+ ax.plot(x_plot, y_plot, color="steelblue", lw=2, label="Cubic Spline")
298
+ ax.scatter(self.x, self.y, color="tomato", s=60, zorder=5,
299
+ label="Data Points")
300
+ ax.set_xlabel("x"); ax.set_ylabel("y")
301
+ ax.set_title(f"Cubic Spline Interpolation (BC: {self.bc_type})")
302
+ ax.legend(); ax.grid(True, alpha=0.3)
303
+ plt.tight_layout()
304
+ if save_path:
305
+ plt.savefig(save_path, dpi=150)
306
+ plt.show()