mendozame23 commited on
Commit
0489920
1 Parent(s): 76f83fe

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +70 -0
app.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import numpy as np
3
+ import matplotlib.pyplot as plt
4
+ import optuna
5
+
6
+ st.title("Optimization tool")
7
+
8
+ func_user = st.selectbox("Choose a function:", ("cuadratic", "sine", "gaussian"))
9
+ # ("sin(x/10)", "(x-2)^2", "exp-(x-4)^2")
10
+
11
+
12
+ def func_cuadratic(x):
13
+ return (x - 2) ** 2
14
+
15
+
16
+ def func_sine(x):
17
+ return np.sin(x / 10)
18
+
19
+
20
+ def func_gauss(x):
21
+ return np.exp(-((x - 4) ** 2))
22
+
23
+
24
+ if func_user == "cuadratic":
25
+ st.latex(r"(x - 2)^2")
26
+ func_to_use = func_cuadratic
27
+
28
+ elif func_user == "sine":
29
+ st.latex(r"sin({ x \over 10 })")
30
+ func_to_use = func_sine
31
+
32
+ else:
33
+ st.latex(r"e^{-(x-4)^2}")
34
+ func_to_use = func_gauss
35
+
36
+
37
+ opt_user = st.selectbox("Choose the optimization direction:", ("minimize", "maximize"))
38
+
39
+ x_low = st.number_input("Please, give me the lower bound:", value=-10)
40
+ x_upp = st.number_input("Please, give me the upper bound:", value=10)
41
+
42
+
43
+ def objective(trial):
44
+ x = trial.suggest_float("x", x_low, x_upp)
45
+ return func_to_use(x)
46
+
47
+
48
+ study = optuna.create_study(direction=opt_user)
49
+ study.optimize(objective, n_trials=500)
50
+
51
+ x_opt = study.best_params["x"]
52
+ y_opt = func_to_use(x_opt)
53
+
54
+ st.write(f"The critical point found is ({x_opt:,.4f}, {y_opt:,.4f}).")
55
+
56
+ x_to_use = np.linspace(x_low, x_upp)
57
+
58
+ plt.title("Plot of critical point within interval given by user")
59
+ plt.xlabel("x axis")
60
+ plt.ylabel("y axis")
61
+ plt.plot(x_to_use, func_to_use(x_to_use))
62
+ plt.scatter(x_opt, func_to_use(x_opt), c="red")
63
+ plt.annotate(
64
+ f"({x_opt:,.2f}, {y_opt:,.2f})",
65
+ (x_opt, y_opt),
66
+ textcoords="offset points",
67
+ ha="center",
68
+ )
69
+
70
+ st.pyplot(plt)