FrankWanger commited on
Commit
250d6ba
·
1 Parent(s): ef03fc8

updated ui and download options

Browse files
Files changed (1) hide show
  1. app.py +191 -33
app.py CHANGED
@@ -4,11 +4,54 @@ import pickle
4
  import plotly.graph_objects as go
5
  import plotly.express as px
6
  import pandas as pd
 
 
7
 
8
- # Define styling for success/failure highlighting
9
- def highlight_success(val):
10
- color = 'lightgreen' if val == 'Success' else 'lightcoral'
11
- return f'color:white;background-color: {color}'
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
 
13
  # Simulation function for electrospraying
14
  def sim_espray_constrained(x, noise_se=None):
@@ -42,7 +85,12 @@ exp_record_df = pd.DataFrame(X_init, columns=['Concentration (%w/v)', 'Flow Rate
42
  exp_record_df['Size (um)'] = Y_init[:, 0]
43
  exp_record_df['Solvent'] = ['DMAc' if x == 0 else 'CHCl3' for x in exp_record_df['Solvent']]
44
  exp_record_df['Feasible?'] = ['Success' if x == 1 else 'Failed' for x in Y_init[:, 1]]
45
- prior_experiments_display = exp_record_df.style.map(highlight_success, subset=['Feasible?']).format(precision=3)
 
 
 
 
 
46
 
47
  # Functions for data processing and visualization
48
  def import_results():
@@ -166,6 +214,17 @@ def plot_results(exp_data_df):
166
 
167
  return fig
168
 
 
 
 
 
 
 
 
 
 
 
 
169
  # Prediction function - simplified signature by removing unnecessary text params
170
  def predict(state, conc1, flow_rate1, voltage1, solvent1, conc2, flow_rate2, voltage2, solvent2):
171
  # Get current results storage from state or initialize if None
@@ -193,63 +252,149 @@ def predict(state, conc1, flow_rate1, voltage1, solvent1, conc2, flow_rate2, vol
193
  results_df['Feasible?'] = ['Success' if x == 1 else 'Failed' for x in results_df['Feasible?']]
194
 
195
  results_storage = pd.concat([results_storage, results_df], ignore_index=True)
196
- results_display = results_storage.style.map(highlight_success, subset=['Feasible?']).format(precision=3)
 
 
 
 
 
197
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
198
  # Return updated state and UI updates
199
  return (
200
  results_storage,
201
  gr.DataFrame(value=prior_experiments_display, label="Prior Experiments"),
202
  gr.DataFrame(value=results_display, label="Your Results"),
203
- plot_results(results_storage)
 
 
 
 
204
  )
205
 
206
  # Reset results function
207
  def reset_results(state):
208
  results_storage = pd.DataFrame(columns=['Concentration (%w/v)', 'Flow Rate (mL/h)', 'Voltage (kV)', 'Solvent', 'Size (um)', 'Feasible?'])
 
 
 
 
 
 
 
 
 
209
  return (
210
- results_storage,
211
- gr.DataFrame(value=prior_experiments_display, label="Prior Experiments"),
212
- gr.DataFrame(value=results_storage.style.map(highlight_success, subset=['Feasible?']).format(precision=3), label="Your Results"),
213
- plot_results(results_storage)
 
 
 
 
214
  )
215
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
216
  # Application description
217
  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 (or below if you're using your phone), remember, your target size is <u><i><strong>3.000 um</strong></i></u> ----></li><li>Select your parameters, you have <strong>2</strong> experiments (chances) in each round, use them wisely! </li><li>Click <strong>Submit</strong> to see the results, reflect and improve your selection!</li><li>Repeat the process for <strong>5</strong> rounds to see if you can beat CCBO!</li></ul></p><p>Your data will not be stored, so feel free to play again, good luck!</p>"
218
 
219
  # Create Gradio interface
220
  with gr.Blocks() as demo:
221
- gr.Markdown("## Human vs CCBO Campaign - Optimize Electrospray")
222
- gr.Markdown(description)
223
-
224
  # Add state component to store user-specific results
225
  results_state = gr.State()
226
-
227
  with gr.Row():
228
  # Input parameters column
229
  with gr.Column():
230
- gr.Markdown("### Experiment 1")
231
- conc1 = gr.Slider(minimum=0.05, maximum=5.0, value=1.2, step=0.001, label="Concentration (%w/v)")
232
- flow_rate1 = gr.Slider(minimum=0.01, maximum=60.0, value=20.0, step=0.001, label="Flow Rate (mL/h)")
233
- voltage1 = gr.Slider(minimum=10.0, maximum=18.0, value=15.0, step=0.001, label="Voltage (kV)")
234
- solvent1 = gr.Dropdown(['DMAc', 'CHCl3'], value='DMAc', label='Solvent')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
235
 
236
- gr.Markdown("### Experiment 2")
237
- conc2 = gr.Slider(minimum=0.05, maximum=5.0, value=2.8, step=0.001, label="Concentration (%w/v)")
238
- flow_rate2 = gr.Slider(minimum=0.01, maximum=60.0, value=20.0, step=0.001, label="Flow Rate (mL/h)")
239
- voltage2 = gr.Slider(minimum=10.0, maximum=18.0, value=15.0, step=0.001, label="Voltage (kV)")
240
- solvent2 = gr.Dropdown(['DMAc', 'CHCl3'], value='CHCl3', label='Solvent')
241
 
242
  # Results display column
243
  with gr.Column():
244
  prior_experiments = gr.DataFrame(value=prior_experiments_display, label="Prior Experiments")
245
  results_df = gr.DataFrame(label="Your Results")
246
  perf_plot = gr.Plot(label="Performance Comparison")
247
-
248
- # Action buttons
249
- with gr.Row():
250
- submit_btn = gr.Button("Submit")
251
- reset_btn = gr.Button("Reset Results")
252
-
253
  # Connect the submit button to the predict function
254
  submit_btn.click(
255
  fn=predict,
@@ -258,14 +403,27 @@ with gr.Blocks() as demo:
258
  conc1, flow_rate1, voltage1, solvent1,
259
  conc2, flow_rate2, voltage2, solvent2
260
  ],
261
- outputs=[results_state, prior_experiments, results_df, perf_plot]
 
 
 
262
  )
263
 
264
  # Connect the reset button to the reset_results function
265
  reset_btn.click(
266
  fn=reset_results,
267
  inputs=[results_state],
268
- outputs=[results_state, prior_experiments, results_df, perf_plot]
 
 
 
 
 
 
 
 
 
 
269
  )
270
 
271
  demo.launch()
 
4
  import plotly.graph_objects as go
5
  import plotly.express as px
6
  import pandas as pd
7
+ import tempfile
8
+ import os
9
 
10
+ # Split the styling into two separate functions for clarity and simplicity
11
+ def style_feasible_column(val):
12
+ """Style for the Feasible? column"""
13
+ if val == 'Success':
14
+ return 'color:white;background-color: lightgreen'
15
+ elif val == 'Failed':
16
+ return 'color:white;background-color: lightcoral'
17
+ return ''
18
+
19
+ def style_size_column(val):
20
+ """Style for the Size column based on proximity to target"""
21
+ try:
22
+ val_float = float(val)
23
+
24
+ distance = val_float - 3.0 # Signed distance from target
25
+ abs_distance = abs(distance)
26
+
27
+ # Calculate width percentage based on distance
28
+ max_distance = 2.5
29
+ width_pct = 100 - min(abs_distance / max_distance * 100, 100)
30
+
31
+ # Determine color based on value position relative to target
32
+ if distance < 0:
33
+ color = f"rgba(0, 128, 128, {min(1.0, 0.4 + 0.6*(1-abs_distance/max_distance))})" # Teal for below
34
+ else:
35
+ color = f"rgba(230, 97, 0, {min(1.0, 0.4 + 0.6*(1-abs_distance/max_distance))})" # Orange for above
36
+
37
+ # Text styling based on proximity to target
38
+ if abs_distance > 3:
39
+ text_color = "grey"
40
+ elif abs_distance > 1:
41
+ text_color = "black"
42
+ else:
43
+ text_color = "white"
44
+
45
+ font_weight = "bold" if abs_distance < 0.5 else "normal"
46
+
47
+ # Create gradient style
48
+ return (
49
+ f"background: linear-gradient(90deg, {color} {width_pct}%, transparent {width_pct}%); "
50
+ f"color: {text_color}; "
51
+ f"font-weight: {font_weight}; "
52
+ )
53
+ except (ValueError, TypeError):
54
+ return ''
55
 
56
  # Simulation function for electrospraying
57
  def sim_espray_constrained(x, noise_se=None):
 
85
  exp_record_df['Size (um)'] = Y_init[:, 0]
86
  exp_record_df['Solvent'] = ['DMAc' if x == 0 else 'CHCl3' for x in exp_record_df['Solvent']]
87
  exp_record_df['Feasible?'] = ['Success' if x == 1 else 'Failed' for x in Y_init[:, 1]]
88
+
89
+ # Apply each styling function to its specific column
90
+ prior_experiments_display = exp_record_df.style\
91
+ .map(style_feasible_column, subset=['Feasible?'])\
92
+ .map(style_size_column, subset=['Size (um)'])\
93
+ .format(precision=3)
94
 
95
  # Functions for data processing and visualization
96
  def import_results():
 
214
 
215
  return fig
216
 
217
+ # Add function to calculate AUC
218
+ def calculate_auc(human_performance_values):
219
+ """Calculate the Area Under the Curve for a user's performance"""
220
+ # Simple trapezoidal integration
221
+ if len(human_performance_values) <= 1:
222
+ return 0
223
+
224
+ # AUC calculation using trapezoidal rule
225
+ auc_value = np.trapezoid(human_performance_values, dx=1)
226
+ return round(auc_value, 4)
227
+
228
  # Prediction function - simplified signature by removing unnecessary text params
229
  def predict(state, conc1, flow_rate1, voltage1, solvent1, conc2, flow_rate2, voltage2, solvent2):
230
  # Get current results storage from state or initialize if None
 
252
  results_df['Feasible?'] = ['Success' if x == 1 else 'Failed' for x in results_df['Feasible?']]
253
 
254
  results_storage = pd.concat([results_storage, results_df], ignore_index=True)
255
+
256
+ # Apply each styling function to its specific column
257
+ results_display = results_storage.style\
258
+ .map(style_feasible_column, subset=['Feasible?'])\
259
+ .map(style_size_column, subset=['Size (um)'])\
260
+ .format(precision=3)
261
 
262
+ # Check if user has completed 5 rounds (10 experiments)
263
+ completed = len(results_storage) >= 10
264
+
265
+ message = ""
266
+ auc_value = 0
267
+ usr_level = ""
268
+
269
+ if completed:
270
+ # Calculate AUC
271
+ human_performance = calc_human_performance(results_storage)
272
+ auc_value = calculate_auc(human_performance)
273
+ # beginner = 2.62, intermediate = 1.60, expert = 1.03
274
+ if auc_value > 4.10:
275
+ usr_level = "randomly playing!"
276
+ elif auc_value > 1.80:
277
+ usr_level = "a beginner."
278
+ elif auc_value > 1.30:
279
+ usr_level = "an intermediate user."
280
+ elif auc_value > 0.60:
281
+ usr_level = "an advanced user."
282
+ else:
283
+ usr_level = "... come on, you must have cheated (or you are extremely lucky)!"
284
+
285
+ message = f"🎉 Congratulations! You've completed all 5 rounds.\nYour performance AUC is ** {auc_value:.2f} ** and CCBO was ** 1.40 **.\nYou seems to be {usr_level}\nNow you can download your results or try again!"
286
+
287
  # Return updated state and UI updates
288
  return (
289
  results_storage,
290
  gr.DataFrame(value=prior_experiments_display, label="Prior Experiments"),
291
  gr.DataFrame(value=results_display, label="Your Results"),
292
+ plot_results(results_storage),
293
+ gr.update(visible=completed), # Show download button when completed
294
+ gr.update(value=message, visible=completed), # Show message when completed
295
+ gr.update(value=auc_value), # Update AUC value
296
+ gr.update(visible=completed) # Show result file component
297
  )
298
 
299
  # Reset results function
300
  def reset_results(state):
301
  results_storage = pd.DataFrame(columns=['Concentration (%w/v)', 'Flow Rate (mL/h)', 'Voltage (kV)', 'Solvent', 'Size (um)', 'Feasible?'])
302
+ # Generate the plot for empty results
303
+ empty_plot = plot_results(results_storage)
304
+
305
+ # Apply each styling function to its specific column
306
+ styled_results = results_storage.style\
307
+ .map(style_feasible_column, subset=['Feasible?'])\
308
+ .map(style_size_column, subset=['Size (um)'])\
309
+ .format(precision=3)
310
+
311
  return (
312
+ results_storage, # results_state
313
+ gr.DataFrame(value=prior_experiments_display, label="Prior Experiments"), # prior_experiments
314
+ gr.DataFrame(value=styled_results, label="Your Results"), # results_df
315
+ empty_plot, # perf_plot
316
+ gr.update(visible=False), # download_btn visibility
317
+ gr.update(value="", visible=False), # completion_message
318
+ gr.update(value=0), # auc_state
319
+ gr.update(visible=False) # result_file visibility
320
  )
321
 
322
+ # Function to prepare results for download
323
+ def prepare_results_for_download(results):
324
+ """Prepare results dataframe for download and save to CSV"""
325
+ if results is None or len(results) == 0:
326
+ return None
327
+
328
+ # Calculate human performance
329
+ human_performance = calc_human_performance(results)
330
+ auc_value = calculate_auc(human_performance)
331
+
332
+ # Add a summary row with AUC
333
+ summary_df = pd.DataFrame({
334
+ 'Concentration (%w/v)': ["Performance AUC:"],
335
+ 'Flow Rate (mL/h)': [auc_value],
336
+ 'Voltage (kV)': [""],
337
+ 'Solvent': [""],
338
+ 'Size (um)': [""],
339
+ 'Feasible?': [""]
340
+ })
341
+
342
+ # Combine results with summary
343
+ combined_df = pd.concat([results, summary_df], ignore_index=True)
344
+
345
+ # Save to temporary file
346
+ temp_dir = tempfile.gettempdir()
347
+ output_path = os.path.join(temp_dir, "electrospray_results.csv")
348
+ combined_df.to_csv(output_path, index=False)
349
+
350
+ return output_path
351
+
352
  # Application description
353
  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 (or below if you're using your phone), remember, your target size is <u><i><strong>3.000 um</strong></i></u> ----></li><li>Select your parameters, you have <strong>2</strong> experiments (chances) in each round, use them wisely! </li><li>Click <strong>Submit</strong> to see the results, reflect and improve your selection!</li><li>Repeat the process for <strong>5</strong> rounds to see if you can beat CCBO!</li></ul></p><p>Your data will not be stored, so feel free to play again, good luck!</p>"
354
 
355
  # Create Gradio interface
356
  with gr.Blocks() as demo:
 
 
 
357
  # Add state component to store user-specific results
358
  results_state = gr.State()
359
+ auc_state = gr.State(value=0)
360
  with gr.Row():
361
  # Input parameters column
362
  with gr.Column():
363
+ gr.Markdown("## Human vs CCBO Campaign - Optimize Electrospray")
364
+ gr.Markdown(description)
365
+
366
+ with gr.Row():
367
+ with gr.Column():
368
+ gr.Markdown("### Experiment 1")
369
+ conc1 = gr.Slider(minimum=0.05, maximum=5.0, value=1.2, step=0.001, label="Concentration (%w/v)")
370
+ flow_rate1 = gr.Slider(minimum=0.01, maximum=60.0, value=20.0, step=0.001, label="Flow Rate (mL/h)")
371
+ voltage1 = gr.Slider(minimum=10.0, maximum=18.0, value=15.0, step=0.001, label="Voltage (kV)")
372
+ solvent1 = gr.Dropdown(['DMAc', 'CHCl3'], value='DMAc', label='Solvent')
373
+ with gr.Column():
374
+ gr.Markdown("### Experiment 2")
375
+ conc2 = gr.Slider(minimum=0.05, maximum=5.0, value=2.8, step=0.001, label="Concentration (%w/v)")
376
+ flow_rate2 = gr.Slider(minimum=0.01, maximum=60.0, value=20.0, step=0.001, label="Flow Rate (mL/h)")
377
+ voltage2 = gr.Slider(minimum=10.0, maximum=18.0, value=15.0, step=0.001, label="Voltage (kV)")
378
+ solvent2 = gr.Dropdown(['DMAc', 'CHCl3'], value='CHCl3', label='Solvent')
379
+
380
+ # Group all buttons in a single row
381
+ with gr.Row():
382
+ submit_btn = gr.Button("Submit")
383
+ reset_btn = gr.Button("Reset Results")
384
+ download_btn = gr.Button("📥 Download Results", visible=False)
385
+
386
+ # Moved file output component below the buttons
387
+ result_file = gr.File(label="Download Results CSV", visible=False)
388
 
389
+ # Add notification component (initially hidden)
390
+ completion_message = gr.Markdown(visible=False)
 
 
 
391
 
392
  # Results display column
393
  with gr.Column():
394
  prior_experiments = gr.DataFrame(value=prior_experiments_display, label="Prior Experiments")
395
  results_df = gr.DataFrame(label="Your Results")
396
  perf_plot = gr.Plot(label="Performance Comparison")
397
+
 
 
 
 
 
398
  # Connect the submit button to the predict function
399
  submit_btn.click(
400
  fn=predict,
 
403
  conc1, flow_rate1, voltage1, solvent1,
404
  conc2, flow_rate2, voltage2, solvent2
405
  ],
406
+ outputs=[
407
+ results_state, prior_experiments, results_df, perf_plot,
408
+ download_btn, completion_message, auc_state, result_file
409
+ ]
410
  )
411
 
412
  # Connect the reset button to the reset_results function
413
  reset_btn.click(
414
  fn=reset_results,
415
  inputs=[results_state],
416
+ outputs=[
417
+ results_state, prior_experiments, results_df, perf_plot,
418
+ download_btn, completion_message, auc_state, result_file
419
+ ]
420
+ )
421
+
422
+ # Connect download button to file download
423
+ download_btn.click(
424
+ fn=prepare_results_for_download,
425
+ inputs=[results_state],
426
+ outputs=[result_file]
427
  )
428
 
429
  demo.launch()