import streamlit as st import numpy as np import matplotlib.pyplot as plt import optuna # Título de la aplicación st.title("Optimization tool") # Selección de la función func_user = st.selectbox("Choose a function:", ("cuadratic", "sine", "gaussian")) # ("sin(x/10)", "(x-2)^2", "exp-(x-4)^2") # Definición de las funciones a optimizar def func_cuadratic(x): return (x - 2) ** 2 def func_sine(x): return np.sin(x / 10) def func_gauss(x): return np.exp(-((x - 4) ** 2)) # Mostrar la fórmula de la función seleccionada y asignar la función correspondiente if func_user == "cuadratic": st.latex(r"(x - 2)^2") func_to_use = func_cuadratic elif func_user == "sine": st.latex(r"sin({ x \over 10 })") func_to_use = func_sine else: st.latex(r"e^{-(x-4)^2}") func_to_use = func_gauss # Selección de la dirección de optimización opt_user = st.selectbox("Choose the optimization direction:", ("minimize", "maximize")) # Entrada de los límites inferiores y superiores x_low = st.number_input("Please, give me the lower bound:", value=-10) x_upp = st.number_input("Please, give me the upper bound:", value=10) # Definición de la función objetivo para Optuna def objective(trial): x = trial.suggest_float("x", x_low, x_upp) return func_to_use(x) # Crear el estudio de Optuna study = optuna.create_study(direction=opt_user) # Ejecutar la optimización study.optimize(objective, n_trials=500) # Obtener el valor óptimo de x y la función en ese punto x_opt = study.best_params["x"] y_opt = func_to_use(x_opt) # Mostrar los resultados de la optimización st.write(f"The critical point found is ({x_opt:,.4f}, {y_opt:,.4f}).") # Visualización de los resultados x_to_use = np.linspace(x_low, x_upp) plt.title("Plot of critical point within interval given by user") plt.xlabel("x axis") plt.ylabel("y axis") plt.plot(x_to_use, func_to_use(x_to_use)) plt.scatter(x_opt, func_to_use(x_opt), c="red") plt.annotate( f"({x_opt:,.2f}, {y_opt:,.2f})", (x_opt, y_opt), textcoords="offset points", ha="center", ) # Mostrar la gráfica en Streamlit st.pyplot(plt)