Create models.py
Browse files
models.py
ADDED
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# models.py
|
2 |
+
|
3 |
+
import numpy as np
|
4 |
+
from scipy.optimize import curve_fit
|
5 |
+
from sympy import symbols, sympify, lambdify
|
6 |
+
import warnings
|
7 |
+
|
8 |
+
class BioprocessModel:
|
9 |
+
def __init__(self):
|
10 |
+
self.params = {}
|
11 |
+
self.models = {}
|
12 |
+
self.r2 = {}
|
13 |
+
self.rmse = {}
|
14 |
+
|
15 |
+
def set_model(self, model_type, equation_str, param_str):
|
16 |
+
equation_str = equation_str.strip()
|
17 |
+
if '=' in equation_str:
|
18 |
+
equation_str = equation_str.split('=', 1)[1].strip()
|
19 |
+
|
20 |
+
params = [param.strip() for param in param_str.split(',')]
|
21 |
+
self.models[model_type] = {
|
22 |
+
'equation_str': equation_str,
|
23 |
+
'params': params
|
24 |
+
}
|
25 |
+
|
26 |
+
t = symbols('t')
|
27 |
+
param_symbols = symbols(params)
|
28 |
+
expr = sympify(equation_str)
|
29 |
+
func = lambdify((t, *param_symbols), expr, 'numpy')
|
30 |
+
self.models[model_type]['function'] = func
|
31 |
+
|
32 |
+
def fit_model(self, model_type, time, data, bounds):
|
33 |
+
func = self.models[model_type]['function']
|
34 |
+
params = self.models[model_type]['params']
|
35 |
+
|
36 |
+
p0 = np.ones(len(params))
|
37 |
+
lower_bounds, upper_bounds = bounds
|
38 |
+
|
39 |
+
lower_bounds = np.array(lower_bounds)
|
40 |
+
upper_bounds = np.array(upper_bounds)
|
41 |
+
|
42 |
+
if len(lower_bounds) != len(params):
|
43 |
+
lower_bounds = np.full(len(params), -np.inf)
|
44 |
+
if len(upper_bounds) != len(params):
|
45 |
+
upper_bounds = np.full(len(params), np.inf)
|
46 |
+
|
47 |
+
with warnings.catch_warnings():
|
48 |
+
warnings.simplefilter("ignore")
|
49 |
+
popt, _ = curve_fit(func, time, data, p0=p0, bounds=(lower_bounds, upper_bounds), maxfev=10000)
|
50 |
+
|
51 |
+
self.params[model_type] = dict(zip(params, popt))
|
52 |
+
y_pred = func(time, *popt)
|
53 |
+
ss_res = np.sum((data - y_pred) ** 2)
|
54 |
+
ss_tot = np.sum((data - np.mean(data)) ** 2)
|
55 |
+
self.r2[model_type] = 1 - (ss_res / ss_tot)
|
56 |
+
self.rmse[model_type] = np.sqrt(np.mean((data - y_pred) ** 2))
|
57 |
+
return y_pred
|