-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbmp_model.py
More file actions
191 lines (159 loc) · 7.57 KB
/
Copy pathbmp_model.py
File metadata and controls
191 lines (159 loc) · 7.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
from dataclasses import dataclass, field
from typing import List, Tuple, Optional, Callable
import numpy as np
from scipy.optimize import minimize
# Define model A
def model_a(time, params):
'''
Simple first order BMP model
y = B0 * (1 - exp(-k * t))'''
B0, k = params
return B0 * (1 - np.exp(-k * time))
# Define model B
def model_b(time, params):
'''
Two-phase BMP model
y = B0 * (1 + (kH*exp(-kVFA*t)-kVFA*exp(-kH*t)/(kVFA-kH)))
Note: after estimation of model A parameters:
B0(0) = B0, kH = k, kVFA(0) = k*2
'''
B0, kH, kVFA = params
return B0 * (1 + (kH*np.exp(-kVFA*time)-kVFA*np.exp(-kH*time)/(kVFA-kH)))
# Define model C
def model_c(time, params):
'''
Biphasic BMP model with fractional contribution
y = B0 * (1 - alpha * exp(-kF * t) - (1 - alpha) * exp(-kL * t))
Note: after estimation of model A parameters:
B0(0) = B0, alpha(0) = 0.5, kF(0) = k, kL(0) = k/2
'''
B0, alpha, kF, kL = params
return B0 * (1 - alpha * np.exp(-kF * time) - (1 - alpha) * np.exp(-kL * time))
def model_d(time, params):
'''
Biphasic BMP model with fractional contribution and VFA inhibition
y = B0 * (alpha*(1 + (kF*exp(-kVFA*t)-kVFA*exp(-kF*t))/(kVFA-kF)) + (1 - alpha) * (1 + (kL*exp(-kVFA*t)-kVFA*exp(-kL*t)/(kVFA-kL))))
Note: after estimation of model A and model C parameters:
B0(0) = B0, alpha(0) = 0.5, kF(0) = k, kL(0) = k/2, kVFA = kF*2
'''
B0, alpha, kF, kL, kVFA = params
return B0 * (alpha*(1 + (kF*np.exp(-kVFA*time)-kVFA*np.exp(-kF*time))/(kVFA-kF)) + (1 - alpha) * (1 + (kL*np.exp(-kVFA*time)-kVFA*np.exp(-kL*time)/(kVFA-kL))))
def model_e(time, params):
'''
Modified Gompertz BMP model
y = B0 * exp(-exp(1 + (lag - t)*(Rmax*exp(1)/B0)))
'''
B0, Rmax, lag = params
return B0 * np.exp(-np.exp(1 + (lag - time)*(Rmax*np.exp(1)/B0)))
@dataclass
class BMP_estimation:
"""
A class to evaluate and estimate parameters of a simple algebraic model.
The model A is: y = param1 * (1 - exp(-param2 * t))
To set the initial conditions of the models given an arbitrary first guess for model A, refer to: https://link.springer.com/article/10.1007/s00449-014-1150-4#appendices
Model expressions are reported in the Appendix A of: https://www.sciencedirect.com/science/article/pii/S0960148122001562
"""
time: np.ndarray # Time points
data: Optional[np.ndarray] = None # Observed data points (optional)
model: Callable[[np.ndarray, List[float]], np.ndarray] = None # Model function
default_params: List[float] = field(default_factory=lambda: [1.0, 0.1]) # Default first guess for parameters [param1, param2]
weights: Optional[np.ndarray] = None # Weights for weighted least squares (optional)
def evaluate_model(self, params: Optional[List[float]] = None) -> np.ndarray:
"""
Evaluate the model with given parameters.
Args:
params (List[float]): Parameters for the model. If None, default parameters are used.
Returns:
np.ndarray: Model output for the given parameters.
"""
if self.model is None:
raise ValueError("No model function is defined.")
if params is None:
params = self.default_params
return self.model(self.time, params)
def compute_error(self, params: Optional[List[float]] = None) -> np.ndarray:
"""
Compute the error between the model and observed data.
Args:
params (List[float]): Parameters for the model. If None, default parameters are used.
Returns:
np.ndarray: Error values for each time point.
"""
if self.data is None:
raise ValueError("Observed data is not provided.")
model_output = self.evaluate_model(params)
return self.data - model_output
def compute_rmse(self, params: Optional[List[float]] = None) -> float:
"""
Compute the Root Mean Squared Error (RMSE) between the model and observed data.
Args:
params (List[float]): Parameters for the model. If None, default parameters are used.
Returns:
float: RMSE value.
"""
error = self.compute_error(params)
rmse = np.sqrt(np.mean(error ** 2))
return rmse
def compute_weighted_rmse(self, params: Optional[List[float]] = None) -> float:
"""
Compute the Weighted Root Mean Squared Error (WRMSE) between the model and observed data.
Args:
params (List[float]): Parameters for the model. If None, default parameters are used.
Returns:
float: Weighted RMSE value.
"""
if self.weights is None:
raise ValueError("Weights are not provided for weighted least squares.")
error = self.compute_error(params)
weighted_error = self.weights * (error ** 2)
wrmse = np.sqrt(np.sum(weighted_error) / np.sum(self.weights))
return wrmse
def estimate_parameters(self, method: str = "BFGS", cost_function: Optional[Callable] = None) -> Tuple[List[float], float, Optional[np.ndarray]]:
"""
Estimate the parameters by minimizing the specified cost function.
Args:
method (str): Optimization method to use (default: "BFGS").
cost_function (Callable): Custom cost function to minimize. If None, defaults to RMSE or WRMSE.
Returns:
Tuple[List[float], float, Optional[np.ndarray]]:
- Optimized parameters (rescaled to original magnitude).
- Minimized cost function value.
- Covariance matrix of the parameters (if available, otherwise None).
"""
# Define scaling factors for normalization
param_scales = np.array(self.default_params)
scale_min = 1
scale_max = 10
def scale_params(params):
"""Scale parameters to the range (1, 10)."""
return (params / param_scales) * (scale_max - scale_min) + scale_min
def rescale_params(scaled_params):
"""Rescale parameters back to their original magnitude."""
return (scaled_params - scale_min) / (scale_max - scale_min) * param_scales
# Use RMSE or WRMSE as the default cost function
if cost_function is None:
if self.weights is None:
cost_function = self.compute_rmse
print("Cost function and weights not provided, using RMSE")
else:
cost_function = self.compute_weighted_rmse
print("Cost function not provided, using weights-RMSE")
def wrapped_cost_function(scaled_params):
"""Cost function for optimization."""
params = rescale_params(scaled_params)
return cost_function(params)
# Initial guess scaled
scaled_initial_guess = scale_params(self.default_params)
# Perform optimization
result = minimize(wrapped_cost_function, scaled_initial_guess, method=method)
# Rescale optimized parameters back to original magnitude
optimized_params = rescale_params(result.x).tolist()
minimized_cost = result.fun
# Compute covariance matrix if available
covariance_matrix = None
if method == "BFGS" and result.hess_inv is not None:
# Rescale Hessian inverse to original parameter space
hess_inv = result.hess_inv
scaling_factors = np.diag(param_scales / (scale_max - scale_min))
covariance_matrix = scaling_factors @ hess_inv @ scaling_factors
return optimized_params, minimized_cost, covariance_matrix