mendozame23's picture
Update app.py
42f6eed verified
raw
history blame contribute delete
No virus
1.57 kB
import streamlit as st
import numpy as np
import matplotlib.pyplot as plt
import optuna
st.title("Optimization tool")
func_user = st.selectbox("Choose a function:", ("cuadratic", "sine", "gaussian"))
# ("sin(x/10)", "(x-2)^2", "exp-(x-4)^2")
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))
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
opt_user = st.selectbox("Choose the optimization direction:", ("minimize", "maximize"))
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)
def objective(trial):
x = trial.suggest_float("x", x_low, x_upp)
return func_to_use(x)
study = optuna.create_study(direction=opt_user)
study.optimize(objective, n_trials=500)
x_opt = study.best_params["x"]
y_opt = func_to_use(x_opt)
st.write(f"The critical point found is ({x_opt:,.4f}, {y_opt:,.4f}).")
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",
)
st.pyplot(plt)