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/curve_fitting.py ADDED
@@ -0,0 +1,339 @@
1
+ """
2
+ Module: curve_fitting.py
3
+ =========================
4
+ AIM:
5
+ To fit mathematical curves to given data points using the Method of
6
+ Least Squares. The method minimises the sum of squared residuals
7
+ between observed y-values and those predicted by the model.
8
+
9
+ Supported models:
10
+ 'linear' : y = a + b*x
11
+ 'polynomial' : y = a0 + a1*x + a2*x² + ... + an*x^n
12
+ 'exponential' : y = a * e^(b*x) (linearised: ln y = ln a + b*x)
13
+ 'power' : y = a * x^b (linearised: ln y = ln a + b*ln x)
14
+ 'logarithmic' : y = a + b * ln(x)
15
+ 'reciprocal' : y = a + b/x
16
+
17
+ For each fit the module computes:
18
+ - Fitted coefficients
19
+ - Sum of Squared Residuals (SSR)
20
+ - R-squared (coefficient of determination)
21
+ - Standard errors of coefficients (where applicable)
22
+ - Optional plot
23
+
24
+ Handles:
25
+ - Negative / zero values in x or y for linearised models (warns).
26
+ - Ill-conditioned systems.
27
+ - Arbitrary polynomial degree.
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 CurveFitter:
37
+ """
38
+ Fit a curve to data using the least-squares method.
39
+
40
+ Parameters
41
+ ----------
42
+ x : Independent variable data.
43
+ y : Dependent variable data.
44
+
45
+ Examples
46
+ --------
47
+ >>> cf = CurveFitter(x=[1, 2, 3, 4, 5],
48
+ ... y=[2.1, 4.0, 6.2, 7.9, 9.8])
49
+ >>> result = cf.fit('linear')
50
+ >>> cf.display()
51
+ >>> cf.plot()
52
+
53
+ >>> # Polynomial degree 2
54
+ >>> result = cf.fit('polynomial', degree=2)
55
+ >>> cf.display()
56
+ """
57
+
58
+ def __init__(self, x: List[float], y: List[float]):
59
+ self.x = np.array(x, dtype=float)
60
+ self.y = np.array(y, dtype=float)
61
+ if len(self.x) != len(self.y):
62
+ raise ValueError("x and y must have the same length.")
63
+ if len(self.x) < 2:
64
+ raise ValueError("At least 2 data points are required.")
65
+ self.model = None
66
+ self.result = None
67
+
68
+ # ------------------------------------------------------------------
69
+ def _r_squared(self, y_pred: np.ndarray) -> float:
70
+ ss_res = np.sum((self.y - y_pred) ** 2)
71
+ ss_tot = np.sum((self.y - self.y.mean()) ** 2)
72
+ return 1 - ss_res / ss_tot if ss_tot > 1e-14 else 1.0
73
+
74
+ # ------------------------------------------------------------------
75
+ def fit(self, model: str = "linear", degree: int = 2,
76
+ **kwargs) -> dict:
77
+ """
78
+ Fit data to the specified model.
79
+
80
+ Parameters
81
+ ----------
82
+ model : One of 'linear', 'polynomial', 'exponential',
83
+ 'power', 'logarithmic', 'reciprocal'.
84
+ degree : Polynomial degree (only for model='polynomial').
85
+
86
+ Returns
87
+ -------
88
+ dict with keys:
89
+ model : model name
90
+ coefficients: fitted coefficients
91
+ equation : equation string
92
+ ssr : Sum of Squared Residuals
93
+ r_squared : R² value
94
+ y_pred : Predicted y values at input x
95
+ """
96
+ self.model = model.lower()
97
+ dispatch = {
98
+ "linear" : self._fit_linear,
99
+ "polynomial" : lambda: self._fit_polynomial(degree),
100
+ "exponential": self._fit_exponential,
101
+ "power" : self._fit_power,
102
+ "logarithmic": self._fit_logarithmic,
103
+ "reciprocal" : self._fit_reciprocal,
104
+ }
105
+ if self.model not in dispatch:
106
+ raise ValueError(f"Unknown model '{model}'. Choose from: "
107
+ + str(list(dispatch.keys())))
108
+ self.result = dispatch[self.model]()
109
+ return self.result
110
+
111
+ # ------------------------------------------------------------------
112
+ def _least_squares(self, A: np.ndarray, b: np.ndarray) -> np.ndarray:
113
+ """Solve normal equations A·coeffs = b using lstsq."""
114
+ coeffs, _, _, _ = np.linalg.lstsq(A, b, rcond=None)
115
+ return coeffs
116
+
117
+ # ------------------------------------------------------------------
118
+ def _fit_linear(self) -> dict:
119
+ n = len(self.x)
120
+ A = np.column_stack([np.ones(n), self.x])
121
+ coeffs = self._least_squares(A, self.y)
122
+ a, b = coeffs
123
+ y_pred = a + b * self.x
124
+ ssr = float(np.sum((self.y - y_pred) ** 2))
125
+ return {
126
+ "model" : "linear",
127
+ "coefficients": {"a": a, "b": b},
128
+ "equation" : f"y = {a:.6g} + {b:.6g}·x",
129
+ "ssr" : ssr,
130
+ "r_squared" : self._r_squared(y_pred),
131
+ "y_pred" : y_pred,
132
+ "coeffs_array": np.array([a, b]),
133
+ }
134
+
135
+ # ------------------------------------------------------------------
136
+ def _fit_polynomial(self, degree: int) -> dict:
137
+ n = len(self.x)
138
+ if degree >= n:
139
+ warnings.warn(f"Polynomial degree {degree} >= number of data "
140
+ f"points {n}. Reducing to {n-1}.")
141
+ degree = n - 1
142
+ coeffs = np.polyfit(self.x, self.y, degree) # highest degree first
143
+ poly = np.poly1d(coeffs)
144
+ y_pred = poly(self.x)
145
+ ssr = float(np.sum((self.y - y_pred) ** 2))
146
+ coeffs_rev = coeffs[::-1] # from a0 to an
147
+ terms = " + ".join(f"{coeffs_rev[i]:.4g}·x^{i}" if i > 0
148
+ else f"{coeffs_rev[0]:.4g}"
149
+ for i in range(degree + 1))
150
+ return {
151
+ "model" : f"polynomial (degree {degree})",
152
+ "coefficients": {f"a{i}": coeffs_rev[i] for i in range(degree+1)},
153
+ "equation" : f"y = {terms}",
154
+ "ssr" : ssr,
155
+ "r_squared" : self._r_squared(y_pred),
156
+ "y_pred" : y_pred,
157
+ "coeffs_array": coeffs_rev,
158
+ "poly1d" : poly,
159
+ }
160
+
161
+ # ------------------------------------------------------------------
162
+ def _fit_exponential(self) -> dict:
163
+ """y = a * e^(bx); linearise: ln(y) = ln(a) + b*x"""
164
+ if np.any(self.y <= 0):
165
+ warnings.warn("Exponential fit requires y > 0. "
166
+ "Non-positive values will be ignored.")
167
+ mask = self.y > 0
168
+ x, y = self.x[mask], self.y[mask]
169
+ else:
170
+ x, y = self.x, self.y
171
+
172
+ n = len(x)
173
+ A = np.column_stack([np.ones(n), x])
174
+ b_ = np.log(y)
175
+ c = self._least_squares(A, b_)
176
+ a = np.exp(c[0])
177
+ b = c[1]
178
+ y_pred = a * np.exp(b * self.x)
179
+ ssr = float(np.sum((self.y - y_pred) ** 2))
180
+ return {
181
+ "model" : "exponential",
182
+ "coefficients": {"a": a, "b": b},
183
+ "equation" : f"y = {a:.6g} · e^({b:.6g}·x)",
184
+ "ssr" : ssr,
185
+ "r_squared" : self._r_squared(y_pred),
186
+ "y_pred" : y_pred,
187
+ "coeffs_array": np.array([a, b]),
188
+ }
189
+
190
+ # ------------------------------------------------------------------
191
+ def _fit_power(self) -> dict:
192
+ """y = a * x^b; linearise: ln(y) = ln(a) + b*ln(x)"""
193
+ if np.any(self.x <= 0) or np.any(self.y <= 0):
194
+ warnings.warn("Power fit requires x > 0 and y > 0.")
195
+ mask = (self.x > 0) & (self.y > 0)
196
+ x, y = self.x[mask], self.y[mask]
197
+ else:
198
+ x, y = self.x, self.y
199
+ n = len(x)
200
+ A = np.column_stack([np.ones(n), np.log(x)])
201
+ b_ = np.log(y)
202
+ c = self._least_squares(A, b_)
203
+ a = np.exp(c[0])
204
+ b = c[1]
205
+ x_safe = np.where(self.x > 0, self.x, np.nan)
206
+ y_pred = a * np.power(x_safe, b)
207
+ ssr = float(np.nansum((self.y - y_pred) ** 2))
208
+ return {
209
+ "model" : "power",
210
+ "coefficients": {"a": a, "b": b},
211
+ "equation" : f"y = {a:.6g} · x^({b:.6g})",
212
+ "ssr" : ssr,
213
+ "r_squared" : self._r_squared(np.nan_to_num(y_pred, nan=0)),
214
+ "y_pred" : y_pred,
215
+ "coeffs_array": np.array([a, b]),
216
+ }
217
+
218
+ # ------------------------------------------------------------------
219
+ def _fit_logarithmic(self) -> dict:
220
+ """y = a + b * ln(x)"""
221
+ if np.any(self.x <= 0):
222
+ warnings.warn("Logarithmic fit requires x > 0.")
223
+ mask = self.x > 0
224
+ x, y = self.x[mask], self.y[mask]
225
+ else:
226
+ x, y = self.x, self.y
227
+ n = len(x)
228
+ A = np.column_stack([np.ones(n), np.log(x)])
229
+ c = self._least_squares(A, y)
230
+ a, b = c
231
+ x_safe = np.where(self.x > 0, self.x, np.nan)
232
+ y_pred = a + b * np.log(x_safe)
233
+ ssr = float(np.nansum((self.y - y_pred) ** 2))
234
+ return {
235
+ "model" : "logarithmic",
236
+ "coefficients": {"a": a, "b": b},
237
+ "equation" : f"y = {a:.6g} + {b:.6g}·ln(x)",
238
+ "ssr" : ssr,
239
+ "r_squared" : self._r_squared(np.nan_to_num(y_pred, nan=0)),
240
+ "y_pred" : y_pred,
241
+ "coeffs_array": np.array([a, b]),
242
+ }
243
+
244
+ # ------------------------------------------------------------------
245
+ def _fit_reciprocal(self) -> dict:
246
+ """y = a + b/x"""
247
+ if np.any(self.x == 0):
248
+ warnings.warn("Reciprocal fit requires x ≠ 0. Zeros removed.")
249
+ mask = self.x != 0
250
+ x, y = self.x[mask], self.y[mask]
251
+ else:
252
+ x, y = self.x, self.y
253
+ n = len(x)
254
+ A = np.column_stack([np.ones(n), 1.0 / x])
255
+ c = self._least_squares(A, y)
256
+ a, b = c
257
+ x_safe = np.where(self.x != 0, self.x, np.nan)
258
+ y_pred = a + b / x_safe
259
+ ssr = float(np.nansum((self.y - y_pred) ** 2))
260
+ return {
261
+ "model" : "reciprocal",
262
+ "coefficients": {"a": a, "b": b},
263
+ "equation" : f"y = {a:.6g} + {b:.6g}/x",
264
+ "ssr" : ssr,
265
+ "r_squared" : self._r_squared(np.nan_to_num(y_pred, nan=0)),
266
+ "y_pred" : y_pred,
267
+ "coeffs_array": np.array([a, b]),
268
+ }
269
+
270
+ # ------------------------------------------------------------------
271
+ def predict(self, x_new: Union[float, List[float]]) -> np.ndarray:
272
+ """Predict y at new x values using the fitted model."""
273
+ if self.result is None:
274
+ raise RuntimeError("Call .fit() first.")
275
+ x_new = np.array(x_new, dtype=float)
276
+ model = self.result["model"].split()[0]
277
+ coeffs = self.result["coefficients"]
278
+ if model == "linear":
279
+ return coeffs["a"] + coeffs["b"] * x_new
280
+ elif model == "polynomial":
281
+ return self.result["poly1d"](x_new)
282
+ elif model == "exponential":
283
+ return coeffs["a"] * np.exp(coeffs["b"] * x_new)
284
+ elif model == "power":
285
+ return coeffs["a"] * np.power(np.abs(x_new), coeffs["b"])
286
+ elif model == "logarithmic":
287
+ return coeffs["a"] + coeffs["b"] * np.log(np.abs(x_new))
288
+ elif model == "reciprocal":
289
+ return coeffs["a"] + coeffs["b"] / x_new
290
+ raise ValueError(f"Cannot predict for model '{model}'.")
291
+
292
+ # ------------------------------------------------------------------
293
+ def display(self) -> None:
294
+ if self.result is None:
295
+ raise RuntimeError("Call .fit() first.")
296
+ r = self.result
297
+ print("=" * 55)
298
+ print(f" Least-Squares Curve Fitting [{r['model']}]")
299
+ print("=" * 55)
300
+ print(f" Equation : {r['equation']}")
301
+ print(f" Coefficients:")
302
+ for k, v in r["coefficients"].items():
303
+ print(f" {k} = {v:.8g}")
304
+ print(f" SSR : {r['ssr']:.6g}")
305
+ print(f" R² : {r['r_squared']:.6g}")
306
+ print("-" * 55)
307
+ print(f" {'x':>10} {'y_obs':>12} {'y_pred':>12} {'residual':>12}")
308
+ for xi, yi, yp in zip(self.x, self.y, r["y_pred"]):
309
+ print(f" {xi:>10.4g} {yi:>12.4g} {yp:>12.4g} {yi-yp:>12.4g}")
310
+ print("=" * 55)
311
+
312
+ # ------------------------------------------------------------------
313
+ def plot(self, save_path: Optional[str] = None,
314
+ n_points: int = 300) -> None:
315
+ """Plot data points and fitted curve."""
316
+ try:
317
+ import matplotlib.pyplot as plt
318
+ except ImportError:
319
+ warnings.warn("matplotlib required for plotting.")
320
+ return
321
+
322
+ if self.result is None:
323
+ raise RuntimeError("Call .fit() first.")
324
+
325
+ x_plot = np.linspace(self.x.min(), self.x.max(), n_points)
326
+ y_plot = self.predict(x_plot)
327
+
328
+ fig, ax = plt.subplots(figsize=(7, 5))
329
+ ax.scatter(self.x, self.y, color="steelblue", zorder=5, label="Data")
330
+ ax.plot(x_plot, y_plot, color="tomato", lw=2,
331
+ label=f"Fit: {self.result['equation']}")
332
+ ax.set_xlabel("x"); ax.set_ylabel("y")
333
+ ax.set_title(f"Least Squares Fit — {self.result['model']} "
334
+ f"(R²={self.result['r_squared']:.4f})")
335
+ ax.legend(); ax.grid(True, alpha=0.3)
336
+ plt.tight_layout()
337
+ if save_path:
338
+ plt.savefig(save_path, dpi=150)
339
+ plt.show()
pyOR/dual_simplex.py ADDED
@@ -0,0 +1,254 @@
1
+ """
2
+ Module: dual_simplex.py
3
+ ========================
4
+ AIM:
5
+ To solve a Linear Programming Problem using the Dual Simplex Method.
6
+
7
+ The Dual Simplex Method is particularly useful when:
8
+ - All reduced costs satisfy optimality (dual feasibility), but
9
+ some basic variables are negative (primal infeasibility).
10
+ - This arises naturally when adding constraints to an existing
11
+ optimal solution, or when solving minimisation problems with
12
+ >= constraints (after multiplying by -1).
13
+
14
+ Steps:
15
+ 1. Start with a dual-feasible (but primal-infeasible) tableau.
16
+ 2. Select the most negative basic variable as the leaving variable.
17
+ 3. Apply the minimum ratio test on the objective row coefficients.
18
+ 4. Pivot until primal feasibility is achieved or infeasibility confirmed.
19
+
20
+ Handles:
21
+ - Mixed <= / >= / = constraints
22
+ - Maximisation and Minimisation
23
+ - Infeasibility detection
24
+ """
25
+
26
+ from __future__ import annotations
27
+ import numpy as np
28
+ from typing import List, Optional
29
+
30
+
31
+ class DualSimplex:
32
+ """
33
+ Dual Simplex Method solver.
34
+
35
+ Parameters
36
+ ----------
37
+ c : Objective coefficients.
38
+ A : Constraint coefficient matrix.
39
+ b : RHS values.
40
+ senses : List of constraint senses: '<=' | '>=' | '='.
41
+ Default is all '<='.
42
+ objective : 'min' (default) or 'max'.
43
+ var_names : Optional variable names.
44
+
45
+ Examples
46
+ --------
47
+ >>> ds = DualSimplex(
48
+ ... c = [2, 3],
49
+ ... A = [[1, 1], [1, 0], [0, 1]],
50
+ ... b = [4, 2, 3],
51
+ ... senses = ['<=', '<=', '<='],
52
+ ... objective= 'min'
53
+ ... )
54
+ >>> result = ds.solve()
55
+ >>> ds.display()
56
+ """
57
+
58
+ def __init__(
59
+ self,
60
+ c: List[float],
61
+ A: List[List[float]],
62
+ b: List[float],
63
+ senses: Optional[List[str]] = None,
64
+ objective: str = "min",
65
+ var_names: Optional[List[str]] = None,
66
+ ):
67
+ self.objective = objective.lower()
68
+ self.A_orig = np.array(A, dtype=float)
69
+ self.b_orig = np.array(b, dtype=float)
70
+ self.c_orig = np.array(c, dtype=float)
71
+ m, n = self.A_orig.shape
72
+ self.m, self.n = m, n
73
+
74
+ if senses is None:
75
+ senses = ["<="] * m
76
+ self.senses = senses
77
+
78
+ # Convert to maximisation internally
79
+ if self.objective == "min":
80
+ self.c_int = -self.c_orig.copy()
81
+ else:
82
+ self.c_int = self.c_orig.copy()
83
+
84
+ if var_names:
85
+ self.var_names = var_names
86
+ else:
87
+ self.var_names = [f"x{i+1}" for i in range(n)]
88
+
89
+ self.result = None
90
+
91
+ # ------------------------------------------------------------------
92
+ def _build_tableau(self) -> tuple:
93
+ """
94
+ Convert constraints to standard form for dual simplex.
95
+ >= constraints are multiplied by -1 (making b negative).
96
+ = constraints get an artificial with big-M treatment.
97
+ Returns (tableau, basis).
98
+ """
99
+ m, n = self.m, self.n
100
+ # number of slack/surplus variables
101
+ n_slack = m
102
+ total = n + n_slack
103
+ T = np.zeros((m + 1, total + 1))
104
+
105
+ basis = []
106
+ for i, sense in enumerate(self.senses):
107
+ a_row = self.A_orig[i].copy()
108
+ b_val = self.b_orig[i]
109
+ if sense == "<=":
110
+ T[i, :n] = a_row
111
+ T[i, n + i] = 1.0
112
+ T[i, -1] = b_val
113
+ basis.append(n + i)
114
+ elif sense == ">=":
115
+ # Multiply row by -1 → makes it dual feasible from the start
116
+ T[i, :n] = -a_row
117
+ T[i, n + i] = 1.0 # surplus becomes slack after negation
118
+ T[i, -1] = -b_val
119
+ basis.append(n + i)
120
+ elif sense == "=":
121
+ T[i, :n] = a_row
122
+ T[i, n + i] = 1.0
123
+ T[i, -1] = b_val
124
+ basis.append(n + i)
125
+
126
+ # Objective row
127
+ T[-1, :n] = -self.c_int
128
+
129
+ # Eliminate basic slack variables from obj row
130
+ for i, b in enumerate(basis):
131
+ if T[-1, b] != 0:
132
+ T[-1, :] -= T[-1, b] * T[i, :]
133
+
134
+ # Extend var names
135
+ self._all_var_names = (self.var_names
136
+ + [f"s{i+1}" for i in range(m)])
137
+ return T, basis
138
+
139
+ # ------------------------------------------------------------------
140
+ def _pivot(self, T: np.ndarray, row: int, col: int) -> np.ndarray:
141
+ T = T.copy()
142
+ T[row, :] /= T[row, col]
143
+ for i in range(T.shape[0]):
144
+ if i != row:
145
+ T[i, :] -= T[i, col] * T[row, :]
146
+ return T
147
+
148
+ # ------------------------------------------------------------------
149
+ def solve(self, max_iter: int = 500) -> dict:
150
+ """
151
+ Execute the Dual Simplex algorithm.
152
+
153
+ Returns
154
+ -------
155
+ dict with keys: status, x, obj_value, iterations, tableau
156
+ """
157
+ T, basis = self._build_tableau()
158
+ m = self.m
159
+
160
+ for iteration in range(max_iter):
161
+ rhs = T[:m, -1]
162
+
163
+ # --- Primal feasibility check ---
164
+ if all(rhs >= -1e-9):
165
+ break
166
+
167
+ # --- Select leaving variable (most negative RHS) ---
168
+ row = int(np.argmin(rhs))
169
+
170
+ # --- Check infeasibility ---
171
+ pivot_col_candidates = T[row, :-1]
172
+ if all(pivot_col_candidates >= -1e-9):
173
+ self.result = {
174
+ "status" : "Infeasible",
175
+ "x" : None,
176
+ "obj_value" : None,
177
+ "iterations": iteration,
178
+ "tableau" : T,
179
+ }
180
+ return self.result
181
+
182
+ # --- Min ratio test on objective row ---
183
+ # Consider only columns where T[row, col] < 0
184
+ ratios = []
185
+ for j in range(T.shape[1] - 1):
186
+ if T[row, j] < -1e-9:
187
+ ratios.append((abs(T[-1, j] / T[row, j]), j))
188
+ if not ratios:
189
+ self.result = {
190
+ "status" : "Infeasible",
191
+ "x" : None,
192
+ "obj_value" : None,
193
+ "iterations": iteration,
194
+ "tableau" : T,
195
+ }
196
+ return self.result
197
+
198
+ ratios.sort()
199
+ col = ratios[0][1]
200
+
201
+ basis[row] = col
202
+ T = self._pivot(T, row, col)
203
+
204
+ else:
205
+ self.result = {
206
+ "status" : "Max iterations reached",
207
+ "x" : None,
208
+ "obj_value" : None,
209
+ "iterations": max_iter,
210
+ "tableau" : T,
211
+ }
212
+ return self.result
213
+
214
+ # Extract solution
215
+ n = self.n
216
+ total = T.shape[1] - 1
217
+ x_full = np.zeros(total)
218
+ for i, b in enumerate(basis):
219
+ x_full[b] = T[i, -1]
220
+
221
+ x_orig = x_full[:n]
222
+ z_int = float(T[-1, -1])
223
+ z = z_int if self.objective == "max" else -z_int
224
+
225
+ self.result = {
226
+ "status" : "Optimal",
227
+ "x" : x_orig,
228
+ "slack" : x_full[n:],
229
+ "obj_value" : z,
230
+ "iterations": iteration + 1,
231
+ "tableau" : T,
232
+ "basis" : basis,
233
+ }
234
+ return self.result
235
+
236
+ # ------------------------------------------------------------------
237
+ def display(self) -> None:
238
+ """Display the solution."""
239
+ if self.result is None:
240
+ self.solve()
241
+ r = self.result
242
+ print("=" * 55)
243
+ print(" Dual Simplex Method Solution")
244
+ print("=" * 55)
245
+ c_str = " + ".join(f"{self.c_orig[i]:g}·{self.var_names[i]}"
246
+ for i in range(self.n))
247
+ print(f" Objective : {self.objective}imise Z = {c_str}")
248
+ print(f" Status : {r['status']}")
249
+ if r["x"] is not None:
250
+ for i, xi in enumerate(r["x"]):
251
+ print(f" {self.var_names[i]:<10} = {xi:.6g}")
252
+ print(f" Z* = {r['obj_value']:.6g}")
253
+ print(f" Iterations: {r['iterations']}")
254
+ print("=" * 55)