-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCompartment_model.py
378 lines (333 loc) ยท 13.7 KB
/
Compartment_model.py
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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
import streamlit as st
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import least_squares
from scipy.interpolate import interp1d
from scipy.stats import probplot
# ํ์ด์ง ์ค์
st.set_page_config(layout="wide", page_title="PK/PD Analyzer Pro")
st.title("Advanced Pharmacokinetic Modeling")
# ์ธ์
์ํ ์ด๊ธฐํ
if 'data' not in st.session_state:
st.session_state.data = pd.DataFrame(columns=['Time', 'Concentration'])
if 'params' not in st.session_state:
st.session_state.params = {
'model_type': '1-Compartment',
'admin_route': 'IV',
'dose': 100.0,
'CL': 5.0,
'Vc': 10.0,
'CLd': 2.0,
'Vp': 20.0,
'Ka': 1.5,
'F': 1.0,
'step_size': 0.1
}
if 'param_bounds' not in st.session_state:
st.session_state.param_bounds = {
'CL': (0.1, 20.0),
'Vc': (1.0, 100.0),
'CLd': (0.1, 10.0),
'Vp': (5.0, 200.0),
'Ka': (0.1, 5.0),
'F': (0.1, 1.0)
}
# ODE ์์คํ
์ ์
def pk_ode(t, y):
p = st.session_state.params
model = p['model_type']
route = p['admin_route']
if model == '1-Compartment':
if route == 'IV':
dA_c = -(p['CL']/p['Vc']) * y[0]
return [dA_c]
else: # PO
dA_g = -p['Ka'] * y[0]
dA_c = p['Ka'] * y[0] - (p['CL']/p['Vc']) * y[1]
return [dA_g, dA_c]
else: # 2-Compartment
if route == 'IV':
C_c = y[0] / p['Vc']
C_p = y[1] / p['Vp']
dA_c = p['CLd']*(C_p - C_c) - p['CL']*C_c
dA_p = p['CLd']*(C_c - C_p)
return [dA_c, dA_p]
else: # PO
C_c = y[1] / p['Vc']
C_p = y[2] / p['Vp']
dA_g = -p['Ka'] * y[0]
dA_c = p['Ka'] * y[0] + p['CLd']*(C_p - C_c) - p['CL']*C_c
dA_p = p['CLd']*(C_c - C_p)
return [dA_g, dA_c, dA_p]
def solve_ode():
p = st.session_state.params
try:
# ์ด๊ธฐ ์กฐ๊ฑด ์ค์
if p['admin_route'] == 'IV':
if p['model_type'] == '1-Compartment':
y0 = [p['dose']]
else:
y0 = [p['dose'], 0]
else: # PO
dose = p['dose'] * p['F']
if p['model_type'] == '1-Compartment':
y0 = [dose, 0]
else:
y0 = [dose, 0, 0]
t_max = max(st.session_state.data['Time'])*1.5 if not st.session_state.data.empty else 24
t_eval = np.arange(0, t_max + p['step_size'], p['step_size'])
# RK4 Solver
y = np.zeros((len(t_eval), len(y0)))
y[0] = y0
for i in range(1, len(t_eval)):
h = p['step_size']
k1 = pk_ode(t_eval[i-1], y[i-1])
k2 = pk_ode(t_eval[i-1] + h/2, y[i-1] + h/2*np.array(k1))
k3 = pk_ode(t_eval[i-1] + h/2, y[i-1] + h/2*np.array(k2))
k4 = pk_ode(t_eval[i-1] + h, y[i-1] + h*np.array(k3))
y[i] = y[i-1] + h/6*(np.array(k1) + 2*np.array(k2) + 2*np.array(k3) + np.array(k4))
return t_eval, y
except Exception as e:
st.error(f"ODE Solver Error: {str(e)}")
return None, None
# ์ฌ์ด๋๋ฐ ์ค์
with st.sidebar:
st.header("โ๏ธ Model Configuration")
st.session_state.params['model_type'] = st.selectbox(
"Model Type", ["1-Compartment", "2-Compartment"])
st.session_state.params['admin_route'] = st.selectbox(
"Administration Route", ["IV", "PO"])
st.subheader("Dosing Parameters")
st.session_state.params['dose'] = st.number_input(
"Dose", 0.0, 10e+10, 100.0, 0.1)
st.subheader("PK Parameters & Bounds")
def param_input(param, default, min_val, max_val):
cols = st.columns([3,1,1])
with cols[0]:
st.session_state.params[param] = st.number_input(
f"{param}",
min_val, max_val, default, 0.1,
key=f"val_{param}"
)
with cols[1]:
min_bound = st.number_input(
"Min", min_val, max_val, st.session_state.param_bounds[param][0], 0.1,
key=f"min_{param}"
)
with cols[2]:
max_bound = st.number_input(
"Max", min_val, max_val, st.session_state.param_bounds[param][1], 0.1,
key=f"max_{param}"
)
st.session_state.param_bounds[param] = (min_bound, max_bound)
param_input('CL', 5.0, 0.0, 10e+10)
param_input('Vc', 10.0, 0.0, 10e+10)
if st.session_state.params['model_type'] == '2-Compartment':
param_input('CLd', 2.0, 0.0, 10e+10)
param_input('Vp', 20.0, 0.0, 10e+10)
if st.session_state.params['admin_route'] == 'PO':
param_input('Ka', 1.5, 0.0, 10e+3)
param_input('F', 1.0, 0.0, 1.0)
st.subheader("Solver Settings")
st.session_state.params['step_size'] = st.number_input(
"Step Size (h)", 0.01, 2.0, 0.1, 0.01)
# ๋ฉ์ธ ํ๋ฉด
col1, col2 = st.columns([1, 2])
with col1:
st.subheader("๐ฅ Data Input")
uploaded_file = st.file_uploader("Upload CSV/Excel", type=["csv", "xlsx"])
if uploaded_file:
try:
df = pd.read_excel(uploaded_file) if uploaded_file.name.endswith('.xlsx') else pd.read_csv(uploaded_file)
if {'Time', 'Concentration'}.issubset(df.columns):
st.session_state.data = df.sort_values('Time')
st.success(f"Loaded {len(df)} data points")
else:
st.error("Missing required columns: Time & Concentration")
except Exception as e:
st.error(f"File Error: {str(e)}")
with st.expander("Manual Data Entry"):
edited_df = st.data_editor(
st.session_state.data,
num_rows="dynamic",
column_config={
"Time": {"format": "%.2f"},
"Concentration": {"format": "%.4f"}
},
height=300
)
st.session_state.data = edited_df
with col2:
st.subheader("๐ Simulation Results")
t_sim, y_sim = solve_ode()
# ๋๋ ๊ณ์ฐ
conc_sim = []
if y_sim is not None:
p = st.session_state.params
if p['admin_route'] == 'IV':
conc_sim = y_sim[:,0] / p['Vc']
else:
conc_sim = y_sim[:,1] / p['Vc']
# ๋ฉ์ธ ํ๋กฏ
fig = plt.figure(figsize=(10, 4))
if not st.session_state.data.empty:
t_obs = st.session_state.data['Time'].values
c_obs = st.session_state.data['Concentration'].values
plt.scatter(t_obs, c_obs, c='red', label='Observed')
if len(conc_sim) > 0:
plt.plot(t_sim, conc_sim, 'b--', label='Simulated')
plt.xlabel('Time')
plt.ylabel('Concentration')
plt.title('Concentration-Time Profile')
plt.legend()
plt.grid(alpha=0.3)
st.pyplot(fig)
# ํ๋ผ๋ฏธํฐ ์ถ์
if st.button("๐ Run Parameter Estimation"):
if len(st.session_state.data) < 3:
st.warning("Minimum 3 data points required")
st.stop()
try:
p = st.session_state.params
t_obs = st.session_state.data['Time'].values
c_obs = st.session_state.data['Concentration'].values
# ์ถ์ ํ๋ผ๋ฏธํฐ ์ ํ
param_info = []
if p['model_type'] == '1-Compartment':
param_info += [('CL', p['CL']), ('Vc', p['Vc'])]
if p['admin_route'] == 'PO':
param_info += [('Ka', p['Ka']), ('F', p['F'])]
else:
param_info += [('CL', p['CL']), ('Vc', p['Vc']),
('CLd', p['CLd']), ('Vp', p['Vp'])]
if p['admin_route'] == 'PO':
param_info += [('Ka', p['Ka']), ('F', p['F'])]
# ๊ฒฝ๊ณ๊ฐ ์ค์
bounds = (
[st.session_state.param_bounds[name][0] for name, _ in param_info],
[st.session_state.param_bounds[name][1] for name, _ in param_info]
)
x0 = [val for _, val in param_info]
param_names = [name for name, _ in param_info]
def residual(params):
try:
# ํ๋ผ๋ฏธํฐ ์
๋ฐ์ดํธ
for name, val in zip(param_names, params):
p[name] = val
# ์๋ฎฌ๋ ์ด์
์คํ
t_sim, y_sim = solve_ode()
if p['admin_route'] == 'IV':
c_sim = y_sim[:,0] / p['Vc']
else:
c_sim = y_sim[:,1] / p['Vc']
# ๋ณด๊ฐ
f = interp1d(t_sim, c_sim, bounds_error=False, fill_value=0)
return f(t_obs) - c_obs
except:
return np.ones_like(c_obs)*1e6
# ์ต์ ํ ์คํ
result = least_squares(residual, x0=x0, bounds=bounds, method='trf')
# ๊ฒฐ๊ณผ ์ ์ฅ
for name, val in zip(param_names, result.x):
p[name] = val
# ๋ฆฌํฌํธ ๋ฐ์ดํฐ ์์ฑ
t_sim, y_sim = solve_ode()
c_sim = y_sim[:,1]/p['Vc'] if p['admin_route']=='PO' else y_sim[:,0]/p['Vc']
f = interp1d(t_sim, c_sim, bounds_error=False, fill_value=0)
c_pred = f(t_obs)
st.session_state.report = {
'params': p.copy(),
't_sim': t_sim,
'c_sim': c_sim,
't_obs': t_obs,
'c_obs': c_obs,
'c_pred': c_pred,
'residuals': c_obs - c_pred,
'metrics': {
'Rยฒ': 1 - np.sum((c_obs - c_pred)**2)/np.sum((c_obs - np.mean(c_obs))**2),
'RMSE': np.sqrt(np.mean((c_obs - c_pred)**2)),
'AIC': len(c_obs)*np.log(np.sum((c_obs - c_pred)**2)/len(c_obs)) + 2*len(result.x)
}
}
st.success("Parameter estimation completed!")
st.rerun()
except Exception as e:
st.error(f"Optimization failed: {str(e)}")
# ๋ฆฌํฌํธ ํ์
if 'report' in st.session_state:
st.divider()
st.subheader("๐ Analysis Report")
subcol1, subcol2 = st.columns([1, 2])
with subcol1:
st.write("Model Parameters")
# ํ๋ผ๋ฏธํฐ ํ
์ด๋ธ
p = st.session_state.report['params']
param_df = pd.DataFrame({
'Parameter': ['CL', 'Vc', 'CLd', 'Vp', 'Ka', 'F'],
'Value': [p['CL'], p['Vc'], p.get('CLd', np.nan),
p.get('Vp', np.nan), p.get('Ka', np.nan), p.get('F', np.nan)],
})
if p['model_type'] == '1-Compartment':
param_df = param_df[~param_df['Parameter'].isin(['CLd', 'Vp'])]
if p['admin_route'] == 'IV':
param_df = param_df[~param_df['Parameter'].isin(['Ka', 'F'])]
st.dataframe(param_df, hide_index=True)
with subcol2:
st.write("Model Diagnostics")
# ์ฑ๋ฅ ์งํ
evaluation_df = pd.DataFrame({
'Evaluation Metric': ['Rยฒ', 'RMSE', 'AIC'],
'Value':[f"{st.session_state.report['metrics']['Rยฒ']:0.4f}",
f"{st.session_state.report['metrics']['RMSE']:0.4f}",
f"{st.session_state.report['metrics']['AIC']:0.4f}"]
})
st.dataframe(evaluation_df, hide_index=True)
# ์ง๋จ ํ๋กฏ
fig = plt.figure(figsize=(12, 8))
# ๋๋ ํ๋กํ์ผ
plt.subplot(2,2,1)
plt.plot(st.session_state.report['t_sim'], st.session_state.report['c_sim'], 'b--', label='Simulated')
plt.scatter(st.session_state.report['t_obs'], st.session_state.report['c_obs'], c='red', label='Observed')
plt.title('Concentration-Time Profile')
plt.xlabel('Time')
plt.ylabel('Concentration')
plt.legend()
# ์์ฐจ ํ๋กฏ
plt.subplot(2,2,2)
plt.scatter(st.session_state.report['t_obs'], st.session_state.report['residuals'], alpha=0.6)
plt.axhline(0, color='r', linestyle='--')
plt.title('Residuals vs Time')
plt.xlabel('Time')
plt.ylabel('Residuals')
# ์์ธก vs ๊ด์ธก
plt.subplot(2,2,3)
plt.scatter(st.session_state.report['c_obs'], st.session_state.report['c_pred'], alpha=0.6)
lims = [0, max(st.session_state.report['c_obs'])*1.1]
plt.plot(lims, lims, 'r--')
plt.title('Predicted vs Observed')
plt.xlabel('Observed')
plt.ylabel('Predicted')
# Q-Q ํ๋กฏ (Scipy ๋ฒ์ ํธํ์ฑ ์ฒ๋ฆฌ ๋ฐ ํ๊ท์ ์ถ๊ฐ)
plt.subplot(2,2,4)
res = st.session_state.report['residuals']
try:
# fit=True๋ฅผ ์ฌ์ฉํ๋ฉด slope, intercept, r ๊ฐ์ ํจ๊ป ๋ฐํํจ
(osm, osr), (slope, intercept, r) = probplot(res, dist="norm", fit=True)
except Exception as e:
prob_res = probplot(res, dist="norm", fit=False)
osm, osr = prob_res[0], prob_res[1]
# fit ๊ฒฐ๊ณผ๊ฐ ์์ผ๋ฉด np.polyfit์ ์ด์ฉํด ํ๊ท์ ์ถ์
slope, intercept = np.polyfit(osm, osr, 1)
plt.scatter(osm, osr, alpha=0.6, label="Data")
# ๊ธฐ์ค ์ (Identity line)
plt.plot([min(osm), max(osm)], [min(osm), max(osm)], 'r--', label="Identity")
# ํ๊ท์ ๊ณ์ฐ ๋ฐ ํ๋กฏ
x_vals = np.linspace(min(osm), max(osm), 100)
plt.plot(x_vals, intercept + slope * x_vals, 'g-', label="Regression Line")
plt.title('Normal Q-Q Plot')
plt.xlabel('Theoretical Quantiles')
plt.ylabel('Sample Quantiles')
plt.legend()
plt.tight_layout()
st.pyplot(fig)