Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -205,7 +205,7 @@ class RSM_BoxBehnken:
|
|
205 |
|
206 |
# Convertir la malla de variables naturales a codificadas
|
207 |
x_grid_coded = self.natural_to_coded(x_grid_natural, varying_variables[0])
|
208 |
-
y_grid_coded = self.natural_to_coded(
|
209 |
|
210 |
# Crear un DataFrame para la predicci贸n con variables codificadas
|
211 |
prediction_data = pd.DataFrame({
|
@@ -302,179 +302,31 @@ class RSM_BoxBehnken:
|
|
302 |
|
303 |
# --- Funciones para la Interfaz de Gradio ---
|
304 |
|
305 |
-
|
306 |
-
|
307 |
-
|
308 |
-
|
309 |
-
|
310 |
-
|
311 |
-
|
312 |
-
|
313 |
-
|
314 |
-
|
315 |
-
|
316 |
-
|
317 |
-
|
318 |
-
|
319 |
-
|
320 |
-
|
321 |
-
|
322 |
-
|
323 |
-
|
324 |
-
|
325 |
-
|
326 |
-
# Personalized model fitting is now triggered separately by custom_model_button
|
327 |
-
optimization_table = rsm.optimize()
|
328 |
-
equation = rsm.get_simplified_equation()
|
329 |
-
prediction_table = rsm.generate_prediction_table()
|
330 |
-
contribution_table = rsm.calculate_contribution_percentage()
|
331 |
-
anova_table = rsm.calculate_detailed_anova()
|
332 |
-
|
333 |
-
rsm.generate_all_plots() # Generate all plots for all models after fitting
|
334 |
-
|
335 |
-
equation_formatted = equation.replace(" + ", "<br>+ ").replace(" ** ", "^").replace("*", " 脳 ")
|
336 |
-
equation_formatted = f"### Ecuaci贸n del Modelo Simplificado:<br>{equation_formatted}"
|
337 |
-
|
338 |
-
excel_path = rsm.save_tables_to_excel()
|
339 |
-
zip_path = rsm.save_figures_to_zip()
|
340 |
-
|
341 |
-
return (
|
342 |
-
model_completo.summary().as_html(),
|
343 |
-
pareto_completo,
|
344 |
-
model_simplificado_output, # output_components are correctly referenced now
|
345 |
-
pareto_simplificado,
|
346 |
-
equation_formatted,
|
347 |
-
optimization_table,
|
348 |
-
prediction_table,
|
349 |
-
contribution_table,
|
350 |
-
anova_table,
|
351 |
-
zip_path,
|
352 |
-
excel_path
|
353 |
-
)
|
354 |
-
|
355 |
-
def fit_custom_model(factor_checkboxes, interaction_checkboxes, model_personalized_output_component, pareto_personalized_output_component):
|
356 |
-
if 'rsm' not in globals():
|
357 |
-
return [None]*2 # adjust output number
|
358 |
-
|
359 |
-
formula_parts = [rsm.x1_name, rsm.x2_name, rsm.x3_name] if "factors" in factor_checkboxes else []
|
360 |
-
if "x1_sq" in factor_checkboxes: formula_parts.append(f'I({rsm.x1_name}**2)')
|
361 |
-
if "x2_sq" in factor_checkboxes: formula_parts.append(f'I({rsm.x2_name}**2)')
|
362 |
-
if "x3_sq" in factor_checkboxes: formula_parts.append(f'I({rsm.x3_name}**2)')
|
363 |
-
if "x1x2" in interaction_checkboxes: formula_parts.append(f'{rsm.x1_name}:{rsm.x2_name}')
|
364 |
-
if "x1x3" in interaction_checkboxes: formula_parts.append(f'{rsm.x1_name}:{rsm.x3_name}')
|
365 |
-
if "x2x3" in interaction_checkboxes: formula_parts.append(f'{rsm.x2_name}:{rsm.x3_name}')
|
366 |
-
|
367 |
-
if not formula_parts:
|
368 |
-
formula = f'{rsm.y_name} ~ 1' # Intercept-only model if nothing selected
|
369 |
-
else:
|
370 |
-
formula = f'{rsm.y_name} ~ ' + ' + '.join(formula_parts)
|
371 |
-
|
372 |
-
custom_model, pareto_custom = rsm.fit_personalized_model(formula) # Fit personalized model
|
373 |
-
rsm.generate_all_plots() # Regenerate plots to include personalized model plots
|
374 |
-
|
375 |
-
return custom_model.summary().as_html(), pareto_custom # return values for outputs
|
376 |
-
|
377 |
-
|
378 |
-
def show_plot(current_index, all_figures, model_type): # Modified to accept model_type
|
379 |
-
figure_list = []
|
380 |
-
if model_type == 'full':
|
381 |
-
figure_list = rsm.all_figures_full
|
382 |
-
elif model_type == 'simplified':
|
383 |
-
figure_list = rsm.all_figures_simplified
|
384 |
-
elif model_type == 'personalized':
|
385 |
-
figure_list = rsm.all_figures_personalized
|
386 |
-
|
387 |
-
if not figure_list:
|
388 |
-
return None, f"No hay gr谩ficos disponibles para el modelo {model_type}.", current_index
|
389 |
-
selected_fig = figure_list[current_index]
|
390 |
-
plot_info_text = f"Gr谩fico {current_index + 1} de {len(figure_list)} (Modelo {model_type.capitalize()})" # Updated plot info
|
391 |
-
return selected_fig, plot_info_text, current_index
|
392 |
-
|
393 |
-
def navigate_plot(direction, current_index, all_figures, model_type): # Modified to accept model_type
|
394 |
-
figure_list = []
|
395 |
-
if model_type == 'full':
|
396 |
-
figure_list = rsm.all_figures_full
|
397 |
-
elif model_type == 'simplified':
|
398 |
-
figure_list = rsm.all_figures_simplified
|
399 |
-
elif model_type == 'personalized':
|
400 |
-
figure_list = rsm.all_figures_personalized
|
401 |
-
|
402 |
-
if not figure_list:
|
403 |
-
return None, f"No hay gr谩ficos disponibles para el modelo {model_type}.", current_index
|
404 |
-
|
405 |
-
if direction == 'left':
|
406 |
-
new_index = (current_index - 1) % len(figure_list)
|
407 |
-
elif direction == 'right':
|
408 |
-
new_index = (current_index + 1) % len(figure_list)
|
409 |
-
else:
|
410 |
-
new_index = current_index
|
411 |
-
|
412 |
-
selected_fig = figure_list[new_index]
|
413 |
-
plot_info_text = f"Gr谩fico {new_index + 1} de {len(figure_list)} (Modelo {model_type.capitalize()})" # Updated plot info
|
414 |
-
|
415 |
-
return selected_fig, plot_info_text, new_index
|
416 |
-
|
417 |
-
def download_current_plot(all_figures, current_index, model_type): # Modified to accept model_type
|
418 |
-
figure_list = []
|
419 |
-
if model_type == 'full':
|
420 |
-
figure_list = rsm.all_figures_full
|
421 |
-
elif model_type == 'simplified':
|
422 |
-
figure_list = rsm.all_figures_simplified
|
423 |
-
elif model_type == 'personalized':
|
424 |
-
figure_list = rsm.all_figures_personalized
|
425 |
-
if not figure_list:
|
426 |
-
return None
|
427 |
-
fig = figure_list[current_index]
|
428 |
-
img_bytes = rsm.save_fig_to_bytes(fig)
|
429 |
-
filename = f"Grafico_RSM_{model_type}_{current_index + 1}.png" # Added model type to filename
|
430 |
-
|
431 |
-
with tempfile.NamedTemporaryFile(delete=False, suffix=".png") as temp_file:
|
432 |
-
temp_file.write(img_bytes)
|
433 |
-
temp_path = temp_file.name
|
434 |
-
return temp_path
|
435 |
-
|
436 |
-
def download_all_plots_zip(model_type): # Modified to accept model_type
|
437 |
-
if 'rsm' not in globals():
|
438 |
-
return None
|
439 |
-
if model_type == 'full':
|
440 |
-
rsm.all_figures = rsm.all_figures_full # Set current figures to download
|
441 |
-
elif model_type == 'simplified':
|
442 |
-
rsm.all_figures = rsm.all_figures_simplified
|
443 |
-
elif model_type == 'personalized':
|
444 |
-
rsm.all_figures = rsm.all_figures_personalized
|
445 |
-
|
446 |
-
zip_path = rsm.save_figures_to_zip()
|
447 |
-
if zip_path:
|
448 |
-
filename = f"Graficos_RSM_{model_type}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.zip" # Added model type to filename
|
449 |
-
return zip_path
|
450 |
-
return None
|
451 |
-
|
452 |
-
def download_all_tables_excel():
|
453 |
-
"""
|
454 |
-
Descarga todas las tablas en un archivo Excel con m煤ltiples hojas.
|
455 |
-
"""
|
456 |
-
if 'rsm' not in globals():
|
457 |
-
return None
|
458 |
-
excel_path = rsm.save_tables_to_excel()
|
459 |
-
if excel_path:
|
460 |
-
filename = f"Tablas_RSM_{datetime.now().strftime('%Y%m%d_%H%M%S')}.xlsx"
|
461 |
-
# Gradio no permite renombrar directamente, por lo que retornamos la ruta del archivo
|
462 |
-
return excel_path
|
463 |
-
return None
|
464 |
-
|
465 |
-
def exportar_word(rsm_instance, tables_dict):
|
466 |
-
"""
|
467 |
-
Funci贸n para exportar las tablas a un documento de Word.
|
468 |
-
"""
|
469 |
-
word_path = rsm_instance.export_tables_to_word(tables_dict)
|
470 |
-
if word_path and os.path.exists(word_path):
|
471 |
-
return word_path
|
472 |
-
return None
|
473 |
-
|
474 |
-
|
475 |
-
# --- Crear la interfaz de Gradio ---
|
476 |
|
477 |
def create_gradio_interface():
|
|
|
|
|
478 |
with gr.Blocks() as demo:
|
479 |
gr.Markdown("# Optimizaci贸n de la Absorbancia usando RSM")
|
480 |
|
@@ -493,28 +345,28 @@ def create_gradio_interface():
|
|
493 |
with gr.Column():
|
494 |
fit_button = gr.Button("Ajustar Modelo Simplificado y Completo") # Button label changed
|
495 |
gr.Markdown("**Modelo Completo**")
|
496 |
-
model_completo_output = gr.HTML()
|
497 |
-
pareto_completo_output = gr.Plot()
|
498 |
gr.Markdown("**Modelo Simplificado**")
|
499 |
-
model_simplificado_output = gr.HTML()
|
500 |
-
pareto_simplificado_output = gr.Plot()
|
501 |
|
502 |
gr.Markdown("## Modelo Personalizado") # Personalized Model Section
|
503 |
-
|
504 |
-
|
505 |
custom_model_button = gr.Button("Ajustar Modelo Personalizado") # Fit Custom Model Button
|
506 |
-
|
507 |
-
|
508 |
|
509 |
gr.Markdown("**Ecuaci贸n del Modelo Simplificado**")
|
510 |
-
equation_output = gr.HTML()
|
511 |
-
optimization_table_output = gr.Dataframe(label="Tabla de Optimizaci贸n", interactive=False)
|
512 |
-
prediction_table_output = gr.Dataframe(label="Tabla de Predicciones", interactive=False)
|
513 |
-
contribution_table_output = gr.Dataframe(label="Tabla de % de Contribuci贸n", interactive=False)
|
514 |
-
anova_table_output = gr.Dataframe(label="Tabla ANOVA Detallada", interactive=False)
|
515 |
|
516 |
gr.Markdown("## Descargar Todas las Tablas")
|
517 |
-
|
518 |
download_word_button = gr.DownloadButton("Descargar Tablas en Word")
|
519 |
|
520 |
with gr.Column():
|
@@ -526,14 +378,14 @@ def create_gradio_interface():
|
|
526 |
with gr.Row():
|
527 |
left_button = gr.Button("<")
|
528 |
right_button = gr.Button(">")
|
529 |
-
rsm_plot_output = gr.Plot()
|
530 |
-
plot_info = gr.Textbox(label="Informaci贸n del Gr谩fico", value="Gr谩fico 1 de 9", interactive=False)
|
531 |
with gr.Row():
|
532 |
-
|
533 |
-
|
534 |
-
current_index_state = gr.State(0)
|
535 |
-
all_figures_state = gr.State([])
|
536 |
-
current_model_type_state = gr.State('simplified')
|
537 |
|
538 |
|
539 |
# Cargar datos
|
@@ -565,8 +417,8 @@ def create_gradio_interface():
|
|
565 |
# Ajustar modelo personalizado
|
566 |
custom_model_button.click( # New event for custom model fitting
|
567 |
fit_custom_model,
|
568 |
-
inputs=[
|
569 |
-
outputs=[
|
570 |
)
|
571 |
|
572 |
|
|
|
205 |
|
206 |
# Convertir la malla de variables naturales a codificadas
|
207 |
x_grid_coded = self.natural_to_coded(x_grid_natural, varying_variables[0])
|
208 |
+
y_grid_coded = self.natural_to_coded(y_range_natural, varying_variables[1])
|
209 |
|
210 |
# Crear un DataFrame para la predicci贸n con variables codificadas
|
211 |
prediction_data = pd.DataFrame({
|
|
|
302 |
|
303 |
# --- Funciones para la Interfaz de Gradio ---
|
304 |
|
305 |
+
model_completo_output = gr.HTML()
|
306 |
+
pareto_completo_output = gr.Plot()
|
307 |
+
model_simplificado_output = gr.HTML()
|
308 |
+
pareto_simplificado_output = gr.Plot()
|
309 |
+
equation_output = gr.HTML()
|
310 |
+
optimization_table_output = gr.Dataframe(label="Tabla de Optimizaci贸n", interactive=False)
|
311 |
+
prediction_table_output = gr.Dataframe(label="Tabla de Predicciones", interactive=False)
|
312 |
+
contribution_table_output = gr.Dataframe(label="Tabla de % de Contribuci贸n", interactive=False)
|
313 |
+
anova_table_output = gr.Dataframe(label="Tabla ANOVA Detallada", interactive=False)
|
314 |
+
download_all_plots_button = gr.DownloadButton("Descargar Todos los Gr谩ficos (ZIP)")
|
315 |
+
download_excel_button = gr.DownloadButton("Descargar Tablas en Excel")
|
316 |
+
rsm_plot_output = gr.Plot()
|
317 |
+
plot_info = gr.Textbox(label="Informaci贸n del Gr谩fico", value="Gr谩fico 1 de 9", interactive=False)
|
318 |
+
current_index_state = gr.State(0)
|
319 |
+
all_figures_state = gr.State([])
|
320 |
+
current_model_type_state = gr.State('simplified')
|
321 |
+
model_personalized_output = gr.HTML() # Output for personalized model summary
|
322 |
+
pareto_personalized_output = gr.Plot() # Pareto for personalized model
|
323 |
+
factor_checkboxes = gr.CheckboxGroup(["factors", "x1_sq", "x2_sq", "x3_sq"], label="T茅rminos de Factores", value=["factors", "x1_sq", "x2_sq", "x3_sq"]) # Factor Checkboxes
|
324 |
+
interaction_checkboxes = gr.CheckboxGroup(["x1x2", "x1x3", "x2x3"], label="T茅rminos de Interacci贸n") # Interaction Checkboxes
|
325 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
326 |
|
327 |
def create_gradio_interface():
|
328 |
+
global 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, download_all_plots_button, download_excel_button, rsm_plot_output, plot_info, current_index_state, all_figures_state, current_model_type_state, model_personalized_output, pareto_personalized_output, factor_checkboxes, interaction_checkboxes
|
329 |
+
|
330 |
with gr.Blocks() as demo:
|
331 |
gr.Markdown("# Optimizaci贸n de la Absorbancia usando RSM")
|
332 |
|
|
|
345 |
with gr.Column():
|
346 |
fit_button = gr.Button("Ajustar Modelo Simplificado y Completo") # Button label changed
|
347 |
gr.Markdown("**Modelo Completo**")
|
348 |
+
model_completo_output = model_completo_output # gr.HTML() # output_components are now global
|
349 |
+
pareto_completo_output = pareto_completo_output # gr.Plot()
|
350 |
gr.Markdown("**Modelo Simplificado**")
|
351 |
+
model_simplificado_output = model_simplificado_output # gr.HTML()
|
352 |
+
pareto_simplificado_output = pareto_simplificado_output # gr.Plot()
|
353 |
|
354 |
gr.Markdown("## Modelo Personalizado") # Personalized Model Section
|
355 |
+
factor_checkboxes_comp = factor_checkboxes # gr.CheckboxGroup(["factors", "x1_sq", "x2_sq", "x3_sq"], label="T茅rminos de Factores", value=["factors", "x1_sq", "x2_sq", "x3_sq"]) # Factor Checkboxes
|
356 |
+
interaction_checkboxes_comp = interaction_checkboxes # gr.CheckboxGroup(["x1x2", "x1x3", "x2x3"], label="T茅rminos de Interacci贸n") # Interaction Checkboxes
|
357 |
custom_model_button = gr.Button("Ajustar Modelo Personalizado") # Fit Custom Model Button
|
358 |
+
model_personalized_output_comp = model_personalized_output # gr.HTML() # Output for personalized model summary
|
359 |
+
pareto_personalized_output_comp = pareto_personalized_output # gr.Plot() # Pareto for personalized model
|
360 |
|
361 |
gr.Markdown("**Ecuaci贸n del Modelo Simplificado**")
|
362 |
+
equation_output = equation_output # gr.HTML()
|
363 |
+
optimization_table_output = optimization_table_output # gr.Dataframe(label="Tabla de Optimizaci贸n", interactive=False)
|
364 |
+
prediction_table_output = prediction_table_output # gr.Dataframe(label="Tabla de Predicciones", interactive=False)
|
365 |
+
contribution_table_output = contribution_table_output # gr.Dataframe(label="Tabla de % de Contribuci贸n", interactive=False)
|
366 |
+
anova_table_output = anova_table_output # gr.Dataframe(label="Tabla ANOVA Detallada", interactive=False)
|
367 |
|
368 |
gr.Markdown("## Descargar Todas las Tablas")
|
369 |
+
download_excel_button_comp = download_excel_button # gr.DownloadButton("Descargar Tablas en Excel")
|
370 |
download_word_button = gr.DownloadButton("Descargar Tablas en Word")
|
371 |
|
372 |
with gr.Column():
|
|
|
378 |
with gr.Row():
|
379 |
left_button = gr.Button("<")
|
380 |
right_button = gr.Button(">")
|
381 |
+
rsm_plot_output = rsm_plot_output # gr.Plot()
|
382 |
+
plot_info = plot_info # gr.Textbox(label="Informaci贸n del Gr谩fico", value="Gr谩fico 1 de 9", interactive=False)
|
383 |
with gr.Row():
|
384 |
+
download_plot_button_comp = download_plot_button # gr.DownloadButton("Descargar Gr谩fico Actual (PNG)")
|
385 |
+
download_all_plots_button_comp = download_all_plots_button # gr.DownloadButton("Descargar Todos los Gr谩ficos (ZIP)")
|
386 |
+
current_index_state = current_index_state # gr.State(0)
|
387 |
+
all_figures_state = all_figures_state # gr.State([])
|
388 |
+
current_model_type_state = current_model_type_state # gr.State('simplified')
|
389 |
|
390 |
|
391 |
# Cargar datos
|
|
|
417 |
# Ajustar modelo personalizado
|
418 |
custom_model_button.click( # New event for custom model fitting
|
419 |
fit_custom_model,
|
420 |
+
inputs=[factor_checkboxes_comp, interaction_checkboxes_comp],
|
421 |
+
outputs=[model_personalized_output_comp, pareto_personalized_output_comp] # pass output components
|
422 |
)
|
423 |
|
424 |
|