Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -14,7 +14,6 @@ from zipfile import ZipFile
|
|
14 |
|
15 |
class RSM_BoxBehnken:
|
16 |
def __init__(self, data, x1_name, x2_name, x3_name, y_name, x1_levels, x2_levels, x3_levels):
|
17 |
-
# ... (El código de la clase RSM_BoxBehnken se mantiene igual, solo se modifican las funciones que generan dataframes o strings)
|
18 |
self.data = data.copy()
|
19 |
self.model = None
|
20 |
self.model_simplified = None
|
@@ -177,14 +176,10 @@ class RSM_BoxBehnken:
|
|
177 |
return fig
|
178 |
|
179 |
def generate_all_plots(self):
|
180 |
-
"""
|
181 |
-
Genera todas las gráficas de RSM, variando la variable fija y sus niveles usando el modelo simplificado.
|
182 |
-
"""
|
183 |
if self.model_simplified is None:
|
184 |
print("Error: Ajusta el modelo simplificado primero.")
|
185 |
return
|
186 |
|
187 |
-
# Niveles naturales para graficar
|
188 |
levels_to_plot_natural = {
|
189 |
self.x1_name: self.x1_levels,
|
190 |
self.x2_name: self.x2_levels,
|
@@ -193,7 +188,6 @@ class RSM_BoxBehnken:
|
|
193 |
|
194 |
figs = []
|
195 |
|
196 |
-
# Generar y mostrar gráficos individuales
|
197 |
for fixed_variable in [self.x1_name, self.x2_name, self.x3_name]:
|
198 |
for level in levels_to_plot_natural[fixed_variable]:
|
199 |
fig = self.plot_rsm_individual(fixed_variable, level)
|
@@ -268,7 +262,6 @@ class RSM_BoxBehnken:
|
|
268 |
self.data['Predicho'] = self.model_simplified.predict(self.data)
|
269 |
self.data['Residual'] = self.data[self.y_name] - self.data['Predicho']
|
270 |
|
271 |
-
# Redondear a 3 decimales en la tabla de predicciones
|
272 |
prediction_table = self.data[[self.y_name, 'Predicho', 'Residual']].copy()
|
273 |
prediction_table[self.y_name] = prediction_table[self.y_name].round(3)
|
274 |
prediction_table['Predicho'] = prediction_table['Predicho'].round(3)
|
@@ -403,7 +396,7 @@ def fit_and_optimize_model():
|
|
403 |
prediction_table = rsm.generate_prediction_table()
|
404 |
contribution_table = rsm.calculate_contribution_percentage()
|
405 |
anova_table = rsm.calculate_detailed_anova()
|
406 |
-
|
407 |
equation_formatted = equation.replace(" + ", "<br>+ ").replace(" ** ", "^").replace("*", " × ")
|
408 |
equation_formatted = f"### Ecuación del Modelo Simplificado:<br>{equation_formatted}"
|
409 |
|
@@ -414,19 +407,16 @@ def generate_rsm_plot(fixed_variable, fixed_level):
|
|
414 |
if 'rsm' not in globals():
|
415 |
return None, "Error: Carga los datos primero."
|
416 |
|
417 |
-
#
|
418 |
all_figs = rsm.generate_all_plots()
|
419 |
|
420 |
-
#
|
421 |
-
|
422 |
-
for fig in all_figs:
|
423 |
-
# Convertir la figura a una imagen en formato PNG
|
424 |
-
img_bytes = fig.to_image(format="png")
|
425 |
-
plot_outputs.append(img_bytes)
|
426 |
|
427 |
-
#
|
428 |
-
return
|
429 |
|
|
|
430 |
def download_excel():
|
431 |
if 'rsm' not in globals():
|
432 |
return None, "Error: Carga los datos y ajusta el modelo primero."
|
@@ -435,42 +425,31 @@ def download_excel():
|
|
435 |
with pd.ExcelWriter(output, engine='xlsxwriter') as writer:
|
436 |
rsm.data.to_excel(writer, sheet_name='Datos', index=False)
|
437 |
rsm.generate_prediction_table().to_excel(writer, sheet_name='Predicciones', index=False)
|
438 |
-
rsm.optimize().to_excel(writer, sheet_name='
|
439 |
-
rsm.calculate_contribution_percentage().to_excel(writer, sheet_name='
|
440 |
rsm.calculate_detailed_anova().to_excel(writer, sheet_name='ANOVA', index=False)
|
441 |
|
442 |
output.seek(0)
|
443 |
-
|
|
|
|
|
444 |
|
|
|
445 |
def download_images():
|
446 |
if 'rsm' not in globals():
|
447 |
return None, "Error: Carga los datos y ajusta el modelo primero."
|
448 |
|
449 |
-
|
450 |
-
|
451 |
-
|
|
|
|
|
|
|
|
|
|
|
452 |
|
453 |
-
|
454 |
-
|
455 |
-
for i, fig in enumerate(all_figs):
|
456 |
-
img_path = os.path.join(temp_dir, f"plot_{i}.png")
|
457 |
-
fig.write_image(img_path)
|
458 |
-
|
459 |
-
# Comprimir las imágenes en un archivo ZIP
|
460 |
-
zip_buffer = io.BytesIO()
|
461 |
-
with ZipFile(zip_buffer, "w") as zip_file:
|
462 |
-
for filename in os.listdir(temp_dir):
|
463 |
-
file_path = os.path.join(temp_dir, filename)
|
464 |
-
zip_file.write(file_path, arcname=filename)
|
465 |
-
|
466 |
-
# Eliminar el directorio temporal
|
467 |
-
for filename in os.listdir(temp_dir):
|
468 |
-
file_path = os.path.join(temp_dir, filename)
|
469 |
-
os.remove(file_path)
|
470 |
-
os.rmdir(temp_dir)
|
471 |
-
|
472 |
-
zip_buffer.seek(0)
|
473 |
-
return gr.File.update(value=zip_buffer, visible=True, filename="graficos_rsm.zip")
|
474 |
|
475 |
# --- Crear la interfaz de Gradio ---
|
476 |
|
@@ -513,8 +492,6 @@ with gr.Blocks() as demo:
|
|
513 |
with gr.Row(visible=False) as analysis_row:
|
514 |
with gr.Column():
|
515 |
fit_button = gr.Button("Ajustar Modelo y Optimizar")
|
516 |
-
download_excel_button = gr.Button("Descargar Tablas en Excel")
|
517 |
-
download_images_button = gr.Button("Descargar Gráficos en ZIP")
|
518 |
gr.Markdown("**Modelo Completo**")
|
519 |
model_completo_output = gr.HTML()
|
520 |
pareto_completo_output = gr.Plot()
|
@@ -526,12 +503,22 @@ with gr.Blocks() as demo:
|
|
526 |
prediction_table_output = gr.Dataframe(label="Tabla de Predicciones")
|
527 |
contribution_table_output = gr.Dataframe(label="Tabla de % de Contribución")
|
528 |
anova_table_output = gr.Dataframe(label="Tabla ANOVA Detallada")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
529 |
with gr.Column():
|
530 |
gr.Markdown("## Generar Gráficos de Superficie de Respuesta")
|
531 |
fixed_variable_input = gr.Dropdown(label="Variable Fija", choices=["Glucosa", "Extracto_de_Levadura", "Triptofano"], value="Glucosa")
|
532 |
fixed_level_input = gr.Slider(label="Nivel de Variable Fija", minimum=0, maximum=1, step=0.01, value=0.5)
|
533 |
plot_button = gr.Button("Generar Gráfico")
|
534 |
-
|
|
|
|
|
535 |
|
536 |
load_button.click(
|
537 |
load_data,
|
@@ -541,10 +528,11 @@ with gr.Blocks() as demo:
|
|
541 |
|
542 |
fit_button.click(fit_and_optimize_model, outputs=[model_completo_output, pareto_completo_output, model_simplificado_output, pareto_simplificado_output, equation_output, optimization_table_output, prediction_table_output, contribution_table_output, anova_table_output])
|
543 |
|
544 |
-
plot_button.click(generate_rsm_plot, inputs=[fixed_variable_input, fixed_level_input], outputs=[
|
545 |
|
546 |
-
|
547 |
-
|
|
|
548 |
|
549 |
# Ejemplo de uso
|
550 |
gr.Markdown("## Ejemplo de uso")
|
@@ -554,7 +542,7 @@ with gr.Blocks() as demo:
|
|
554 |
gr.Markdown("4. Haz clic en 'Ajustar Modelo y Optimizar' para ajustar el modelo y encontrar los niveles óptimos de los factores.")
|
555 |
gr.Markdown("5. Selecciona una variable fija y su nivel en los controles deslizantes.")
|
556 |
gr.Markdown("6. Haz clic en 'Generar Gráfico' para generar un gráfico de superficie de respuesta.")
|
557 |
-
gr.Markdown("7. Haz clic en 'Descargar Tablas en Excel' para obtener un archivo
|
558 |
-
gr.Markdown("8. Haz clic en 'Descargar Gráficos en ZIP' para obtener un archivo
|
559 |
|
560 |
demo.launch()
|
|
|
14 |
|
15 |
class RSM_BoxBehnken:
|
16 |
def __init__(self, data, x1_name, x2_name, x3_name, y_name, x1_levels, x2_levels, x3_levels):
|
|
|
17 |
self.data = data.copy()
|
18 |
self.model = None
|
19 |
self.model_simplified = None
|
|
|
176 |
return fig
|
177 |
|
178 |
def generate_all_plots(self):
|
|
|
|
|
|
|
179 |
if self.model_simplified is None:
|
180 |
print("Error: Ajusta el modelo simplificado primero.")
|
181 |
return
|
182 |
|
|
|
183 |
levels_to_plot_natural = {
|
184 |
self.x1_name: self.x1_levels,
|
185 |
self.x2_name: self.x2_levels,
|
|
|
188 |
|
189 |
figs = []
|
190 |
|
|
|
191 |
for fixed_variable in [self.x1_name, self.x2_name, self.x3_name]:
|
192 |
for level in levels_to_plot_natural[fixed_variable]:
|
193 |
fig = self.plot_rsm_individual(fixed_variable, level)
|
|
|
262 |
self.data['Predicho'] = self.model_simplified.predict(self.data)
|
263 |
self.data['Residual'] = self.data[self.y_name] - self.data['Predicho']
|
264 |
|
|
|
265 |
prediction_table = self.data[[self.y_name, 'Predicho', 'Residual']].copy()
|
266 |
prediction_table[self.y_name] = prediction_table[self.y_name].round(3)
|
267 |
prediction_table['Predicho'] = prediction_table['Predicho'].round(3)
|
|
|
396 |
prediction_table = rsm.generate_prediction_table()
|
397 |
contribution_table = rsm.calculate_contribution_percentage()
|
398 |
anova_table = rsm.calculate_detailed_anova()
|
399 |
+
|
400 |
equation_formatted = equation.replace(" + ", "<br>+ ").replace(" ** ", "^").replace("*", " × ")
|
401 |
equation_formatted = f"### Ecuación del Modelo Simplificado:<br>{equation_formatted}"
|
402 |
|
|
|
407 |
if 'rsm' not in globals():
|
408 |
return None, "Error: Carga los datos primero."
|
409 |
|
410 |
+
# Obtener todas las gráficas
|
411 |
all_figs = rsm.generate_all_plots()
|
412 |
|
413 |
+
# Convertir la figura seleccionada a bytes
|
414 |
+
img_bytes = all_figs[0].to_image(format="png")
|
|
|
|
|
|
|
|
|
415 |
|
416 |
+
# Devolver la lista de figuras y la imagen en bytes
|
417 |
+
return all_figs, img_bytes
|
418 |
|
419 |
+
# Función para descargar el Excel con todas las tablas
|
420 |
def download_excel():
|
421 |
if 'rsm' not in globals():
|
422 |
return None, "Error: Carga los datos y ajusta el modelo primero."
|
|
|
425 |
with pd.ExcelWriter(output, engine='xlsxwriter') as writer:
|
426 |
rsm.data.to_excel(writer, sheet_name='Datos', index=False)
|
427 |
rsm.generate_prediction_table().to_excel(writer, sheet_name='Predicciones', index=False)
|
428 |
+
rsm.optimize().to_excel(writer, sheet_name='Optimización', index=False)
|
429 |
+
rsm.calculate_contribution_percentage().to_excel(writer, sheet_name='Contribución', index=False)
|
430 |
rsm.calculate_detailed_anova().to_excel(writer, sheet_name='ANOVA', index=False)
|
431 |
|
432 |
output.seek(0)
|
433 |
+
|
434 |
+
# Modificar para usar gr.File
|
435 |
+
return gr.File(value=output, visible=True, filename="resultados_rsm.xlsx")
|
436 |
|
437 |
+
# Función para descargar las imágenes
|
438 |
def download_images():
|
439 |
if 'rsm' not in globals():
|
440 |
return None, "Error: Carga los datos y ajusta el modelo primero."
|
441 |
|
442 |
+
zip_output = io.BytesIO()
|
443 |
+
with ZipFile(zip_output, 'w') as zipf:
|
444 |
+
for fixed_variable in [rsm.x1_name, rsm.x2_name, rsm.x3_name]:
|
445 |
+
for level in rsm.get_levels(fixed_variable):
|
446 |
+
fig = rsm.plot_rsm_individual(fixed_variable, level)
|
447 |
+
img_bytes = fig.to_image(format="png")
|
448 |
+
img_path = f"{fixed_variable}_{level}.png"
|
449 |
+
zipf.writestr(img_path, img_bytes)
|
450 |
|
451 |
+
zip_output.seek(0)
|
452 |
+
return gr.File(value=zip_output, visible=True, filename="graficos_rsm.zip")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
453 |
|
454 |
# --- Crear la interfaz de Gradio ---
|
455 |
|
|
|
492 |
with gr.Row(visible=False) as analysis_row:
|
493 |
with gr.Column():
|
494 |
fit_button = gr.Button("Ajustar Modelo y Optimizar")
|
|
|
|
|
495 |
gr.Markdown("**Modelo Completo**")
|
496 |
model_completo_output = gr.HTML()
|
497 |
pareto_completo_output = gr.Plot()
|
|
|
503 |
prediction_table_output = gr.Dataframe(label="Tabla de Predicciones")
|
504 |
contribution_table_output = gr.Dataframe(label="Tabla de % de Contribución")
|
505 |
anova_table_output = gr.Dataframe(label="Tabla ANOVA Detallada")
|
506 |
+
|
507 |
+
# Botones de descarga
|
508 |
+
with gr.Row():
|
509 |
+
download_excel_button = gr.Button("Descargar Tablas en Excel")
|
510 |
+
download_images_button = gr.Button("Descargar Gráficos en ZIP")
|
511 |
+
excel_file_output = gr.File(label="Descargar Excel")
|
512 |
+
zip_file_output = gr.File(label="Descargar ZIP")
|
513 |
+
|
514 |
with gr.Column():
|
515 |
gr.Markdown("## Generar Gráficos de Superficie de Respuesta")
|
516 |
fixed_variable_input = gr.Dropdown(label="Variable Fija", choices=["Glucosa", "Extracto_de_Levadura", "Triptofano"], value="Glucosa")
|
517 |
fixed_level_input = gr.Slider(label="Nivel de Variable Fija", minimum=0, maximum=1, step=0.01, value=0.5)
|
518 |
plot_button = gr.Button("Generar Gráfico")
|
519 |
+
# Usar Gallery para mostrar las imágenes
|
520 |
+
gallery = gr.Gallery(label="Gráficos RSM").style(preview=False, grid=(3,3), height="auto")
|
521 |
+
image_output = gr.Image(label="Descargar Gráfico")
|
522 |
|
523 |
load_button.click(
|
524 |
load_data,
|
|
|
528 |
|
529 |
fit_button.click(fit_and_optimize_model, outputs=[model_completo_output, pareto_completo_output, model_simplificado_output, pareto_simplificado_output, equation_output, optimization_table_output, prediction_table_output, contribution_table_output, anova_table_output])
|
530 |
|
531 |
+
plot_button.click(generate_rsm_plot, inputs=[fixed_variable_input, fixed_level_input], outputs=[gallery, image_output])
|
532 |
|
533 |
+
# Asociar las funciones de descarga a los botones
|
534 |
+
download_excel_button.click(download_excel, outputs=excel_file_output)
|
535 |
+
download_images_button.click(download_images, outputs=zip_file_output)
|
536 |
|
537 |
# Ejemplo de uso
|
538 |
gr.Markdown("## Ejemplo de uso")
|
|
|
542 |
gr.Markdown("4. Haz clic en 'Ajustar Modelo y Optimizar' para ajustar el modelo y encontrar los niveles óptimos de los factores.")
|
543 |
gr.Markdown("5. Selecciona una variable fija y su nivel en los controles deslizantes.")
|
544 |
gr.Markdown("6. Haz clic en 'Generar Gráfico' para generar un gráfico de superficie de respuesta.")
|
545 |
+
gr.Markdown("7. Haz clic en 'Descargar Tablas en Excel' para obtener un archivo .xlsx con todas las tablas generadas.")
|
546 |
+
gr.Markdown("8. Haz clic en 'Descargar Gráficos en ZIP' para obtener un archivo .zip con todas las imágenes de los gráficos.")
|
547 |
|
548 |
demo.launch()
|