Update app.py
Browse files
app.py
CHANGED
@@ -1,229 +1,675 @@
|
|
1 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
2 |
|
3 |
import numpy as np
|
4 |
import pandas as pd
|
5 |
import matplotlib.pyplot as plt
|
6 |
-
|
|
|
|
|
|
|
|
|
|
|
7 |
import io
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
8 |
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
def parse_bounds(bounds_str, num_params):
|
13 |
-
try:
|
14 |
-
# Reemplazar 'inf' por 'np.inf' si el usuario lo escribió así
|
15 |
-
bounds_str = bounds_str.replace('inf', 'np.inf')
|
16 |
-
# Evaluar la cadena de límites
|
17 |
-
bounds = eval(f"[{bounds_str}]")
|
18 |
-
if len(bounds) != num_params:
|
19 |
-
raise ValueError("Número de límites no coincide con el número de parámetros.")
|
20 |
-
lower_bounds = [b[0] for b in bounds]
|
21 |
-
upper_bounds = [b[1] for b in bounds]
|
22 |
-
return lower_bounds, upper_bounds
|
23 |
-
except Exception as e:
|
24 |
-
print(f"Error al parsear los límites: {e}. Usando límites por defecto.")
|
25 |
-
lower_bounds = [-np.inf] * num_params
|
26 |
-
upper_bounds = [np.inf] * num_params
|
27 |
-
return lower_bounds, upper_bounds
|
28 |
-
|
29 |
-
@gpu_decorator(duration=300)
|
30 |
-
def generate_analysis(prompt, max_length=1024, device=None):
|
31 |
-
# Implementación existente para generar análisis usando Hugging Face o similar
|
32 |
-
# Por ejemplo, podrías usar un modelo de lenguaje para generar texto
|
33 |
-
# Aquí se deja como placeholder
|
34 |
-
analysis = "Análisis generado por el modelo de lenguaje."
|
35 |
-
return analysis
|
36 |
-
|
37 |
-
@gpu_decorator(duration=600) # Ajusta la duración según tus necesidades
|
38 |
-
def process_and_plot(
|
39 |
-
file,
|
40 |
-
biomass_eq1, biomass_eq2, biomass_eq3,
|
41 |
-
biomass_param1, biomass_param2, biomass_param3,
|
42 |
-
biomass_bound1, biomass_bound2, biomass_bound3,
|
43 |
-
substrate_eq1, substrate_eq2, substrate_eq3,
|
44 |
-
substrate_param1, substrate_param2, substrate_param3,
|
45 |
-
substrate_bound1, substrate_bound2, substrate_bound3,
|
46 |
-
product_eq1, product_eq2, product_eq3,
|
47 |
-
product_param1, product_param2, product_param3,
|
48 |
-
product_bound1, product_bound2, product_bound3,
|
49 |
-
legend_position,
|
50 |
-
show_legend,
|
51 |
-
show_params,
|
52 |
-
biomass_eq_count,
|
53 |
-
substrate_eq_count,
|
54 |
-
product_eq_count,
|
55 |
-
device=None
|
56 |
-
):
|
57 |
-
# Leer el archivo Excel
|
58 |
-
df = pd.read_excel(file.name)
|
59 |
-
|
60 |
-
# Verificar que las columnas necesarias estén presentes
|
61 |
-
expected_columns = ['Tiempo', 'Biomasa', 'Sustrato', 'Producto']
|
62 |
-
for col in expected_columns:
|
63 |
-
if col not in df.columns:
|
64 |
-
raise KeyError(f"La columna esperada '{col}' no se encuentra en el archivo Excel.")
|
65 |
-
|
66 |
-
# Asignar los datos desde las columnas
|
67 |
-
time = df['Tiempo'].values
|
68 |
-
biomass_data = df['Biomasa'].values
|
69 |
-
substrate_data = df['Sustrato'].values
|
70 |
-
product_data = df['Producto'].values
|
71 |
-
|
72 |
-
# Convierte los contadores a enteros
|
73 |
-
biomass_eq_count = int(biomass_eq_count)
|
74 |
-
substrate_eq_count = int(substrate_eq_count)
|
75 |
-
product_eq_count = int(product_eq_count)
|
76 |
-
|
77 |
-
# Recolecta las ecuaciones, parámetros y límites según los contadores
|
78 |
-
biomass_eqs = [biomass_eq1, biomass_eq2, biomass_eq3][:biomass_eq_count]
|
79 |
-
biomass_params = [biomass_param1, biomass_param2, biomass_param3][:biomass_eq_count]
|
80 |
-
biomass_bounds = [biomass_bound1, biomass_bound2, biomass_bound3][:biomass_eq_count]
|
81 |
-
|
82 |
-
substrate_eqs = [substrate_eq1, substrate_eq2, substrate_eq3][:substrate_eq_count]
|
83 |
-
substrate_params = [substrate_param1, substrate_param2, substrate_param3][:substrate_eq_count]
|
84 |
-
substrate_bounds = [substrate_bound1, substrate_bound2, substrate_bound3][:substrate_eq_count]
|
85 |
-
|
86 |
-
product_eqs = [product_eq1, product_eq2, product_eq3][:product_eq_count]
|
87 |
-
product_params = [product_param1, product_param2, product_param3][:product_eq_count]
|
88 |
-
product_bounds = [product_bound1, product_bound2, product_bound3][:product_eq_count]
|
89 |
-
|
90 |
-
biomass_results = []
|
91 |
-
substrate_results = []
|
92 |
-
product_results = []
|
93 |
-
|
94 |
-
# Inicializar el modelo principal
|
95 |
-
main_model = BioprocessModel()
|
96 |
-
|
97 |
-
# Ajusta los modelos de Biomasa
|
98 |
-
for i in range(len(biomass_eqs)):
|
99 |
-
equation = biomass_eqs[i]
|
100 |
-
params_str = biomass_params[i]
|
101 |
-
bounds_str = biomass_bounds[i]
|
102 |
-
|
103 |
-
try:
|
104 |
-
main_model.set_model_biomass(equation, params_str)
|
105 |
-
except ValueError as ve:
|
106 |
-
raise ValueError(f"Error en la configuración del modelo de biomasa {i+1}: {ve}")
|
107 |
-
|
108 |
-
params = [param.strip() for param in params_str.split(',')]
|
109 |
-
lower_bounds, upper_bounds = parse_bounds(bounds_str, len(params))
|
110 |
-
|
111 |
-
try:
|
112 |
-
y_pred = main_model.fit_model(
|
113 |
-
'biomass', time, biomass_data,
|
114 |
-
bounds=(lower_bounds, upper_bounds)
|
115 |
-
)
|
116 |
-
biomass_results.append({
|
117 |
-
'model': main_model,
|
118 |
-
'y_pred': y_pred,
|
119 |
-
'equation': equation,
|
120 |
-
'params': main_model.params['biomass']
|
121 |
-
})
|
122 |
-
except Exception as e:
|
123 |
-
raise RuntimeError(f"Error al ajustar el modelo de biomasa {i+1}: {e}")
|
124 |
-
|
125 |
-
# Ajusta los modelos de Sustrato
|
126 |
-
for i in range(len(substrate_eqs)):
|
127 |
-
equation = substrate_eqs[i]
|
128 |
-
params_str = substrate_params[i]
|
129 |
-
bounds_str = substrate_bounds[i]
|
130 |
-
|
131 |
-
try:
|
132 |
-
main_model.set_model_substrate(equation, params_str)
|
133 |
-
except ValueError as ve:
|
134 |
-
raise ValueError(f"Error en la configuración del modelo de sustrato {i+1}: {ve}")
|
135 |
-
|
136 |
-
params = [param.strip() for param in params_str.split(',')]
|
137 |
-
lower_bounds, upper_bounds = parse_bounds(bounds_str, len(params))
|
138 |
-
|
139 |
-
try:
|
140 |
-
y_pred = main_model.fit_model(
|
141 |
-
'substrate', time, substrate_data,
|
142 |
-
bounds=(lower_bounds, upper_bounds)
|
143 |
-
)
|
144 |
-
substrate_results.append({
|
145 |
-
'model': main_model,
|
146 |
-
'y_pred': y_pred,
|
147 |
-
'equation': equation,
|
148 |
-
'params': main_model.params['substrate']
|
149 |
-
})
|
150 |
-
except Exception as e:
|
151 |
-
raise RuntimeError(f"Error al ajustar el modelo de sustrato {i+1}: {e}")
|
152 |
-
|
153 |
-
# Ajusta los modelos de Producto
|
154 |
-
for i in range(len(product_eqs)):
|
155 |
-
equation = product_eqs[i]
|
156 |
-
params_str = product_params[i]
|
157 |
-
bounds_str = product_bounds[i]
|
158 |
-
|
159 |
-
try:
|
160 |
-
main_model.set_model_product(equation, params_str)
|
161 |
-
except ValueError as ve:
|
162 |
-
raise ValueError(f"Error en la configuración del modelo de producto {i+1}: {ve}")
|
163 |
-
|
164 |
-
params = [param.strip() for param in params_str.split(',')]
|
165 |
-
lower_bounds, upper_bounds = parse_bounds(bounds_str, len(params))
|
166 |
-
|
167 |
-
try:
|
168 |
-
y_pred = main_model.fit_model(
|
169 |
-
'product', time, product_data,
|
170 |
-
bounds=(lower_bounds, upper_bounds)
|
171 |
-
)
|
172 |
-
product_results.append({
|
173 |
-
'model': main_model,
|
174 |
-
'y_pred': y_pred,
|
175 |
-
'equation': equation,
|
176 |
-
'params': main_model.params['product']
|
177 |
-
})
|
178 |
-
except Exception as e:
|
179 |
-
raise RuntimeError(f"Error al ajustar el modelo de producto {i+1}: {e}")
|
180 |
-
|
181 |
-
# Genera las gráficas
|
182 |
-
fig, axs = plt.subplots(3, 1, figsize=(10, 15))
|
183 |
-
|
184 |
-
# Gráfica de Biomasa
|
185 |
-
axs[0].plot(time, biomass_data, 'o', label='Datos de Biomasa')
|
186 |
-
for i, result in enumerate(biomass_results):
|
187 |
-
axs[0].plot(time, result['y_pred'], '-', label=f'Modelo de Biomasa {i+1}')
|
188 |
-
axs[0].set_xlabel('Tiempo')
|
189 |
-
axs[0].set_ylabel('Biomasa')
|
190 |
-
if show_legend:
|
191 |
-
axs[0].legend(loc=legend_position)
|
192 |
-
|
193 |
-
# Gráfica de Sustrato
|
194 |
-
axs[1].plot(time, substrate_data, 'o', label='Datos de Sustrato')
|
195 |
-
for i, result in enumerate(substrate_results):
|
196 |
-
axs[1].plot(time, result['y_pred'], '-', label=f'Modelo de Sustrato {i+1}')
|
197 |
-
axs[1].set_xlabel('Tiempo')
|
198 |
-
axs[1].set_ylabel('Sustrato')
|
199 |
-
if show_legend:
|
200 |
-
axs[1].legend(loc=legend_position)
|
201 |
-
|
202 |
-
# Gráfica de Producto
|
203 |
-
axs[2].plot(time, product_data, 'o', label='Datos de Producto')
|
204 |
-
for i, result in enumerate(product_results):
|
205 |
-
axs[2].plot(time, result['y_pred'], '-', label=f'Modelo de Producto {i+1}')
|
206 |
-
axs[2].set_xlabel('Tiempo')
|
207 |
-
axs[2].set_ylabel('Producto')
|
208 |
-
if show_legend:
|
209 |
-
axs[2].legend(loc=legend_position)
|
210 |
-
|
211 |
-
plt.tight_layout()
|
212 |
-
buf = io.BytesIO()
|
213 |
-
plt.savefig(buf, format='png')
|
214 |
-
buf.seek(0)
|
215 |
-
image = Image.open(buf)
|
216 |
-
|
217 |
-
prompt = f"""
|
218 |
-
Eres un experto en modelado de bioprocesos.
|
219 |
-
Analiza los siguientes resultados experimentales y proporciona un veredicto sobre la calidad de los modelos, sugiriendo mejoras si es necesario.
|
220 |
-
Biomasa:
|
221 |
-
{biomass_results}
|
222 |
-
Sustrato:
|
223 |
-
{substrate_results}
|
224 |
-
Producto:
|
225 |
-
{product_results}
|
226 |
-
"""
|
227 |
-
analysis = generate_analysis(prompt, device=device)
|
228 |
-
|
229 |
-
return image, analysis
|
|
|
1 |
+
# -*- coding: utf-8 -*-
|
2 |
+
"""PrediLectia - Gradio Final v2 with Multiple Y-Axes in Combined Plot.ipynb"""
|
3 |
+
|
4 |
+
# Instalación de librerías necesarias
|
5 |
+
#!pip install gradio seaborn scipy -q
|
6 |
+
import os
|
7 |
+
os.system('pip install gradio seaborn scipy scikit-learn openpyxl pydantic==1.10.0')
|
8 |
+
|
9 |
+
from pydantic import BaseModel, ConfigDict
|
10 |
+
|
11 |
+
class YourModel(BaseModel):
|
12 |
+
class Config:
|
13 |
+
arbitrary_types_allowed = True
|
14 |
|
15 |
import numpy as np
|
16 |
import pandas as pd
|
17 |
import matplotlib.pyplot as plt
|
18 |
+
import seaborn as sns
|
19 |
+
from scipy.integrate import odeint
|
20 |
+
from scipy.interpolate import interp1d
|
21 |
+
from scipy.optimize import curve_fit
|
22 |
+
from sklearn.metrics import mean_squared_error
|
23 |
+
import gradio as gr
|
24 |
import io
|
25 |
+
from PIL import Image
|
26 |
+
|
27 |
+
# Definición de la clase BioprocessModel
|
28 |
+
class BioprocessModel:
|
29 |
+
def __init__(self):
|
30 |
+
self.params = {}
|
31 |
+
self.r2 = {}
|
32 |
+
self.rmse = {}
|
33 |
+
self.datax = []
|
34 |
+
self.datas = []
|
35 |
+
self.datap = []
|
36 |
+
self.dataxp = []
|
37 |
+
self.datasp = []
|
38 |
+
self.datapp = []
|
39 |
+
self.datax_std = []
|
40 |
+
self.datas_std = []
|
41 |
+
self.datap_std = []
|
42 |
+
|
43 |
+
# Funciones modelo analíticas
|
44 |
+
@staticmethod
|
45 |
+
def logistic(time, xo, xm, um):
|
46 |
+
return (xo * np.exp(um * time)) / (1 - (xo / xm) * (1 - np.exp(um * time)))
|
47 |
+
|
48 |
+
@staticmethod
|
49 |
+
def substrate(time, so, p, q, xo, xm, um):
|
50 |
+
return so - (p * xo * ((np.exp(um * time)) / (1 - (xo / xm) * (1 - np.exp(um * time))) - 1)) - \
|
51 |
+
(q * (xm / um) * np.log(1 - (xo / xm) * (1 - np.exp(um * time))))
|
52 |
+
|
53 |
+
@staticmethod
|
54 |
+
def product(time, po, alpha, beta, xo, xm, um):
|
55 |
+
return po + (alpha * xo * ((np.exp(um * time) / (1 - (xo / xm) * (1 - np.exp(um * time)))) - 1)) + \
|
56 |
+
(beta * (xm / um) * np.log(1 - (xo / xm) * (1 - np.exp(um * time))))
|
57 |
+
|
58 |
+
# Funciones modelo diferenciales
|
59 |
+
@staticmethod
|
60 |
+
def logistic_diff(X, t, params):
|
61 |
+
xo, xm, um = params
|
62 |
+
dXdt = um * X * (1 - X / xm)
|
63 |
+
return dXdt
|
64 |
+
|
65 |
+
def substrate_diff(self, S, t, params, biomass_params, X_func):
|
66 |
+
so, p, q = params
|
67 |
+
xo, xm, um = biomass_params
|
68 |
+
X_t = X_func(t)
|
69 |
+
dSdt = -p * (um * X_t * (1 - X_t / xm)) - q * X_t
|
70 |
+
return dSdt
|
71 |
+
|
72 |
+
def product_diff(self, P, t, params, biomass_params, X_func):
|
73 |
+
po, alpha, beta = params
|
74 |
+
xo, xm, um = biomass_params
|
75 |
+
X_t = X_func(t)
|
76 |
+
dPdt = alpha * (um * X_t * (1 - X_t / xm)) + beta * X_t
|
77 |
+
return dPdt
|
78 |
+
|
79 |
+
# Métodos de procesamiento y ajuste de datos
|
80 |
+
def process_data(self, df):
|
81 |
+
# Obtener todas las columnas que contengan "Biomasa", "Sustrato", y "Producto"
|
82 |
+
biomass_cols = [col for col in df.columns if col[1] == 'Biomasa']
|
83 |
+
substrate_cols = [col for col in df.columns if col[1] == 'Sustrato']
|
84 |
+
product_cols = [col for col in df.columns if col[1] == 'Producto']
|
85 |
+
|
86 |
+
# Procesar los datos de tiempo
|
87 |
+
time_col = [col for col in df.columns if col[1] == 'Tiempo'][0]
|
88 |
+
time = df[time_col].values
|
89 |
+
|
90 |
+
# Procesar los datos de biomasa
|
91 |
+
data_biomass = [df[col].values for col in biomass_cols]
|
92 |
+
data_biomass = np.array(data_biomass) # shape (num_experiments, num_time_points)
|
93 |
+
self.datax.append(data_biomass)
|
94 |
+
self.dataxp.append(np.mean(data_biomass, axis=0))
|
95 |
+
self.datax_std.append(np.std(data_biomass, axis=0, ddof=1))
|
96 |
+
|
97 |
+
# Procesar los datos de sustrato
|
98 |
+
data_substrate = [df[col].values for col in substrate_cols]
|
99 |
+
data_substrate = np.array(data_substrate)
|
100 |
+
self.datas.append(data_substrate)
|
101 |
+
self.datasp.append(np.mean(data_substrate, axis=0))
|
102 |
+
self.datas_std.append(np.std(data_substrate, axis=0, ddof=1))
|
103 |
+
|
104 |
+
# Procesar los datos de producto
|
105 |
+
data_product = [df[col].values for col in product_cols]
|
106 |
+
data_product = np.array(data_product)
|
107 |
+
self.datap.append(data_product)
|
108 |
+
self.datapp.append(np.mean(data_product, axis=0))
|
109 |
+
self.datap_std.append(np.std(data_product, axis=0, ddof=1))
|
110 |
+
|
111 |
+
self.time = time
|
112 |
+
|
113 |
+
def fit_model(self, model_type='logistic'):
|
114 |
+
if model_type == 'logistic':
|
115 |
+
self.fit_biomass = self.fit_biomass_logistic
|
116 |
+
self.fit_substrate = self.fit_substrate_logistic
|
117 |
+
self.fit_product = self.fit_product_logistic
|
118 |
+
# Puedes agregar más modelos aquí si los necesitas.
|
119 |
+
|
120 |
+
def fit_biomass_logistic(self, time, biomass, bounds):
|
121 |
+
popt, _ = curve_fit(self.logistic, time, biomass, bounds=bounds, maxfev=10000)
|
122 |
+
self.params['biomass'] = {'xo': popt[0], 'xm': popt[1], 'um': popt[2]}
|
123 |
+
y_pred = self.logistic(time, *popt)
|
124 |
+
self.r2['biomass'] = 1 - (np.sum((biomass - y_pred) ** 2) / np.sum((biomass - np.mean(biomass)) ** 2))
|
125 |
+
self.rmse['biomass'] = np.sqrt(mean_squared_error(biomass, y_pred))
|
126 |
+
return y_pred
|
127 |
+
|
128 |
+
def fit_substrate_logistic(self, time, substrate, biomass_params, bounds):
|
129 |
+
popt, _ = curve_fit(lambda t, so, p, q: self.substrate(t, so, p, q, *biomass_params.values()),
|
130 |
+
time, substrate, bounds=bounds)
|
131 |
+
self.params['substrate'] = {'so': popt[0], 'p': popt[1], 'q': popt[2]}
|
132 |
+
y_pred = self.substrate(time, *popt, *biomass_params.values())
|
133 |
+
self.r2['substrate'] = 1 - (np.sum((substrate - y_pred) ** 2) / np.sum((substrate - np.mean(substrate)) ** 2))
|
134 |
+
self.rmse['substrate'] = np.sqrt(mean_squared_error(substrate, y_pred))
|
135 |
+
return y_pred
|
136 |
+
|
137 |
+
def fit_product_logistic(self, time, product, biomass_params, bounds):
|
138 |
+
popt, _ = curve_fit(lambda t, po, alpha, beta: self.product(t, po, alpha, beta, *biomass_params.values()),
|
139 |
+
time, product, bounds=bounds)
|
140 |
+
self.params['product'] = {'po': popt[0], 'alpha': popt[1], 'beta': popt[2]}
|
141 |
+
y_pred = self.product(time, *popt, *biomass_params.values())
|
142 |
+
self.r2['product'] = 1 - (np.sum((product - y_pred) ** 2) / np.sum((product - np.mean(product)) ** 2))
|
143 |
+
self.rmse['product'] = np.sqrt(mean_squared_error(product, y_pred))
|
144 |
+
return y_pred
|
145 |
+
|
146 |
+
# Métodos de visualización de resultados
|
147 |
+
def generate_fine_time_grid(self, time):
|
148 |
+
# Generar una malla temporal más fina para curvas suaves
|
149 |
+
time_fine = np.linspace(time.min(), time.max(), 500)
|
150 |
+
return time_fine
|
151 |
+
|
152 |
+
def solve_differential_equations(self, time, initial_conditions, params):
|
153 |
+
# Resolver la ecuación diferencial para biomasa
|
154 |
+
xo, xm, um = params['biomass'].values()
|
155 |
+
biomass_params = [xo, xm, um]
|
156 |
+
time_fine = self.generate_fine_time_grid(time)
|
157 |
+
|
158 |
+
# Resolver biomasa
|
159 |
+
X0 = xo
|
160 |
+
X = odeint(self.logistic_diff, X0, time_fine, args=(biomass_params,)).flatten()
|
161 |
+
|
162 |
+
# Crear función de interpolación para X(t)
|
163 |
+
X_func = interp1d(time_fine, X, kind='linear', fill_value="extrapolate")
|
164 |
+
|
165 |
+
# Resolver sustrato
|
166 |
+
so, p, q = params['substrate'].values()
|
167 |
+
substrate_params = [so, p, q]
|
168 |
+
S0 = so
|
169 |
+
S = odeint(self.substrate_diff, S0, time_fine, args=(substrate_params, biomass_params, X_func)).flatten()
|
170 |
+
|
171 |
+
# Resolver producto
|
172 |
+
po, alpha, beta = params['product'].values()
|
173 |
+
product_params = [po, alpha, beta]
|
174 |
+
P0 = po
|
175 |
+
P = odeint(self.product_diff, P0, time_fine, args=(product_params, biomass_params, X_func)).flatten()
|
176 |
+
|
177 |
+
return X, S, P, time_fine
|
178 |
+
|
179 |
+
def plot_results(self, time, biomass, substrate, product,
|
180 |
+
y_pred_biomass, y_pred_substrate, y_pred_product,
|
181 |
+
biomass_std=None, substrate_std=None, product_std=None,
|
182 |
+
experiment_name='', legend_position='best', params_position='upper right',
|
183 |
+
show_legend=True, show_params=True,
|
184 |
+
style='whitegrid',
|
185 |
+
line_color='#0000FF', point_color='#000000', line_style='-', marker_style='o',
|
186 |
+
use_differential=False):
|
187 |
+
sns.set_style(style) # Establecer el estilo seleccionado
|
188 |
+
|
189 |
+
if use_differential:
|
190 |
+
y_pred_biomass, y_pred_substrate, y_pred_product, time_to_plot = self.solve_differential_equations(
|
191 |
+
time, [biomass[0], substrate[0], product[0]], self.params)
|
192 |
+
else:
|
193 |
+
time_to_plot = time
|
194 |
+
|
195 |
+
fig, (ax1, ax2, ax3) = plt.subplots(3, 1, figsize=(10, 15))
|
196 |
+
fig.suptitle(f'{experiment_name}', fontsize=16)
|
197 |
+
|
198 |
+
plots = [
|
199 |
+
(ax1, biomass, y_pred_biomass, biomass_std, 'Biomasa', 'Modelo', self.params['biomass'],
|
200 |
+
self.r2['biomass'], self.rmse['biomass']),
|
201 |
+
(ax2, substrate, y_pred_substrate, substrate_std, 'Sustrato', 'Modelo', self.params['substrate'],
|
202 |
+
self.r2['substrate'], self.rmse['substrate']),
|
203 |
+
(ax3, product, y_pred_product, product_std, 'Producto', 'Modelo', self.params['product'],
|
204 |
+
self.r2['product'], self.rmse['product'])
|
205 |
+
]
|
206 |
+
|
207 |
+
for idx, (ax, data, y_pred, data_std, ylabel, model_name, params, r2, rmse) in enumerate(plots):
|
208 |
+
if data_std is not None:
|
209 |
+
ax.errorbar(time, data, yerr=data_std, fmt=marker_style, color=point_color,
|
210 |
+
label='Datos experimentales', capsize=5)
|
211 |
+
else:
|
212 |
+
ax.plot(time, data, marker=marker_style, linestyle='', color=point_color,
|
213 |
+
label='Datos experimentales')
|
214 |
+
if use_differential:
|
215 |
+
ax.plot(time_to_plot, y_pred, linestyle=line_style, color=line_color, label=model_name)
|
216 |
+
else:
|
217 |
+
ax.plot(time, y_pred, linestyle=line_style, color=line_color, label=model_name)
|
218 |
+
ax.set_xlabel('Tiempo')
|
219 |
+
ax.set_ylabel(ylabel)
|
220 |
+
if show_legend:
|
221 |
+
ax.legend(loc=legend_position)
|
222 |
+
ax.set_title(f'{ylabel}')
|
223 |
+
|
224 |
+
if show_params:
|
225 |
+
param_text = '\n'.join([f"{k} = {v:.4f}" for k, v in params.items()])
|
226 |
+
text = f"{param_text}\nR² = {r2:.4f}\nRMSE = {rmse:.4f}"
|
227 |
+
|
228 |
+
# Si la posición es 'outside right', ajustar la posición del texto
|
229 |
+
if params_position == 'outside right':
|
230 |
+
bbox_props = dict(boxstyle='round', facecolor='white', alpha=0.5)
|
231 |
+
ax.annotate(text, xy=(1.05, 0.5), xycoords='axes fraction',
|
232 |
+
verticalalignment='center', bbox=bbox_props)
|
233 |
+
else:
|
234 |
+
if params_position in ['upper right', 'lower right']:
|
235 |
+
text_x = 0.95
|
236 |
+
ha = 'right'
|
237 |
+
else:
|
238 |
+
text_x = 0.05
|
239 |
+
ha = 'left'
|
240 |
+
|
241 |
+
if params_position in ['upper right', 'upper left']:
|
242 |
+
text_y = 0.95
|
243 |
+
va = 'top'
|
244 |
+
else:
|
245 |
+
text_y = 0.05
|
246 |
+
va = 'bottom'
|
247 |
+
|
248 |
+
ax.text(text_x, text_y, text, transform=ax.transAxes,
|
249 |
+
verticalalignment=va, horizontalalignment=ha,
|
250 |
+
bbox={'boxstyle': 'round', 'facecolor': 'white', 'alpha': 0.5})
|
251 |
+
|
252 |
+
plt.tight_layout()
|
253 |
+
return fig
|
254 |
+
|
255 |
+
def plot_combined_results(self, time, biomass, substrate, product,
|
256 |
+
y_pred_biomass, y_pred_substrate, y_pred_product,
|
257 |
+
biomass_std=None, substrate_std=None, product_std=None,
|
258 |
+
experiment_name='', legend_position='best', params_position='upper right',
|
259 |
+
show_legend=True, show_params=True,
|
260 |
+
style='whitegrid',
|
261 |
+
line_color='#0000FF', point_color='#000000', line_style='-', marker_style='o',
|
262 |
+
use_differential=False):
|
263 |
+
sns.set_style(style) # Establecer el estilo seleccionado
|
264 |
+
|
265 |
+
if use_differential:
|
266 |
+
y_pred_biomass, y_pred_substrate, y_pred_product, time_to_plot = self.solve_differential_equations(
|
267 |
+
time, [biomass[0], substrate[0], product[0]], self.params)
|
268 |
+
else:
|
269 |
+
time_to_plot = time
|
270 |
+
|
271 |
+
fig, ax1 = plt.subplots(figsize=(10, 7))
|
272 |
+
fig.suptitle(f'{experiment_name}', fontsize=16)
|
273 |
+
|
274 |
+
# Colores específicos para cada variable
|
275 |
+
colors = {'Biomasa': 'blue', 'Sustrato': 'green', 'Producto': 'red'}
|
276 |
+
|
277 |
+
# Plot Biomasa en ax1
|
278 |
+
ax1.set_xlabel('Tiempo')
|
279 |
+
ax1.set_ylabel('Biomasa', color=colors['Biomasa'])
|
280 |
+
if biomass_std is not None:
|
281 |
+
ax1.errorbar(time, biomass, yerr=biomass_std, fmt=marker_style, color=colors['Biomasa'],
|
282 |
+
label='Biomasa (Datos)', capsize=5)
|
283 |
+
else:
|
284 |
+
ax1.plot(time, biomass, marker=marker_style, linestyle='', color=colors['Biomasa'],
|
285 |
+
label='Biomasa (Datos)')
|
286 |
+
if use_differential:
|
287 |
+
ax1.plot(time_to_plot, y_pred_biomass, linestyle=line_style, color=colors['Biomasa'],
|
288 |
+
label='Biomasa (Modelo)')
|
289 |
+
else:
|
290 |
+
ax1.plot(time, y_pred_biomass, linestyle=line_style, color=colors['Biomasa'],
|
291 |
+
label='Biomasa (Modelo)')
|
292 |
+
ax1.tick_params(axis='y', labelcolor=colors['Biomasa'])
|
293 |
+
|
294 |
+
# Crear segundo eje y para Sustrato
|
295 |
+
ax2 = ax1.twinx()
|
296 |
+
ax2.set_ylabel('Sustrato', color=colors['Sustrato'])
|
297 |
+
if substrate_std is not None:
|
298 |
+
ax2.errorbar(time, substrate, yerr=substrate_std, fmt=marker_style, color=colors['Sustrato'],
|
299 |
+
label='Sustrato (Datos)', capsize=5)
|
300 |
+
else:
|
301 |
+
ax2.plot(time, substrate, marker=marker_style, linestyle='', color=colors['Sustrato'],
|
302 |
+
label='Sustrato (Datos)')
|
303 |
+
if use_differential:
|
304 |
+
ax2.plot(time_to_plot, y_pred_substrate, linestyle=line_style, color=colors['Sustrato'],
|
305 |
+
label='Sustrato (Modelo)')
|
306 |
+
else:
|
307 |
+
ax2.plot(time, y_pred_substrate, linestyle=line_style, color=colors['Sustrato'],
|
308 |
+
label='Sustrato (Modelo)')
|
309 |
+
ax2.tick_params(axis='y', labelcolor=colors['Sustrato'])
|
310 |
+
|
311 |
+
# Crear tercer eje y para Producto
|
312 |
+
ax3 = ax1.twinx()
|
313 |
+
# Desplazar el tercer eje para evitar superposición
|
314 |
+
ax3.spines["right"].set_position(("axes", 1.1))
|
315 |
+
ax3.set_frame_on(True)
|
316 |
+
ax3.patch.set_visible(False)
|
317 |
+
for sp in ax3.spines.values():
|
318 |
+
sp.set_visible(True)
|
319 |
+
|
320 |
+
ax3.set_ylabel('Producto', color=colors['Producto'])
|
321 |
+
if product_std is not None:
|
322 |
+
ax3.errorbar(time, product, yerr=product_std, fmt=marker_style, color=colors['Producto'],
|
323 |
+
label='Producto (Datos)', capsize=5)
|
324 |
+
else:
|
325 |
+
ax3.plot(time, product, marker=marker_style, linestyle='', color=colors['Producto'],
|
326 |
+
label='Producto (Datos)')
|
327 |
+
if use_differential:
|
328 |
+
ax3.plot(time_to_plot, y_pred_product, linestyle=line_style, color=colors['Producto'],
|
329 |
+
label='Producto (Modelo)')
|
330 |
+
else:
|
331 |
+
ax3.plot(time, y_pred_product, linestyle=line_style, color=colors['Producto'],
|
332 |
+
label='Producto (Modelo)')
|
333 |
+
ax3.tick_params(axis='y', labelcolor=colors['Producto'])
|
334 |
+
|
335 |
+
# Manejo de leyendas
|
336 |
+
lines_labels = [ax.get_legend_handles_labels() for ax in [ax1, ax2, ax3]]
|
337 |
+
lines, labels = [sum(lol, []) for lol in zip(*lines_labels)]
|
338 |
+
if show_legend:
|
339 |
+
ax1.legend(lines, labels, loc=legend_position)
|
340 |
+
|
341 |
+
# Mostrar parámetros y estadísticas en el gráfico
|
342 |
+
if show_params:
|
343 |
+
param_text_biomass = '\n'.join([f"{k} = {v:.4f}" for k, v in self.params['biomass'].items()])
|
344 |
+
text_biomass = f"Biomasa:\n{param_text_biomass}\nR² = {self.r2['biomass']:.4f}\nRMSE = {self.rmse['biomass']:.4f}"
|
345 |
+
|
346 |
+
param_text_substrate = '\n'.join([f"{k} = {v:.4f}" for k, v in self.params['substrate'].items()])
|
347 |
+
text_substrate = f"Sustrato:\n{param_text_substrate}\nR² = {self.r2['substrate']:.4f}\nRMSE = {self.rmse['substrate']:.4f}"
|
348 |
+
|
349 |
+
param_text_product = '\n'.join([f"{k} = {v:.4f}" for k, v in self.params['product'].items()])
|
350 |
+
text_product = f"Producto:\n{param_text_product}\nR² = {self.r2['product']:.4f}\nRMSE = {self.rmse['product']:.4f}"
|
351 |
+
|
352 |
+
total_text = f"{text_biomass}\n\n{text_substrate}\n\n{text_product}"
|
353 |
+
|
354 |
+
if params_position == 'outside right':
|
355 |
+
bbox_props = dict(boxstyle='round', facecolor='white', alpha=0.5)
|
356 |
+
ax3.annotate(total_text, xy=(1.2, 0.5), xycoords='axes fraction',
|
357 |
+
verticalalignment='center', bbox=bbox_props)
|
358 |
+
else:
|
359 |
+
if params_position in ['upper right', 'lower right']:
|
360 |
+
text_x = 0.95
|
361 |
+
ha = 'right'
|
362 |
+
else:
|
363 |
+
text_x = 0.05
|
364 |
+
ha = 'left'
|
365 |
+
|
366 |
+
if params_position in ['upper right', 'upper left']:
|
367 |
+
text_y = 0.95
|
368 |
+
va = 'top'
|
369 |
+
else:
|
370 |
+
text_y = 0.05
|
371 |
+
va = 'bottom'
|
372 |
+
|
373 |
+
ax1.text(text_x, text_y, total_text, transform=ax1.transAxes,
|
374 |
+
verticalalignment=va, horizontalalignment=ha,
|
375 |
+
bbox={'boxstyle': 'round', 'facecolor': 'white', 'alpha': 0.5})
|
376 |
+
|
377 |
+
plt.tight_layout()
|
378 |
+
return fig
|
379 |
+
|
380 |
+
# Función de procesamiento de datos
|
381 |
+
def process_data(file, legend_position, params_position, model_type, experiment_names, lower_bounds, upper_bounds,
|
382 |
+
mode='independent', style='whitegrid', line_color='#0000FF', point_color='#000000',
|
383 |
+
line_style='-', marker_style='o', show_legend=True, show_params=True, use_differential=False):
|
384 |
+
# Leer todas las hojas del archivo Excel
|
385 |
+
xls = pd.ExcelFile(file.name)
|
386 |
+
sheet_names = xls.sheet_names
|
387 |
+
|
388 |
+
model = BioprocessModel()
|
389 |
+
model.fit_model(model_type)
|
390 |
+
figures = []
|
391 |
+
|
392 |
+
# Si no se proporcionan suficientes límites, usar valores predeterminados
|
393 |
+
default_lower_bounds = (0, 0, 0)
|
394 |
+
default_upper_bounds = (np.inf, np.inf, np.inf)
|
395 |
+
|
396 |
+
experiment_counter = 0 # Contador global de experimentos
|
397 |
+
|
398 |
+
for sheet_name in sheet_names:
|
399 |
+
df = pd.read_excel(file.name, sheet_name=sheet_name, header=[0, 1])
|
400 |
+
|
401 |
+
# Procesar datos
|
402 |
+
model.process_data(df)
|
403 |
+
time = model.time
|
404 |
+
|
405 |
+
if mode == 'independent':
|
406 |
+
# Modo independiente: iterar sobre cada experimento
|
407 |
+
num_experiments = len(df.columns.levels[0])
|
408 |
+
for idx in range(num_experiments):
|
409 |
+
col = df.columns.levels[0][idx]
|
410 |
+
time = df[(col, 'Tiempo')].dropna().values
|
411 |
+
biomass = df[(col, 'Biomasa')].dropna().values
|
412 |
+
substrate = df[(col, 'Sustrato')].dropna().values
|
413 |
+
product = df[(col, 'Producto')].dropna().values
|
414 |
+
|
415 |
+
# Si hay replicados en el experimento, calcular la desviación estándar
|
416 |
+
biomass_std = None
|
417 |
+
substrate_std = None
|
418 |
+
product_std = None
|
419 |
+
if biomass.ndim > 1:
|
420 |
+
biomass_std = np.std(biomass, axis=0, ddof=1)
|
421 |
+
biomass = np.mean(biomass, axis=0)
|
422 |
+
if substrate.ndim > 1:
|
423 |
+
substrate_std = np.std(substrate, axis=0, ddof=1)
|
424 |
+
substrate = np.mean(substrate, axis=0)
|
425 |
+
if product.ndim > 1:
|
426 |
+
product_std = np.std(product, axis=0, ddof=1)
|
427 |
+
product = np.mean(product, axis=0)
|
428 |
+
|
429 |
+
# Obtener límites o usar valores predeterminados
|
430 |
+
lower_bound = lower_bounds[experiment_counter] if experiment_counter < len(lower_bounds) else default_lower_bounds
|
431 |
+
upper_bound = upper_bounds[experiment_counter] if experiment_counter < len(upper_bounds) else default_upper_bounds
|
432 |
+
bounds = (lower_bound, upper_bound)
|
433 |
+
|
434 |
+
# Ajustar el modelo
|
435 |
+
y_pred_biomass = model.fit_biomass(time, biomass, bounds)
|
436 |
+
y_pred_substrate = model.fit_substrate(time, substrate, model.params['biomass'], bounds)
|
437 |
+
y_pred_product = model.fit_product(time, product, model.params['biomass'], bounds)
|
438 |
+
|
439 |
+
# Usar el nombre del experimento proporcionado o un nombre por defecto
|
440 |
+
experiment_name = experiment_names[experiment_counter] if experiment_counter < len(experiment_names) else f"Tratamiento {experiment_counter + 1}"
|
441 |
+
|
442 |
+
if mode == 'combinado':
|
443 |
+
fig = model.plot_combined_results(time, biomass, substrate, product,
|
444 |
+
y_pred_biomass, y_pred_substrate, y_pred_product,
|
445 |
+
biomass_std, substrate_std, product_std,
|
446 |
+
experiment_name, legend_position, params_position,
|
447 |
+
show_legend, show_params,
|
448 |
+
style,
|
449 |
+
line_color, point_color, line_style, marker_style,
|
450 |
+
use_differential)
|
451 |
+
else:
|
452 |
+
fig = model.plot_results(time, biomass, substrate, product,
|
453 |
+
y_pred_biomass, y_pred_substrate, y_pred_product,
|
454 |
+
biomass_std, substrate_std, product_std,
|
455 |
+
experiment_name, legend_position, params_position,
|
456 |
+
show_legend, show_params,
|
457 |
+
style,
|
458 |
+
line_color, point_color, line_style, marker_style,
|
459 |
+
use_differential)
|
460 |
+
figures.append(fig)
|
461 |
+
|
462 |
+
experiment_counter += 1
|
463 |
+
|
464 |
+
elif mode == 'average':
|
465 |
+
# Modo promedio: usar dataxp, datasp y datapp
|
466 |
+
time = df[(df.columns.levels[0][0], 'Tiempo')].dropna().values
|
467 |
+
biomass = model.dataxp[-1]
|
468 |
+
substrate = model.datasp[-1]
|
469 |
+
product = model.datapp[-1]
|
470 |
+
|
471 |
+
# Obtener las desviaciones estándar
|
472 |
+
biomass_std = model.datax_std[-1]
|
473 |
+
substrate_std = model.datas_std[-1]
|
474 |
+
product_std = model.datap_std[-1]
|
475 |
+
|
476 |
+
# Obtener límites o usar valores predeterminados
|
477 |
+
lower_bound = lower_bounds[experiment_counter] if experiment_counter < len(lower_bounds) else default_lower_bounds
|
478 |
+
upper_bound = upper_bounds[experiment_counter] if experiment_counter < len(upper_bounds) else default_upper_bounds
|
479 |
+
bounds = (lower_bound, upper_bound)
|
480 |
+
|
481 |
+
# Ajustar el modelo
|
482 |
+
y_pred_biomass = model.fit_biomass(time, biomass, bounds)
|
483 |
+
y_pred_substrate = model.fit_substrate(time, substrate, model.params['biomass'], bounds)
|
484 |
+
y_pred_product = model.fit_product(time, product, model.params['biomass'], bounds)
|
485 |
+
|
486 |
+
# Usar el nombre del experimento proporcionado o un nombre por defecto
|
487 |
+
experiment_name = experiment_names[experiment_counter] if experiment_counter < len(experiment_names) else f"Tratamiento {experiment_counter + 1}"
|
488 |
+
|
489 |
+
if mode == 'combinado':
|
490 |
+
fig = model.plot_combined_results(time, biomass, substrate, product,
|
491 |
+
y_pred_biomass, y_pred_substrate, y_pred_product,
|
492 |
+
biomass_std, substrate_std, product_std,
|
493 |
+
experiment_name, legend_position, params_position,
|
494 |
+
show_legend, show_params,
|
495 |
+
style,
|
496 |
+
line_color, point_color, line_style, marker_style,
|
497 |
+
use_differential)
|
498 |
+
else:
|
499 |
+
fig = model.plot_results(time, biomass, substrate, product,
|
500 |
+
y_pred_biomass, y_pred_substrate, y_pred_product,
|
501 |
+
biomass_std, substrate_std, product_std,
|
502 |
+
experiment_name, legend_position, params_position,
|
503 |
+
show_legend, show_params,
|
504 |
+
style,
|
505 |
+
line_color, point_color, line_style, marker_style,
|
506 |
+
use_differential)
|
507 |
+
figures.append(fig)
|
508 |
+
|
509 |
+
experiment_counter += 1
|
510 |
+
|
511 |
+
elif mode == 'combinado':
|
512 |
+
# Modo combinado: combinar las gráficas en una sola
|
513 |
+
time = df[(df.columns.levels[0][0], 'Tiempo')].dropna().values
|
514 |
+
biomass = model.dataxp[-1]
|
515 |
+
substrate = model.datasp[-1]
|
516 |
+
product = model.datapp[-1]
|
517 |
+
|
518 |
+
# Obtener las desviaciones estándar
|
519 |
+
biomass_std = model.datax_std[-1]
|
520 |
+
substrate_std = model.datas_std[-1]
|
521 |
+
product_std = model.datap_std[-1]
|
522 |
+
|
523 |
+
# Obtener límites o usar valores predeterminados
|
524 |
+
lower_bound = lower_bounds[experiment_counter] if experiment_counter < len(lower_bounds) else default_lower_bounds
|
525 |
+
upper_bound = upper_bounds[experiment_counter] if experiment_counter < len(upper_bounds) else default_upper_bounds
|
526 |
+
bounds = (lower_bound, upper_bound)
|
527 |
+
|
528 |
+
# Ajustar el modelo
|
529 |
+
y_pred_biomass = model.fit_biomass(time, biomass, bounds)
|
530 |
+
y_pred_substrate = model.fit_substrate(time, substrate, model.params['biomass'], bounds)
|
531 |
+
y_pred_product = model.fit_product(time, product, model.params['biomass'], bounds)
|
532 |
+
|
533 |
+
# Usar el nombre del experimento proporcionado o un nombre por defecto
|
534 |
+
experiment_name = experiment_names[experiment_counter] if experiment_counter < len(experiment_names) else f"Tratamiento {experiment_counter + 1}"
|
535 |
+
|
536 |
+
fig = model.plot_combined_results(time, biomass, substrate, product,
|
537 |
+
y_pred_biomass, y_pred_substrate, y_pred_product,
|
538 |
+
biomass_std, substrate_std, product_std,
|
539 |
+
experiment_name, legend_position, params_position,
|
540 |
+
show_legend, show_params,
|
541 |
+
style,
|
542 |
+
line_color, point_color, line_style, marker_style,
|
543 |
+
use_differential)
|
544 |
+
figures.append(fig)
|
545 |
+
|
546 |
+
experiment_counter += 1
|
547 |
+
|
548 |
+
return figures
|
549 |
+
|
550 |
+
def create_interface():
|
551 |
+
with gr.Blocks() as demo:
|
552 |
+
gr.Markdown("# Modelos de Bioproceso: Logístico y Luedeking-Piret")
|
553 |
+
gr.Markdown(
|
554 |
+
"Sube un archivo Excel con múltiples pestañas. Cada pestaña debe contener columnas 'Tiempo', 'Biomasa', 'Sustrato' y 'Producto' para cada experimento.")
|
555 |
+
|
556 |
+
file_input = gr.File(label="Subir archivo Excel")
|
557 |
+
|
558 |
+
with gr.Row():
|
559 |
+
with gr.Column():
|
560 |
+
legend_position = gr.Radio(
|
561 |
+
choices=["upper left", "upper right", "lower left", "lower right", "best"],
|
562 |
+
label="Posición de la leyenda",
|
563 |
+
value="best"
|
564 |
+
)
|
565 |
+
show_legend = gr.Checkbox(label="Mostrar Leyenda", value=True)
|
566 |
+
|
567 |
+
with gr.Column():
|
568 |
+
params_positions = ["upper left", "upper right", "lower left", "lower right", "outside right"]
|
569 |
+
params_position = gr.Radio(
|
570 |
+
choices=params_positions,
|
571 |
+
label="Posición de los parámetros",
|
572 |
+
value="upper right"
|
573 |
+
)
|
574 |
+
show_params = gr.Checkbox(label="Mostrar Parámetros", value=True)
|
575 |
+
|
576 |
+
model_type = gr.Radio(["logistic"], label="Tipo de Modelo", value="logistic")
|
577 |
+
mode = gr.Radio(["independent", "average", "combinado"], label="Modo de Análisis", value="independent")
|
578 |
+
|
579 |
+
use_differential = gr.Checkbox(label="Usar ecuaciones diferenciales para graficar", value=False)
|
580 |
+
|
581 |
+
experiment_names = gr.Textbox(
|
582 |
+
label="Nombres de los experimentos (uno por línea)",
|
583 |
+
placeholder="Experimento 1\nExperimento 2\n...",
|
584 |
+
lines=5
|
585 |
+
)
|
586 |
+
|
587 |
+
with gr.Row():
|
588 |
+
with gr.Column():
|
589 |
+
lower_bounds = gr.Textbox(
|
590 |
+
label="Lower Bounds (uno por línea, formato: xo,xm,um)",
|
591 |
+
placeholder="0,0,0\n0,0,0\n...",
|
592 |
+
lines=5
|
593 |
+
)
|
594 |
+
|
595 |
+
with gr.Column():
|
596 |
+
upper_bounds = gr.Textbox(
|
597 |
+
label="Upper Bounds (uno por línea, formato: xo,xm,um)",
|
598 |
+
placeholder="inf,inf,inf\ninf,inf,inf\n...",
|
599 |
+
lines=5
|
600 |
+
)
|
601 |
+
|
602 |
+
# Añadir un desplegable para seleccionar el estilo del gráfico
|
603 |
+
styles = ['white', 'dark', 'whitegrid', 'darkgrid', 'ticks']
|
604 |
+
style_dropdown = gr.Dropdown(choices=styles, label="Selecciona el estilo de gráfico", value='whitegrid')
|
605 |
+
|
606 |
+
# Añadir color pickers para líneas y puntos
|
607 |
+
line_color_picker = gr.ColorPicker(label="Color de la línea", value='#0000FF')
|
608 |
+
point_color_picker = gr.ColorPicker(label="Color de los puntos", value='#000000')
|
609 |
+
|
610 |
+
# Añadir listas desplegables para tipo de línea y tipo de punto
|
611 |
+
line_style_options = ['-', '--', '-.', ':']
|
612 |
+
line_style_dropdown = gr.Dropdown(choices=line_style_options, label="Estilo de línea", value='-')
|
613 |
+
|
614 |
+
marker_style_options = ['o', 's', '^', 'v', 'D', 'x', '+', '*']
|
615 |
+
marker_style_dropdown = gr.Dropdown(choices=marker_style_options, label="Estilo de punto", value='o')
|
616 |
+
|
617 |
+
simulate_btn = gr.Button("Simular")
|
618 |
+
|
619 |
+
# Definir un componente gr.Gallery para las salidas
|
620 |
+
output_gallery = gr.Gallery(label="Resultados", columns=2, height='auto')
|
621 |
+
|
622 |
+
def process_and_plot(file, legend_position, params_position, model_type, mode, experiment_names,
|
623 |
+
lower_bounds, upper_bounds, style,
|
624 |
+
line_color, point_color, line_style, marker_style,
|
625 |
+
show_legend, show_params, use_differential):
|
626 |
+
# Dividir los nombres de experimentos y límites en listas
|
627 |
+
experiment_names_list = experiment_names.strip().split('\n') if experiment_names.strip() else []
|
628 |
+
lower_bounds_list = [tuple(map(float, lb.split(','))) for lb in
|
629 |
+
lower_bounds.strip().split('\n')] if lower_bounds.strip() else []
|
630 |
+
upper_bounds_list = [tuple(map(float, ub.split(','))) for ub in
|
631 |
+
upper_bounds.strip().split('\n')] if upper_bounds.strip() else []
|
632 |
+
|
633 |
+
# Procesar los datos y generar gráficos
|
634 |
+
figures = process_data(file, legend_position, params_position, model_type, experiment_names_list,
|
635 |
+
lower_bounds_list, upper_bounds_list, mode, style,
|
636 |
+
line_color, point_color, line_style, marker_style,
|
637 |
+
show_legend, show_params, use_differential)
|
638 |
+
|
639 |
+
# Convertir las figuras a imágenes y devolverlas como lista
|
640 |
+
image_list = []
|
641 |
+
for fig in figures:
|
642 |
+
buf = io.BytesIO()
|
643 |
+
fig.savefig(buf, format='png')
|
644 |
+
buf.seek(0)
|
645 |
+
image = Image.open(buf)
|
646 |
+
image_list.append(image)
|
647 |
+
|
648 |
+
return image_list
|
649 |
+
|
650 |
+
simulate_btn.click(
|
651 |
+
fn=process_and_plot,
|
652 |
+
inputs=[file_input,
|
653 |
+
legend_position,
|
654 |
+
params_position,
|
655 |
+
model_type,
|
656 |
+
mode,
|
657 |
+
experiment_names,
|
658 |
+
lower_bounds,
|
659 |
+
upper_bounds,
|
660 |
+
style_dropdown,
|
661 |
+
line_color_picker,
|
662 |
+
point_color_picker,
|
663 |
+
line_style_dropdown,
|
664 |
+
marker_style_dropdown,
|
665 |
+
show_legend,
|
666 |
+
show_params,
|
667 |
+
use_differential],
|
668 |
+
outputs=output_gallery
|
669 |
+
)
|
670 |
+
|
671 |
+
return demo
|
672 |
|
673 |
+
# Crear y lanzar la interfaz
|
674 |
+
demo = create_interface()
|
675 |
+
demo.launch(share=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|