|
|
|
"""PrediLectia - Gradio Final v2 with Multiple Y-Axes in Combined Plot.ipynb""" |
|
|
|
|
|
|
|
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 |
|
|
|
|
|
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 = [] |
|
|
|
|
|
@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)))) |
|
|
|
|
|
@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 |
|
|
|
|
|
def process_data(self, df): |
|
|
|
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'] |
|
|
|
|
|
time_col = [col for col in df.columns if col[1] == 'Tiempo'][0] |
|
time = df[time_col].values |
|
|
|
|
|
data_biomass = [df[col].values for col in biomass_cols] |
|
data_biomass = np.array(data_biomass) |
|
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)) |
|
|
|
|
|
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)) |
|
|
|
|
|
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 |
|
|
|
|
|
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 |
|
|
|
|
|
def generate_fine_time_grid(self, time): |
|
|
|
time_fine = np.linspace(time.min(), time.max(), 500) |
|
return time_fine |
|
|
|
def solve_differential_equations(self, time, initial_conditions, params): |
|
|
|
xo, xm, um = params['biomass'].values() |
|
biomass_params = [xo, xm, um] |
|
time_fine = self.generate_fine_time_grid(time) |
|
|
|
|
|
X0 = xo |
|
X = odeint(self.logistic_diff, X0, time_fine, args=(biomass_params,)).flatten() |
|
|
|
|
|
X_func = interp1d(time_fine, X, kind='linear', fill_value="extrapolate") |
|
|
|
|
|
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() |
|
|
|
|
|
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) |
|
|
|
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}" |
|
|
|
|
|
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) |
|
|
|
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) |
|
|
|
|
|
colors = {'Biomasa': 'blue', 'Sustrato': 'green', 'Producto': 'red'} |
|
|
|
|
|
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']) |
|
|
|
|
|
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']) |
|
|
|
|
|
ax3 = ax1.twinx() |
|
|
|
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']) |
|
|
|
|
|
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) |
|
|
|
|
|
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 |
|
|
|
|
|
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): |
|
|
|
xls = pd.ExcelFile(file.name) |
|
sheet_names = xls.sheet_names |
|
|
|
model = BioprocessModel() |
|
model.fit_model(model_type) |
|
figures = [] |
|
|
|
|
|
default_lower_bounds = (0, 0, 0) |
|
default_upper_bounds = (np.inf, np.inf, np.inf) |
|
|
|
experiment_counter = 0 |
|
|
|
for sheet_name in sheet_names: |
|
df = pd.read_excel(file.name, sheet_name=sheet_name, header=[0, 1]) |
|
|
|
|
|
model.process_data(df) |
|
time = model.time |
|
|
|
if mode == 'independent': |
|
|
|
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 |
|
|
|
|
|
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) |
|
|
|
|
|
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) |
|
|
|
|
|
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) |
|
|
|
|
|
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': |
|
|
|
time = df[(df.columns.levels[0][0], 'Tiempo')].dropna().values |
|
biomass = model.dataxp[-1] |
|
substrate = model.datasp[-1] |
|
product = model.datapp[-1] |
|
|
|
|
|
biomass_std = model.datax_std[-1] |
|
substrate_std = model.datas_std[-1] |
|
product_std = model.datap_std[-1] |
|
|
|
|
|
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) |
|
|
|
|
|
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) |
|
|
|
|
|
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': |
|
|
|
time = df[(df.columns.levels[0][0], 'Tiempo')].dropna().values |
|
biomass = model.dataxp[-1] |
|
substrate = model.datasp[-1] |
|
product = model.datapp[-1] |
|
|
|
|
|
biomass_std = model.datax_std[-1] |
|
substrate_std = model.datas_std[-1] |
|
product_std = model.datap_std[-1] |
|
|
|
|
|
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) |
|
|
|
|
|
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) |
|
|
|
|
|
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 |
|
) |
|
|
|
|
|
styles = ['white', 'dark', 'whitegrid', 'darkgrid', 'ticks'] |
|
style_dropdown = gr.Dropdown(choices=styles, label="Selecciona el estilo de gráfico", value='whitegrid') |
|
|
|
|
|
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') |
|
|
|
|
|
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") |
|
|
|
|
|
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): |
|
|
|
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 [] |
|
|
|
|
|
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) |
|
|
|
|
|
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 |
|
|
|
|
|
demo = create_interface() |
|
demo.launch(share=True) |
|
|