Spaces:
Running
Running
Commit
·
509b18a
1
Parent(s):
71d382d
first commit
Browse files- app.py +211 -0
- human_vs_BO_results.pkl +3 -0
- requirements.txt +4 -0
app.py
ADDED
@@ -0,0 +1,211 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import gradio as gr
|
3 |
+
import pickle
|
4 |
+
|
5 |
+
import plotly.graph_objects as go
|
6 |
+
import plotly.express as px
|
7 |
+
|
8 |
+
import pandas as pd
|
9 |
+
|
10 |
+
# Global variable to store results
|
11 |
+
results_storage = pd.DataFrame(columns=['Concentration (%w/v)', 'Flow Rate (mL/h)', 'Voltage (kV)', 'Solvent', 'Size (um)', 'Feasible?'])
|
12 |
+
|
13 |
+
# define a Dataframe styler to highlight the Feasible? column to be green and red
|
14 |
+
def highlight_success(val):
|
15 |
+
color = 'lightgreen' if val == 'Success' else 'lightcoral'
|
16 |
+
return f'color:white;background-color: {color}'
|
17 |
+
|
18 |
+
def sim_espray_constrained(x, noise_se=None):
|
19 |
+
# Define the equations
|
20 |
+
conc = x[:, 0]
|
21 |
+
flow_rate = x[:, 1]
|
22 |
+
voltage = x[:, 2]
|
23 |
+
solvent = x[:, 3]
|
24 |
+
diameter = (np.sqrt(conc) * np.sqrt(flow_rate)) / np.log2(voltage) * 10 + 0.4 + solvent # Diameter in micrometers
|
25 |
+
if noise_se is not None:
|
26 |
+
diameter = diameter + noise_se * np.random.randn(*diameter.shape)
|
27 |
+
exp_con = (np.log(flow_rate) * (solvent - 0.5) + 1.40 >= 0).astype(float)
|
28 |
+
return np.column_stack((diameter, exp_con))
|
29 |
+
|
30 |
+
X_init = np.array([[0.5, 15, 10, 0],
|
31 |
+
[0.5, 0.1, 10, 1],
|
32 |
+
[3, 20, 15, 0],
|
33 |
+
[1, 20, 10, 1],
|
34 |
+
[0.2, 0.02, 10, 1]])
|
35 |
+
|
36 |
+
Y_init = sim_espray_constrained(X_init)
|
37 |
+
exp_record_df = pd.DataFrame(X_init, columns=['Concentration (%w/v)', 'Flow Rate (mL/h)', 'Voltage (kV)', 'Solvent'])
|
38 |
+
exp_record_df['Size (um)'] = Y_init[:, 0]
|
39 |
+
# map 1 to CHCl3 and 0 to DMAc
|
40 |
+
exp_record_df['Solvent'] = ['DMAc' if x == 0 else 'CHCl3' for x in exp_record_df['Solvent']]
|
41 |
+
exp_record_df['Feasible?'] = ['Success' if x == 1 else 'Failed' for x in Y_init[:, 1]]
|
42 |
+
|
43 |
+
gr_exp_record_df = gr.DataFrame(value=exp_record_df.style.map(highlight_success, subset=['Feasible?']).format(precision=3), label="Prior Experiments")
|
44 |
+
|
45 |
+
def import_results():
|
46 |
+
strategies = ['qEI', 'qEI_vi_mixed_con', 'qEICF_vi_mixed_con', 'rnd']
|
47 |
+
|
48 |
+
# Load results from pickle file
|
49 |
+
with open('human_vs_BO_results.pkl', 'rb') as f:
|
50 |
+
best_distances = pickle.load(f)
|
51 |
+
|
52 |
+
# vstack all values in best_distances
|
53 |
+
best_distances_vstack = {k: np.vstack(best_distances[k]) for k in strategies}
|
54 |
+
best_distances_all_trials = -np.vstack([best_distances_vstack[k] for k in strategies])
|
55 |
+
best_distances_all_trials_df = pd.DataFrame(best_distances_all_trials)
|
56 |
+
best_distances_all_trials_df['strategy'] = np.repeat(['Vanilla BO', 'Constrained BO', 'CCBO', 'Random'], 20)
|
57 |
+
best_distances_all_trials_df['trial'] = list(range(20)) * len(strategies)
|
58 |
+
|
59 |
+
best_distances_df_long = pd.melt(best_distances_all_trials_df, id_vars=['strategy', 'trial'], var_name='iteration', value_name='regret')
|
60 |
+
return best_distances_df_long
|
61 |
+
|
62 |
+
def calc_human_performance(df):
|
63 |
+
# convert back solvent to 0 and 1
|
64 |
+
df['Solvent'] = [0 if x == 'DMAc' else 1 for x in df['Solvent']]
|
65 |
+
|
66 |
+
TARGET_SIZE = 3.0 # Example target size
|
67 |
+
ROUNDS = len(df) // 2
|
68 |
+
|
69 |
+
X_human = df[['Concentration (%w/v)', 'Flow Rate (mL/h)', 'Voltage (kV)', 'Solvent']].values
|
70 |
+
|
71 |
+
X_human_init = X_init.copy()
|
72 |
+
Y_human_init = Y_init.copy()
|
73 |
+
|
74 |
+
best_human_distance = []
|
75 |
+
|
76 |
+
for iter in range(ROUNDS + 1):
|
77 |
+
Y_distance = -np.abs(Y_human_init[:, 0] - TARGET_SIZE)
|
78 |
+
best_human_distance.append(np.ma.masked_array(Y_distance, mask=~Y_human_init[:, 1].astype(bool)).max())
|
79 |
+
new_x = X_human[2 * iter:2 * (iter + 1)]
|
80 |
+
X_human_init = np.vstack([X_human_init, new_x])
|
81 |
+
Y_human_init = np.vstack([Y_human_init, sim_espray_constrained(new_x)])
|
82 |
+
|
83 |
+
return -np.array(best_human_distance)
|
84 |
+
|
85 |
+
def plot_results(exp_data_df):
|
86 |
+
# Extract human performance
|
87 |
+
best_human_distance = calc_human_performance(exp_data_df)
|
88 |
+
|
89 |
+
# Import results
|
90 |
+
best_distances_df_long = import_results()
|
91 |
+
|
92 |
+
fig = go.Figure()
|
93 |
+
|
94 |
+
strategies = best_distances_df_long['strategy'].unique()
|
95 |
+
|
96 |
+
for strategy in strategies:
|
97 |
+
strategy_data = best_distances_df_long[best_distances_df_long['strategy'] == strategy]
|
98 |
+
|
99 |
+
# Calculate mean and standard deviation
|
100 |
+
mean_regret = strategy_data.groupby('iteration')['regret'].mean()
|
101 |
+
std_regret = strategy_data.groupby('iteration')['regret'].std()
|
102 |
+
|
103 |
+
iterations = mean_regret.index
|
104 |
+
color = px.colors.qualitative.Set2[strategies.tolist().index(strategy)]
|
105 |
+
|
106 |
+
# Add trace for mean line
|
107 |
+
mean_trace = go.Scatter(
|
108 |
+
x=iterations,
|
109 |
+
y=mean_regret,
|
110 |
+
mode='lines',
|
111 |
+
name=strategy,
|
112 |
+
line=dict(width=2, color=color)
|
113 |
+
)
|
114 |
+
fig.add_trace(mean_trace)
|
115 |
+
|
116 |
+
# Add trace for shaded area (standard deviation)
|
117 |
+
fig.add_trace(go.Scatter(
|
118 |
+
x=list(iterations) + list(iterations[::-1]),
|
119 |
+
y=list(mean_regret + std_regret) + list((mean_regret - std_regret)[::-1]),
|
120 |
+
fill='toself',
|
121 |
+
fillcolor=mean_trace.line.color.replace('rgb', 'rgba').replace(')', ',0.2)'),
|
122 |
+
line=dict(color='rgba(255,255,255,0)'),
|
123 |
+
showlegend=False,
|
124 |
+
name=f'{strategy} (std dev)'
|
125 |
+
))
|
126 |
+
# Add trace for human performance
|
127 |
+
fig.add_trace(go.Scatter(
|
128 |
+
x=list(range(len(best_human_distance))),
|
129 |
+
y=best_human_distance,
|
130 |
+
mode='lines+markers',
|
131 |
+
name='Human',
|
132 |
+
line=dict(width=2, color='brown')
|
133 |
+
))
|
134 |
+
|
135 |
+
fig.update_layout(
|
136 |
+
title='Performance Comparison',
|
137 |
+
xaxis_title='Iteration',
|
138 |
+
yaxis_title='Regret (μm)',
|
139 |
+
legend_title='Strategy',
|
140 |
+
template='plotly_white',
|
141 |
+
legend=dict(
|
142 |
+
x=0.01,
|
143 |
+
y=0.01,
|
144 |
+
bgcolor='rgba(255, 255, 255, 0.5)',
|
145 |
+
bordercolor='rgba(0, 0, 0, 0.5)',
|
146 |
+
borderwidth=1
|
147 |
+
)
|
148 |
+
)
|
149 |
+
|
150 |
+
return fig
|
151 |
+
|
152 |
+
def predict(text1, conc1, flow_rate1, voltage1, solvent1, text2, conc2, flow_rate2, voltage2, solvent2):
|
153 |
+
global results_storage
|
154 |
+
solvent_value1 = 0 if solvent1 == 'DMAc' else 1
|
155 |
+
solvent_value2 = 0 if solvent2 == 'DMAc' else 1
|
156 |
+
|
157 |
+
# Convert inputs to numpy array
|
158 |
+
inputs1 = np.array([[conc1, flow_rate1, voltage1, solvent_value1]])
|
159 |
+
inputs2 = np.array([[conc2, flow_rate2, voltage2, solvent_value2]])
|
160 |
+
|
161 |
+
# Get predictions
|
162 |
+
results1 = sim_espray_constrained(inputs1)
|
163 |
+
results2 = sim_espray_constrained(inputs2)
|
164 |
+
|
165 |
+
# Format output
|
166 |
+
diameter1 = results1[0, 0]
|
167 |
+
exp_con1 = results1[0, 1]
|
168 |
+
|
169 |
+
diameter2 = results2[0, 0]
|
170 |
+
exp_con2 = results2[0, 1]
|
171 |
+
|
172 |
+
# create a dataframe to store the results
|
173 |
+
results_df = pd.DataFrame(np.array([
|
174 |
+
[conc1, flow_rate1, voltage1, solvent_value1, diameter1, exp_con1],
|
175 |
+
[conc2, flow_rate2, voltage2, solvent_value2, diameter2, exp_con2]
|
176 |
+
]), columns=['Concentration (%w/v)', 'Flow Rate (mL/h)', 'Voltage (kV)', 'Solvent', 'Size (um)', 'Feasible?'])
|
177 |
+
|
178 |
+
results_df['Solvent'] = ['DMAc' if x == 0 else 'CHCl3' for x in results_df['Solvent']]
|
179 |
+
results_df['Feasible?'] = ['Success' if x == 1 else 'Failed' for x in results_df['Feasible?']]
|
180 |
+
|
181 |
+
results_storage = pd.concat([results_storage, results_df], ignore_index=True)
|
182 |
+
results_display = results_storage.style.map(highlight_success, subset=['Feasible?']).format(precision=3)
|
183 |
+
|
184 |
+
return (gr_exp_record_df, gr.DataFrame(value=results_display, label="Your Results"), plot_results(results_storage))
|
185 |
+
|
186 |
+
inputs = [
|
187 |
+
gr.Markdown("### Experiment 1"),
|
188 |
+
gr.Number(value=1.2, label="Concentration (%w/v, range: 0.05-5.00)", minimum=0.05, maximum=5.0, precision=3),
|
189 |
+
gr.Number(value=20.0, label="Flow Rate (mL/h, range: 0.01-60.00)", minimum=0.01, maximum=60.0, precision=3),
|
190 |
+
gr.Number(value=15.0, label="Voltage (kV, range: 10.00-18.00)", minimum=10.0, maximum=18.0, precision=3),
|
191 |
+
gr.Dropdown(['DMAc', 'CHCl3'], value='DMAc', label='Solvent'),
|
192 |
+
gr.Markdown("### Experiment 2"),
|
193 |
+
gr.Number(value=2.8, label="Concentration (%w/v, range: 0.05-5.00)", minimum=0.05, maximum=5.0, precision=3),
|
194 |
+
gr.Number(value=20.0, label="Flow Rate (mL/h, range: 0.01-60.00)", minimum=0.01, maximum=60.0, precision=3),
|
195 |
+
gr.Number(value=15.0, label="Voltage (kV, 10.00-18.00)", minimum=10.0, maximum=18.0, precision=3),
|
196 |
+
gr.Dropdown(['DMAc', 'CHCl3'], value='CHCl3', label='Solvent')
|
197 |
+
]
|
198 |
+
|
199 |
+
outputs = [gr_exp_record_df, gr.DataFrame(label="Your Results"), gr.Plot(label="Performance Comparison")]
|
200 |
+
|
201 |
+
description = "<h3>Welcome, challenger!</h3><p> If you think you may perform better than <strong>CCBO</strong>, try this interactive game to optimize electrospray! Rules are simple: <ul><li>Examine carefully the initial experiments you have on the right, remember, your target size is <u><i><strong>3.000</strong></i></u> ----></li><li>Select your experiment parameters, you have <strong>2</strong> experiments to run</li><li>Click <strong>Submit</strong> to see the results</li><li>Repeat the process for <strong>5</strong> iterations to see if you can beat CCBO!</li></ul></p>"
|
202 |
+
|
203 |
+
# Update interface
|
204 |
+
demo = gr.Interface(
|
205 |
+
fn=predict,
|
206 |
+
inputs=inputs,
|
207 |
+
outputs=outputs,
|
208 |
+
title="Human vs CCBO Campaign - Simulated Electrospray",
|
209 |
+
description=description
|
210 |
+
)
|
211 |
+
demo.launch()
|
human_vs_BO_results.pkl
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:091a2beae4611558eb610af040aeb74a2cba763f6a43fc218f033295d3bdd9fc
|
3 |
+
size 9179
|
requirements.txt
ADDED
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
1 |
+
numpy
|
2 |
+
torch
|
3 |
+
pandas
|
4 |
+
plotly
|