File size: 32,703 Bytes
1105522 ccd76a9 1105522 ccd76a9 1105522 ccd76a9 1105522 |
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 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 |
# -*- coding: utf-8 -*-
"""PrediLectia - Gradio Final v2 with Multiple Y-Axes in Combined Plot.ipynb"""
# Instalación de librerías necesarias
#!pip install gradio seaborn scipy -q
import os
os.system('pip install gradio seaborn scipy scikit-learn openpyxl pydantic==1.10.0')
from pydantic import BaseModel, ConfigDict
class YourModel(BaseModel):
class Config:
arbitrary_types_allowed = True
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from scipy.integrate import odeint
from scipy.interpolate import interp1d
from scipy.optimize import curve_fit
from sklearn.metrics import mean_squared_error
import gradio as gr
import io
from PIL import Image
# Definición de la clase BioprocessModel
class BioprocessModel:
def __init__(self):
self.params = {}
self.r2 = {}
self.rmse = {}
self.datax = []
self.datas = []
self.datap = []
self.dataxp = []
self.datasp = []
self.datapp = []
self.datax_std = []
self.datas_std = []
self.datap_std = []
# Funciones modelo analíticas
@staticmethod
def logistic(time, xo, xm, um):
return (xo * np.exp(um * time)) / (1 - (xo / xm) * (1 - np.exp(um * time)))
@staticmethod
def substrate(time, so, p, q, xo, xm, um):
return so - (p * xo * ((np.exp(um * time)) / (1 - (xo / xm) * (1 - np.exp(um * time))) - 1)) - \
(q * (xm / um) * np.log(1 - (xo / xm) * (1 - np.exp(um * time))))
@staticmethod
def product(time, po, alpha, beta, xo, xm, um):
return po + (alpha * xo * ((np.exp(um * time) / (1 - (xo / xm) * (1 - np.exp(um * time)))) - 1)) + \
(beta * (xm / um) * np.log(1 - (xo / xm) * (1 - np.exp(um * time))))
# Funciones modelo diferenciales
@staticmethod
def logistic_diff(X, t, params):
xo, xm, um = params
dXdt = um * X * (1 - X / xm)
return dXdt
def substrate_diff(self, S, t, params, biomass_params, X_func):
so, p, q = params
xo, xm, um = biomass_params
X_t = X_func(t)
dSdt = -p * (um * X_t * (1 - X_t / xm)) - q * X_t
return dSdt
def product_diff(self, P, t, params, biomass_params, X_func):
po, alpha, beta = params
xo, xm, um = biomass_params
X_t = X_func(t)
dPdt = alpha * (um * X_t * (1 - X_t / xm)) + beta * X_t
return dPdt
# Métodos de procesamiento y ajuste de datos
def process_data(self, df):
# Obtener todas las columnas que contengan "Biomasa", "Sustrato", y "Producto"
biomass_cols = [col for col in df.columns if col[1] == 'Biomasa']
substrate_cols = [col for col in df.columns if col[1] == 'Sustrato']
product_cols = [col for col in df.columns if col[1] == 'Producto']
# Procesar los datos de tiempo
time_col = [col for col in df.columns if col[1] == 'Tiempo'][0]
time = df[time_col].values
# Procesar los datos de biomasa
data_biomass = [df[col].values for col in biomass_cols]
data_biomass = np.array(data_biomass) # shape (num_experiments, num_time_points)
self.datax.append(data_biomass)
self.dataxp.append(np.mean(data_biomass, axis=0))
self.datax_std.append(np.std(data_biomass, axis=0, ddof=1))
# Procesar los datos de sustrato
data_substrate = [df[col].values for col in substrate_cols]
data_substrate = np.array(data_substrate)
self.datas.append(data_substrate)
self.datasp.append(np.mean(data_substrate, axis=0))
self.datas_std.append(np.std(data_substrate, axis=0, ddof=1))
# Procesar los datos de producto
data_product = [df[col].values for col in product_cols]
data_product = np.array(data_product)
self.datap.append(data_product)
self.datapp.append(np.mean(data_product, axis=0))
self.datap_std.append(np.std(data_product, axis=0, ddof=1))
self.time = time
def fit_model(self, model_type='logistic'):
if model_type == 'logistic':
self.fit_biomass = self.fit_biomass_logistic
self.fit_substrate = self.fit_substrate_logistic
self.fit_product = self.fit_product_logistic
# Puedes agregar más modelos aquí si los necesitas.
def fit_biomass_logistic(self, time, biomass, bounds):
popt, _ = curve_fit(self.logistic, time, biomass, bounds=bounds, maxfev=10000)
self.params['biomass'] = {'xo': popt[0], 'xm': popt[1], 'um': popt[2]}
y_pred = self.logistic(time, *popt)
self.r2['biomass'] = 1 - (np.sum((biomass - y_pred) ** 2) / np.sum((biomass - np.mean(biomass)) ** 2))
self.rmse['biomass'] = np.sqrt(mean_squared_error(biomass, y_pred))
return y_pred
def fit_substrate_logistic(self, time, substrate, biomass_params, bounds):
popt, _ = curve_fit(lambda t, so, p, q: self.substrate(t, so, p, q, *biomass_params.values()),
time, substrate, bounds=bounds)
self.params['substrate'] = {'so': popt[0], 'p': popt[1], 'q': popt[2]}
y_pred = self.substrate(time, *popt, *biomass_params.values())
self.r2['substrate'] = 1 - (np.sum((substrate - y_pred) ** 2) / np.sum((substrate - np.mean(substrate)) ** 2))
self.rmse['substrate'] = np.sqrt(mean_squared_error(substrate, y_pred))
return y_pred
def fit_product_logistic(self, time, product, biomass_params, bounds):
popt, _ = curve_fit(lambda t, po, alpha, beta: self.product(t, po, alpha, beta, *biomass_params.values()),
time, product, bounds=bounds)
self.params['product'] = {'po': popt[0], 'alpha': popt[1], 'beta': popt[2]}
y_pred = self.product(time, *popt, *biomass_params.values())
self.r2['product'] = 1 - (np.sum((product - y_pred) ** 2) / np.sum((product - np.mean(product)) ** 2))
self.rmse['product'] = np.sqrt(mean_squared_error(product, y_pred))
return y_pred
# Métodos de visualización de resultados
def generate_fine_time_grid(self, time):
# Generar una malla temporal más fina para curvas suaves
time_fine = np.linspace(time.min(), time.max(), 500)
return time_fine
def solve_differential_equations(self, time, initial_conditions, params):
# Resolver la ecuación diferencial para biomasa
xo, xm, um = params['biomass'].values()
biomass_params = [xo, xm, um]
time_fine = self.generate_fine_time_grid(time)
# Resolver biomasa
X0 = xo
X = odeint(self.logistic_diff, X0, time_fine, args=(biomass_params,)).flatten()
# Crear función de interpolación para X(t)
X_func = interp1d(time_fine, X, kind='linear', fill_value="extrapolate")
# Resolver sustrato
so, p, q = params['substrate'].values()
substrate_params = [so, p, q]
S0 = so
S = odeint(self.substrate_diff, S0, time_fine, args=(substrate_params, biomass_params, X_func)).flatten()
# Resolver producto
po, alpha, beta = params['product'].values()
product_params = [po, alpha, beta]
P0 = po
P = odeint(self.product_diff, P0, time_fine, args=(product_params, biomass_params, X_func)).flatten()
return X, S, P, time_fine
def plot_results(self, time, biomass, substrate, product,
y_pred_biomass, y_pred_substrate, y_pred_product,
biomass_std=None, substrate_std=None, product_std=None,
experiment_name='', legend_position='best', params_position='upper right',
show_legend=True, show_params=True,
style='whitegrid',
line_color='#0000FF', point_color='#000000', line_style='-', marker_style='o',
use_differential=False):
sns.set_style(style) # Establecer el estilo seleccionado
if use_differential:
y_pred_biomass, y_pred_substrate, y_pred_product, time_to_plot = self.solve_differential_equations(
time, [biomass[0], substrate[0], product[0]], self.params)
else:
time_to_plot = time
fig, (ax1, ax2, ax3) = plt.subplots(3, 1, figsize=(10, 15))
fig.suptitle(f'{experiment_name}', fontsize=16)
plots = [
(ax1, biomass, y_pred_biomass, biomass_std, 'Biomasa', 'Modelo', self.params['biomass'],
self.r2['biomass'], self.rmse['biomass']),
(ax2, substrate, y_pred_substrate, substrate_std, 'Sustrato', 'Modelo', self.params['substrate'],
self.r2['substrate'], self.rmse['substrate']),
(ax3, product, y_pred_product, product_std, 'Producto', 'Modelo', self.params['product'],
self.r2['product'], self.rmse['product'])
]
for idx, (ax, data, y_pred, data_std, ylabel, model_name, params, r2, rmse) in enumerate(plots):
if data_std is not None:
ax.errorbar(time, data, yerr=data_std, fmt=marker_style, color=point_color,
label='Datos experimentales', capsize=5)
else:
ax.plot(time, data, marker=marker_style, linestyle='', color=point_color,
label='Datos experimentales')
if use_differential:
ax.plot(time_to_plot, y_pred, linestyle=line_style, color=line_color, label=model_name)
else:
ax.plot(time, y_pred, linestyle=line_style, color=line_color, label=model_name)
ax.set_xlabel('Tiempo')
ax.set_ylabel(ylabel)
if show_legend:
ax.legend(loc=legend_position)
ax.set_title(f'{ylabel}')
if show_params:
param_text = '\n'.join([f"{k} = {v:.4f}" for k, v in params.items()])
text = f"{param_text}\nR² = {r2:.4f}\nRMSE = {rmse:.4f}"
# Si la posición es 'outside right', ajustar la posición del texto
if params_position == 'outside right':
bbox_props = dict(boxstyle='round', facecolor='white', alpha=0.5)
ax.annotate(text, xy=(1.05, 0.5), xycoords='axes fraction',
verticalalignment='center', bbox=bbox_props)
else:
if params_position in ['upper right', 'lower right']:
text_x = 0.95
ha = 'right'
else:
text_x = 0.05
ha = 'left'
if params_position in ['upper right', 'upper left']:
text_y = 0.95
va = 'top'
else:
text_y = 0.05
va = 'bottom'
ax.text(text_x, text_y, text, transform=ax.transAxes,
verticalalignment=va, horizontalalignment=ha,
bbox={'boxstyle': 'round', 'facecolor': 'white', 'alpha': 0.5})
plt.tight_layout()
return fig
def plot_combined_results(self, time, biomass, substrate, product,
y_pred_biomass, y_pred_substrate, y_pred_product,
biomass_std=None, substrate_std=None, product_std=None,
experiment_name='', legend_position='best', params_position='upper right',
show_legend=True, show_params=True,
style='whitegrid',
line_color='#0000FF', point_color='#000000', line_style='-', marker_style='o',
use_differential=False):
sns.set_style(style) # Establecer el estilo seleccionado
if use_differential:
y_pred_biomass, y_pred_substrate, y_pred_product, time_to_plot = self.solve_differential_equations(
time, [biomass[0], substrate[0], product[0]], self.params)
else:
time_to_plot = time
fig, ax1 = plt.subplots(figsize=(10, 7))
fig.suptitle(f'{experiment_name}', fontsize=16)
# Colores específicos para cada variable
colors = {'Biomasa': 'blue', 'Sustrato': 'green', 'Producto': 'red'}
# Plot Biomasa en ax1
ax1.set_xlabel('Tiempo')
ax1.set_ylabel('Biomasa', color=colors['Biomasa'])
if biomass_std is not None:
ax1.errorbar(time, biomass, yerr=biomass_std, fmt=marker_style, color=colors['Biomasa'],
label='Biomasa (Datos)', capsize=5)
else:
ax1.plot(time, biomass, marker=marker_style, linestyle='', color=colors['Biomasa'],
label='Biomasa (Datos)')
if use_differential:
ax1.plot(time_to_plot, y_pred_biomass, linestyle=line_style, color=colors['Biomasa'],
label='Biomasa (Modelo)')
else:
ax1.plot(time, y_pred_biomass, linestyle=line_style, color=colors['Biomasa'],
label='Biomasa (Modelo)')
ax1.tick_params(axis='y', labelcolor=colors['Biomasa'])
# Crear segundo eje y para Sustrato
ax2 = ax1.twinx()
ax2.set_ylabel('Sustrato', color=colors['Sustrato'])
if substrate_std is not None:
ax2.errorbar(time, substrate, yerr=substrate_std, fmt=marker_style, color=colors['Sustrato'],
label='Sustrato (Datos)', capsize=5)
else:
ax2.plot(time, substrate, marker=marker_style, linestyle='', color=colors['Sustrato'],
label='Sustrato (Datos)')
if use_differential:
ax2.plot(time_to_plot, y_pred_substrate, linestyle=line_style, color=colors['Sustrato'],
label='Sustrato (Modelo)')
else:
ax2.plot(time, y_pred_substrate, linestyle=line_style, color=colors['Sustrato'],
label='Sustrato (Modelo)')
ax2.tick_params(axis='y', labelcolor=colors['Sustrato'])
# Crear tercer eje y para Producto
ax3 = ax1.twinx()
# Desplazar el tercer eje para evitar superposición
ax3.spines["right"].set_position(("axes", 1.1))
ax3.set_frame_on(True)
ax3.patch.set_visible(False)
for sp in ax3.spines.values():
sp.set_visible(True)
ax3.set_ylabel('Producto', color=colors['Producto'])
if product_std is not None:
ax3.errorbar(time, product, yerr=product_std, fmt=marker_style, color=colors['Producto'],
label='Producto (Datos)', capsize=5)
else:
ax3.plot(time, product, marker=marker_style, linestyle='', color=colors['Producto'],
label='Producto (Datos)')
if use_differential:
ax3.plot(time_to_plot, y_pred_product, linestyle=line_style, color=colors['Producto'],
label='Producto (Modelo)')
else:
ax3.plot(time, y_pred_product, linestyle=line_style, color=colors['Producto'],
label='Producto (Modelo)')
ax3.tick_params(axis='y', labelcolor=colors['Producto'])
# Manejo de leyendas
lines_labels = [ax.get_legend_handles_labels() for ax in [ax1, ax2, ax3]]
lines, labels = [sum(lol, []) for lol in zip(*lines_labels)]
if show_legend:
ax1.legend(lines, labels, loc=legend_position)
# Mostrar parámetros y estadísticas en el gráfico
if show_params:
param_text_biomass = '\n'.join([f"{k} = {v:.4f}" for k, v in self.params['biomass'].items()])
text_biomass = f"Biomasa:\n{param_text_biomass}\nR² = {self.r2['biomass']:.4f}\nRMSE = {self.rmse['biomass']:.4f}"
param_text_substrate = '\n'.join([f"{k} = {v:.4f}" for k, v in self.params['substrate'].items()])
text_substrate = f"Sustrato:\n{param_text_substrate}\nR² = {self.r2['substrate']:.4f}\nRMSE = {self.rmse['substrate']:.4f}"
param_text_product = '\n'.join([f"{k} = {v:.4f}" for k, v in self.params['product'].items()])
text_product = f"Producto:\n{param_text_product}\nR² = {self.r2['product']:.4f}\nRMSE = {self.rmse['product']:.4f}"
total_text = f"{text_biomass}\n\n{text_substrate}\n\n{text_product}"
if params_position == 'outside right':
bbox_props = dict(boxstyle='round', facecolor='white', alpha=0.5)
ax3.annotate(total_text, xy=(1.2, 0.5), xycoords='axes fraction',
verticalalignment='center', bbox=bbox_props)
else:
if params_position in ['upper right', 'lower right']:
text_x = 0.95
ha = 'right'
else:
text_x = 0.05
ha = 'left'
if params_position in ['upper right', 'upper left']:
text_y = 0.95
va = 'top'
else:
text_y = 0.05
va = 'bottom'
ax1.text(text_x, text_y, total_text, transform=ax1.transAxes,
verticalalignment=va, horizontalalignment=ha,
bbox={'boxstyle': 'round', 'facecolor': 'white', 'alpha': 0.5})
plt.tight_layout()
return fig
# Función de procesamiento de datos
def process_data(file, legend_position, params_position, model_type, experiment_names, lower_bounds, upper_bounds,
mode='independent', style='whitegrid', line_color='#0000FF', point_color='#000000',
line_style='-', marker_style='o', show_legend=True, show_params=True, use_differential=False):
# Leer todas las hojas del archivo Excel
xls = pd.ExcelFile(file.name)
sheet_names = xls.sheet_names
model = BioprocessModel()
model.fit_model(model_type)
figures = []
# Si no se proporcionan suficientes límites, usar valores predeterminados
default_lower_bounds = (0, 0, 0)
default_upper_bounds = (np.inf, np.inf, np.inf)
experiment_counter = 0 # Contador global de experimentos
for sheet_name in sheet_names:
df = pd.read_excel(file.name, sheet_name=sheet_name, header=[0, 1])
# Procesar datos
model.process_data(df)
time = model.time
if mode == 'independent':
# Modo independiente: iterar sobre cada experimento
num_experiments = len(df.columns.levels[0])
for idx in range(num_experiments):
col = df.columns.levels[0][idx]
time = df[(col, 'Tiempo')].dropna().values
biomass = df[(col, 'Biomasa')].dropna().values
substrate = df[(col, 'Sustrato')].dropna().values
product = df[(col, 'Producto')].dropna().values
# Si hay replicados en el experimento, calcular la desviación estándar
biomass_std = None
substrate_std = None
product_std = None
if biomass.ndim > 1:
biomass_std = np.std(biomass, axis=0, ddof=1)
biomass = np.mean(biomass, axis=0)
if substrate.ndim > 1:
substrate_std = np.std(substrate, axis=0, ddof=1)
substrate = np.mean(substrate, axis=0)
if product.ndim > 1:
product_std = np.std(product, axis=0, ddof=1)
product = np.mean(product, axis=0)
# Obtener límites o usar valores predeterminados
lower_bound = lower_bounds[experiment_counter] if experiment_counter < len(lower_bounds) else default_lower_bounds
upper_bound = upper_bounds[experiment_counter] if experiment_counter < len(upper_bounds) else default_upper_bounds
bounds = (lower_bound, upper_bound)
# Ajustar el modelo
y_pred_biomass = model.fit_biomass(time, biomass, bounds)
y_pred_substrate = model.fit_substrate(time, substrate, model.params['biomass'], bounds)
y_pred_product = model.fit_product(time, product, model.params['biomass'], bounds)
# Usar el nombre del experimento proporcionado o un nombre por defecto
experiment_name = experiment_names[experiment_counter] if experiment_counter < len(experiment_names) else f"Tratamiento {experiment_counter + 1}"
if mode == 'combinado':
fig = model.plot_combined_results(time, biomass, substrate, product,
y_pred_biomass, y_pred_substrate, y_pred_product,
biomass_std, substrate_std, product_std,
experiment_name, legend_position, params_position,
show_legend, show_params,
style,
line_color, point_color, line_style, marker_style,
use_differential)
else:
fig = model.plot_results(time, biomass, substrate, product,
y_pred_biomass, y_pred_substrate, y_pred_product,
biomass_std, substrate_std, product_std,
experiment_name, legend_position, params_position,
show_legend, show_params,
style,
line_color, point_color, line_style, marker_style,
use_differential)
figures.append(fig)
experiment_counter += 1
elif mode == 'average':
# Modo promedio: usar dataxp, datasp y datapp
time = df[(df.columns.levels[0][0], 'Tiempo')].dropna().values
biomass = model.dataxp[-1]
substrate = model.datasp[-1]
product = model.datapp[-1]
# Obtener las desviaciones estándar
biomass_std = model.datax_std[-1]
substrate_std = model.datas_std[-1]
product_std = model.datap_std[-1]
# Obtener límites o usar valores predeterminados
lower_bound = lower_bounds[experiment_counter] if experiment_counter < len(lower_bounds) else default_lower_bounds
upper_bound = upper_bounds[experiment_counter] if experiment_counter < len(upper_bounds) else default_upper_bounds
bounds = (lower_bound, upper_bound)
# Ajustar el modelo
y_pred_biomass = model.fit_biomass(time, biomass, bounds)
y_pred_substrate = model.fit_substrate(time, substrate, model.params['biomass'], bounds)
y_pred_product = model.fit_product(time, product, model.params['biomass'], bounds)
# Usar el nombre del experimento proporcionado o un nombre por defecto
experiment_name = experiment_names[experiment_counter] if experiment_counter < len(experiment_names) else f"Tratamiento {experiment_counter + 1}"
if mode == 'combinado':
fig = model.plot_combined_results(time, biomass, substrate, product,
y_pred_biomass, y_pred_substrate, y_pred_product,
biomass_std, substrate_std, product_std,
experiment_name, legend_position, params_position,
show_legend, show_params,
style,
line_color, point_color, line_style, marker_style,
use_differential)
else:
fig = model.plot_results(time, biomass, substrate, product,
y_pred_biomass, y_pred_substrate, y_pred_product,
biomass_std, substrate_std, product_std,
experiment_name, legend_position, params_position,
show_legend, show_params,
style,
line_color, point_color, line_style, marker_style,
use_differential)
figures.append(fig)
experiment_counter += 1
elif mode == 'combinado':
# Modo combinado: combinar las gráficas en una sola
time = df[(df.columns.levels[0][0], 'Tiempo')].dropna().values
biomass = model.dataxp[-1]
substrate = model.datasp[-1]
product = model.datapp[-1]
# Obtener las desviaciones estándar
biomass_std = model.datax_std[-1]
substrate_std = model.datas_std[-1]
product_std = model.datap_std[-1]
# Obtener límites o usar valores predeterminados
lower_bound = lower_bounds[experiment_counter] if experiment_counter < len(lower_bounds) else default_lower_bounds
upper_bound = upper_bounds[experiment_counter] if experiment_counter < len(upper_bounds) else default_upper_bounds
bounds = (lower_bound, upper_bound)
# Ajustar el modelo
y_pred_biomass = model.fit_biomass(time, biomass, bounds)
y_pred_substrate = model.fit_substrate(time, substrate, model.params['biomass'], bounds)
y_pred_product = model.fit_product(time, product, model.params['biomass'], bounds)
# Usar el nombre del experimento proporcionado o un nombre por defecto
experiment_name = experiment_names[experiment_counter] if experiment_counter < len(experiment_names) else f"Tratamiento {experiment_counter + 1}"
fig = model.plot_combined_results(time, biomass, substrate, product,
y_pred_biomass, y_pred_substrate, y_pred_product,
biomass_std, substrate_std, product_std,
experiment_name, legend_position, params_position,
show_legend, show_params,
style,
line_color, point_color, line_style, marker_style,
use_differential)
figures.append(fig)
experiment_counter += 1
return figures
def create_interface():
with gr.Blocks() as demo:
gr.Markdown("# Modelos de Bioproceso: Logístico y Luedeking-Piret")
gr.Markdown(
"Sube un archivo Excel con múltiples pestañas. Cada pestaña debe contener columnas 'Tiempo', 'Biomasa', 'Sustrato' y 'Producto' para cada experimento.")
file_input = gr.File(label="Subir archivo Excel")
with gr.Row():
with gr.Column():
legend_position = gr.Radio(
choices=["upper left", "upper right", "lower left", "lower right", "best"],
label="Posición de la leyenda",
value="best"
)
show_legend = gr.Checkbox(label="Mostrar Leyenda", value=True)
with gr.Column():
params_positions = ["upper left", "upper right", "lower left", "lower right", "outside right"]
params_position = gr.Radio(
choices=params_positions,
label="Posición de los parámetros",
value="upper right"
)
show_params = gr.Checkbox(label="Mostrar Parámetros", value=True)
model_type = gr.Radio(["logistic"], label="Tipo de Modelo", value="logistic")
mode = gr.Radio(["independent", "average", "combinado"], label="Modo de Análisis", value="independent")
use_differential = gr.Checkbox(label="Usar ecuaciones diferenciales para graficar", value=False)
experiment_names = gr.Textbox(
label="Nombres de los experimentos (uno por línea)",
placeholder="Experimento 1\nExperimento 2\n...",
lines=5
)
with gr.Row():
with gr.Column():
lower_bounds = gr.Textbox(
label="Lower Bounds (uno por línea, formato: xo,xm,um)",
placeholder="0,0,0\n0,0,0\n...",
lines=5
)
with gr.Column():
upper_bounds = gr.Textbox(
label="Upper Bounds (uno por línea, formato: xo,xm,um)",
placeholder="inf,inf,inf\ninf,inf,inf\n...",
lines=5
)
# Añadir un desplegable para seleccionar el estilo del gráfico
styles = ['white', 'dark', 'whitegrid', 'darkgrid', 'ticks']
style_dropdown = gr.Dropdown(choices=styles, label="Selecciona el estilo de gráfico", value='whitegrid')
# Añadir color pickers para líneas y puntos
line_color_picker = gr.ColorPicker(label="Color de la línea", value='#0000FF')
point_color_picker = gr.ColorPicker(label="Color de los puntos", value='#000000')
# Añadir listas desplegables para tipo de línea y tipo de punto
line_style_options = ['-', '--', '-.', ':']
line_style_dropdown = gr.Dropdown(choices=line_style_options, label="Estilo de línea", value='-')
marker_style_options = ['o', 's', '^', 'v', 'D', 'x', '+', '*']
marker_style_dropdown = gr.Dropdown(choices=marker_style_options, label="Estilo de punto", value='o')
simulate_btn = gr.Button("Simular")
# Definir un componente gr.Gallery para las salidas
output_gallery = gr.Gallery(label="Resultados", columns=2, height='auto')
def process_and_plot(file, legend_position, params_position, model_type, mode, experiment_names,
lower_bounds, upper_bounds, style,
line_color, point_color, line_style, marker_style,
show_legend, show_params, use_differential):
# Dividir los nombres de experimentos y límites en listas
experiment_names_list = experiment_names.strip().split('\n') if experiment_names.strip() else []
lower_bounds_list = [tuple(map(float, lb.split(','))) for lb in
lower_bounds.strip().split('\n')] if lower_bounds.strip() else []
upper_bounds_list = [tuple(map(float, ub.split(','))) for ub in
upper_bounds.strip().split('\n')] if upper_bounds.strip() else []
# Procesar los datos y generar gráficos
figures = process_data(file, legend_position, params_position, model_type, experiment_names_list,
lower_bounds_list, upper_bounds_list, mode, style,
line_color, point_color, line_style, marker_style,
show_legend, show_params, use_differential)
# Convertir las figuras a imágenes y devolverlas como lista
image_list = []
for fig in figures:
buf = io.BytesIO()
fig.savefig(buf, format='png')
buf.seek(0)
image = Image.open(buf)
image_list.append(image)
return image_list
simulate_btn.click(
fn=process_and_plot,
inputs=[file_input,
legend_position,
params_position,
model_type,
mode,
experiment_names,
lower_bounds,
upper_bounds,
style_dropdown,
line_color_picker,
point_color_picker,
line_style_dropdown,
marker_style_dropdown,
show_legend,
show_params,
use_differential],
outputs=output_gallery
)
return demo
# Crear y lanzar la interfaz
demo = create_interface()
demo.launch(share=True)
|