Bing Yan commited on
Commit
e854c2f
·
1 Parent(s): c63c873

Restore full app.py with multi-image support and all prior fixes

Browse files

Restores from commit 58cb8ee which had:
- Multi-image upload for CV and TPD (one image per scan rate)
- Per-image axis detection via OCR
- Per-image current unit detection
- Robust tick fitting and outlier removal
- Median E0 estimation across images
- Current unit dropdown (auto/µA/mA/A/nA)

Then applies the recent UI cleanup:
- Remove summary markdown tables, use param_table figure instead
- Clean sequential layout: classification -> dropdown -> posteriors+table -> recon -> conc
- Horizontal advanced parameters layout

Made-with: Cursor

Files changed (1) hide show
  1. app.py +254 -177
app.py CHANGED
@@ -134,96 +134,143 @@ def analyze_cv(files, scan_rates_text, E0_V, T_K, A_cm2,
134
  return _run_ec_analysis(potentials, fluxes, sigmas_list, n_samples)
135
 
136
 
137
- def analyze_cv_image(image, scan_rate_text, E0_V, threshold, n_samples,
138
- x_min, x_max, y_min, y_max):
139
- """Analyze CV from an uploaded plot image.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
140
 
141
- Extracts the CV curve via image digitization, then nondimensionalizes
142
  and runs inference identically to the CSV path.
143
- Axis bounds are auto-detected via OCR if not provided.
144
  """
145
- if image is None:
146
- return _ec_error("Please upload an image.")
147
 
148
  try:
149
  from digitizer import digitize_plot, auto_detect_axis_bounds
 
150
  except ImportError:
151
- return _ec_error("OpenCV not available for image digitization.")
152
 
153
  scan_rate_text = scan_rate_text.strip() if scan_rate_text else ""
154
  if not scan_rate_text:
155
- return _ec_error("Please enter the scan rate (V/s).")
156
  try:
157
- v_Vs = float(scan_rate_text)
158
  except ValueError:
159
- return _ec_error("Invalid scan rate. Enter a number in V/s.")
160
 
161
- img_arr = np.array(image)
 
 
 
162
 
163
- # Determine axis bounds: user overrides take priority, else auto-detect
164
  has_user_bounds = all(
165
  v is not None and v != 0 for v in [x_min, x_max, y_min, y_max]
166
  )
167
- if has_user_bounds:
168
- bounds = {
169
- "x_min": float(x_min), "x_max": float(x_max),
170
- "y_min": float(y_min), "y_max": float(y_max),
171
- }
172
- bounds_source = "user"
173
- else:
174
- bounds = auto_detect_axis_bounds(img_arr)
175
- if bounds is None:
176
- return _ec_error(
177
- "Could not auto-detect axis bounds from the image. "
178
- "Please enter E min, E max, I min, I max under "
179
- "'Advanced: axis overrides'.")
180
- bounds_source = "auto"
181
 
182
- try:
183
- E_V, I_raw = digitize_plot(
184
- img_arr, bounds["x_min"], bounds["x_max"],
185
- bounds["y_min"], bounds["y_max"],
186
- threshold=int(threshold),
187
- )
188
- except Exception as e:
189
- return _ec_error(f"Digitization failed: {e}")
190
 
191
- # Convert current units: OCR reads axis labels so I_raw is in the
192
- # display unit (µA, mA, A). Assume A unless values are large.
193
- i_max = np.max(np.abs(I_raw))
194
- if i_max > 100:
195
- i_A = I_raw * 1e-6 # likely µA
196
- i_unit_guess = "µA"
197
- elif i_max > 0.1:
198
- i_A = I_raw * 1e-3 # likely mA
199
- i_unit_guess = "mA"
200
- else:
201
- i_A = I_raw
202
- i_unit_guess = "A"
 
 
 
 
 
 
 
203
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
204
  if E0_V is not None and E0_V != 0:
205
  e0 = float(E0_V)
206
  e0_source = "user"
207
  else:
208
- e0 = float(estimate_E0(E_V, i_A))
209
  e0_source = "auto"
210
 
211
- D = 1e-5
212
- T = 298.15
213
- A = 0.0707
214
- C_molcm3 = 1e-6
215
- n = 1
 
 
 
 
 
216
 
217
- theta, flux, sigma = nondimensionalize_cv(
218
- E_V, i_A, v_Vs, e0, T, A, C_molcm3, D, n
219
- )
 
 
220
 
221
- return _run_ec_analysis([theta], [flux], [sigma], n_samples)
222
 
223
 
224
  def _ec_error(msg=""):
225
  """Return empty outputs for EC error cases."""
226
- return None, None, gr.update(choices=[], value=None), None, None, None, None
227
 
228
 
229
  def _run_ec_analysis(potentials, fluxes, sigmas, n_samples):
@@ -251,7 +298,7 @@ def _run_ec_analysis(potentials, fluxes, sigmas, n_samples):
251
 
252
  return (
253
  fig_probs, state,
254
- gr.update(choices=mech_choices, value=mech_choices[0]),
255
  fig_post, fig_table, fig_recon, fig_conc,
256
  )
257
 
@@ -338,63 +385,77 @@ def analyze_tpd(files, heating_rates_text, n_samples):
338
  return _run_tpd_analysis(temperatures, rates, betas, n_samples)
339
 
340
 
341
- def analyze_tpd_image(image, heating_rates_text, threshold, n_samples,
342
  x_min, x_max, y_min, y_max):
343
- """Analyze TPD from an uploaded plot image.
344
 
345
- Axis bounds are auto-detected via OCR if not provided.
346
  """
347
- if image is None:
348
- return _tpd_error("Please upload an image.")
349
 
350
  try:
351
  from digitizer import digitize_plot, auto_detect_axis_bounds
 
352
  except ImportError:
353
- return _tpd_error("OpenCV not available for image digitization.")
354
 
355
  heating_rates_text = heating_rates_text.strip() if heating_rates_text else ""
356
  if not heating_rates_text:
357
  return _tpd_error(
358
- "Please enter the heating rate (β in K/s). "
359
  "This value is critical for correct inference.")
360
  try:
361
  betas = [float(s.strip()) for s in heating_rates_text.split(",")]
362
  except ValueError:
363
- return _tpd_error("Invalid heating rates.")
364
 
365
- img_arr = np.array(image)
 
 
 
366
 
367
  has_user_bounds = all(
368
  v is not None and v != 0 for v in [x_min, x_max, y_min, y_max]
369
  )
370
- if has_user_bounds:
371
- bounds = {
372
- "x_min": float(x_min), "x_max": float(x_max),
373
- "y_min": float(y_min), "y_max": float(y_max),
374
- }
375
- else:
376
- bounds = auto_detect_axis_bounds(img_arr)
377
- if bounds is None:
378
- return _tpd_error(
379
- "Could not auto-detect axis bounds from the image. "
380
- "Please enter T min, T max, Signal min, Signal max "
381
- "under 'Advanced: axis overrides'.")
382
 
383
- try:
384
- x_data, y_data = digitize_plot(
385
- img_arr, bounds["x_min"], bounds["x_max"],
386
- bounds["y_min"], bounds["y_max"],
387
- threshold=int(threshold),
388
- )
389
- except Exception as e:
390
- return _tpd_error(f"Digitization failed: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
391
 
392
- return _run_tpd_analysis([x_data], [y_data], betas[:1], n_samples)
393
 
394
 
395
  def _tpd_error(msg=""):
396
  """Return empty outputs for TPD error cases."""
397
- return None, None, gr.update(choices=[], value=None), None, None, None
398
 
399
 
400
  def _run_tpd_analysis(temperatures, rates, betas, n_samples):
@@ -420,7 +481,7 @@ def _run_tpd_analysis(temperatures, rates, betas, n_samples):
420
 
421
  return (
422
  fig_probs, state,
423
- gr.update(choices=mech_choices, value=mech_choices[0]),
424
  fig_post, fig_table, fig_recon,
425
  )
426
 
@@ -485,8 +546,7 @@ def download_results(result_text):
485
  def _build_ec_output_section(prefix):
486
  """Build shared output components for one EC input tab.
487
 
488
- Returns (probs_plot, state, mech_dropdown,
489
- posteriors_plot, param_table_plot, recon_plot, conc_plot).
490
  """
491
  gr.Markdown("---")
492
  probs = gr.Plot(label="Mechanism Classification")
@@ -507,8 +567,7 @@ def _build_ec_output_section(prefix):
507
  def _build_tpd_output_section(prefix):
508
  """Build shared output components for one TPD input tab.
509
 
510
- Returns (probs_plot, state, mech_dropdown,
511
- posteriors_plot, param_table_plot, recon_plot).
512
  """
513
  gr.Markdown("---")
514
  probs = gr.Plot(label="Mechanism Classification")
@@ -525,20 +584,35 @@ def _build_tpd_output_section(prefix):
525
  return probs, state, mech_dd, posteriors, param_table, recon
526
 
527
 
 
 
 
 
 
 
 
 
 
 
 
 
 
528
  def build_app():
529
  with gr.Blocks(
530
  title="ECFlow — Bayesian Inference for Electrochemistry & Catalysis",
531
  theme=gr.themes.Soft(
532
  primary_hue="blue",
533
- secondary_hue="purple",
 
534
  ),
 
535
  ) as app:
536
- gr.Markdown(
537
- "# ECFlow\n"
538
- "### Amortized Bayesian Inference for Electrochemistry & Catalysis\n"
539
- "Upload cyclic voltammetry (CV) or temperature-programmed desorption (TPD) data "
540
- "to identify the reaction mechanism and infer kinetic parameters with full uncertainty quantification.",
541
- elem_classes=["main-title"],
542
  )
543
 
544
  with gr.Tabs():
@@ -551,9 +625,10 @@ def build_app():
551
  with gr.Tab("CSV Data"):
552
  gr.Markdown(
553
  "Upload CSV files exported from your potentiostat. "
554
- "Expected columns: **potential** (V) and **current** (A/mA/µA). "
555
  "One file per scan rate. For best accuracy, upload multiple scan rates.\n\n"
556
- "If your CSV includes a **Time (s)** column, the scan rate is "
 
 
557
  "detected automatically. Otherwise, enter scan rates below."
558
  )
559
  cv_files = gr.File(
@@ -571,7 +646,7 @@ def build_app():
571
  cv_E0 = gr.Number(
572
  label="Formal potential E₀ (V)",
573
  value=None,
574
- info="Auto-estimated if empty",
575
  )
576
  cv_T = gr.Number(label="Temperature (K)", value=298.15)
577
  cv_A = gr.Number(label="Electrode area (cm²)", value=0.0707)
@@ -588,7 +663,7 @@ def build_app():
588
  100, 2000, value=500, step=100,
589
  label="Posterior samples",
590
  )
591
- cv_btn = gr.Button("Analyze", variant="primary")
592
 
593
  (cv_probs, cv_state,
594
  cv_mech_dd, cv_posteriors, cv_param_table,
@@ -616,14 +691,20 @@ def build_app():
616
  # --- Image mode ---
617
  with gr.Tab("From Image"):
618
  gr.Markdown(
619
- "Upload an image of a CV plot (potential in V on x-axis, "
620
- "current in A/mA/µA on y-axis). Axis bounds are "
621
- "**auto-detected** via OCR — override in Advanced if needed."
 
 
 
 
 
 
 
622
  )
623
- cv_img = gr.Image(label="Plot image", type="numpy")
624
  cv_img_scan_rate = gr.Textbox(
625
- label="Scan rate (V/s)",
626
- placeholder="e.g., 0.1",
627
  value="",
628
  )
629
  with gr.Accordion("Advanced parameters", open=False):
@@ -634,13 +715,20 @@ def build_app():
634
  info="Auto-estimated from peaks if empty",
635
  )
636
  cv_img_threshold = gr.Slider(
637
- 0, 255, value=128, step=1,
638
- label="Binarization threshold",
639
  )
640
- with gr.Accordion("Advanced: axis overrides", open=False):
 
 
 
 
 
 
641
  gr.Markdown(
642
- "Leave at 0 to auto-detect from the image. "
643
- "Override if OCR detection is inaccurate."
 
644
  )
645
  with gr.Row():
646
  cv_img_xmin = gr.Number(label="E min (V)", value=None)
@@ -652,7 +740,7 @@ def build_app():
652
  100, 2000, value=500, step=100,
653
  label="Posterior samples",
654
  )
655
- cv_img_btn = gr.Button("Analyze", variant="primary")
656
 
657
  (cv_img_probs, cv_img_state,
658
  cv_img_mech_dd, cv_img_posteriors, cv_img_param_table,
@@ -666,8 +754,9 @@ def build_app():
666
  cv_img_btn.click(
667
  analyze_cv_image,
668
  inputs=[
669
- cv_img, cv_img_scan_rate, cv_img_E0,
670
- cv_img_threshold, cv_img_nsamples,
 
671
  cv_img_xmin, cv_img_xmax,
672
  cv_img_ymin, cv_img_ymax,
673
  ],
@@ -687,11 +776,12 @@ def build_app():
687
  # --- CSV mode ---
688
  with gr.Tab("CSV Data"):
689
  gr.Markdown(
690
- "Upload CSV files with Temperature (K) and Signal columns. "
691
- "One file per heating rate. **You must provide the correct β for each file** — "
692
- "the model uses β to condition inference. "
693
- "If your CSV includes a Time (s) column, β is computed automatically. "
694
- "For best accuracy, upload multiple heating rates."
 
695
  )
696
  tpd_files = gr.File(
697
  label="CSV files (one per heating rate)",
@@ -699,8 +789,8 @@ def build_app():
699
  file_types=[".csv", ".txt"],
700
  )
701
  tpd_betas = gr.Textbox(
702
- label="Heating rates β (K/s), comma-separated (auto-detected if CSV has time column)",
703
- placeholder="e.g., 0.3, 2.6, 22.1 (leave empty for auto-detect)",
704
  value="",
705
  )
706
  with gr.Row():
@@ -708,7 +798,7 @@ def build_app():
708
  100, 2000, value=500, step=100,
709
  label="Posterior samples",
710
  )
711
- tpd_btn = gr.Button("Analyze", variant="primary")
712
 
713
  (tpd_probs, tpd_state,
714
  tpd_mech_dd, tpd_posteriors, tpd_param_table,
@@ -732,26 +822,33 @@ def build_app():
732
  # --- Image mode ---
733
  with gr.Tab("From Image"):
734
  gr.Markdown(
735
- "Upload an image of a TPD plot (temperature in K on "
736
- "x-axis, signal on y-axis). Axis bounds are "
737
- "**auto-detected** via OCR — override in Advanced if needed."
 
 
 
 
 
 
 
738
  )
739
- tpd_img = gr.Image(label="Plot image", type="numpy")
740
  tpd_img_betas = gr.Textbox(
741
- label="Heating rate β (K/s)",
742
- placeholder="e.g., 5.0",
743
  value="",
744
  )
745
  with gr.Accordion("Advanced parameters", open=False):
746
  with gr.Row():
747
  tpd_img_threshold = gr.Slider(
748
- 0, 255, value=128, step=1,
749
- label="Binarization threshold",
750
  )
751
- with gr.Accordion("Advanced: axis overrides", open=False):
752
  gr.Markdown(
753
- "Leave at 0 to auto-detect from the image. "
754
- "Override if OCR detection is inaccurate."
 
755
  )
756
  with gr.Row():
757
  tpd_img_xmin = gr.Number(label="T min (K)", value=None)
@@ -763,7 +860,7 @@ def build_app():
763
  100, 2000, value=500, step=100,
764
  label="Posterior samples",
765
  )
766
- tpd_img_btn = gr.Button("Analyze", variant="primary")
767
 
768
  (tpd_img_probs, tpd_img_state,
769
  tpd_img_mech_dd, tpd_img_posteriors, tpd_img_param_table,
@@ -776,7 +873,7 @@ def build_app():
776
  tpd_img_btn.click(
777
  analyze_tpd_image,
778
  inputs=[
779
- tpd_img, tpd_img_betas,
780
  tpd_img_threshold, tpd_img_nsamples,
781
  tpd_img_xmin, tpd_img_xmax,
782
  tpd_img_ymin, tpd_img_ymax,
@@ -794,50 +891,30 @@ def build_app():
794
  # =================================================================
795
  with gr.Tab("About"):
796
  gr.Markdown("""
797
- ## About ECFlow
798
-
799
- ECFlow performs **amortized Bayesian inference** for electrochemical and catalytic systems.
800
- Given experimental data, it simultaneously:
801
-
802
- 1. **Classifies the reaction mechanism** from a library of 6 mechanisms per domain
803
- 2. **Infers kinetic parameters** with full posterior uncertainty quantification
804
-
805
- ### Electrochemistry (CV) Mechanisms
806
 
807
- | Mechanism | Parameters | Description |
808
- |-----------|-----------|-------------|
809
- | Nernst | E₀, d_A, d_B | Reversible (Nernstian) electron transfer |
810
- | BV | K₀, α, d_B | Butler-Volmer kinetics |
811
- | MHC | K₀, λ, d_B | Marcus-Hush-Chidsey kinetics |
812
- | Ads | K₀, α, Γ_sat | Surface-confined (Laviron) kinetics |
813
- | EC | K₀, α, k_c, d_B | Electron transfer + chemical follow-up |
814
- | LH | K₀, α, K_A, K_B, d_B | Langmuir-Hinshelwood surface reaction |
815
 
816
- ### Catalysis (TPD) Mechanisms
 
 
 
 
817
 
818
- | Mechanism | Parameters | Description |
819
- |-----------|-----------|-------------|
820
- | FirstOrder | E_d, ν, θ₀ | First-order desorption |
821
- | SecondOrder | E_d, ν, θ₀ | Second-order (recombinative) desorption |
822
- | LH_Surface | E_a, ν, θ_A0, θ_B0 | Langmuir-Hinshelwood surface reaction |
823
- | MvK | E_a,red, E_a,reox, ν_red, θ_O0 | Mars-van Krevelen mechanism |
824
- | FirstOrderCovDep | E_d0, α_cov, ν, θ₀ | Coverage-dependent activation energy |
825
- | DiffLimited | E_d, ν, D₀, E_diff, θ₀ | Diffusion-limited desorption |
826
-
827
- ### How It Works
828
-
829
- The model uses **conditional normalizing flows** with a Set Transformer encoder
830
- to process multi-scan-rate/multi-heating-rate data. Training uses simulated data
831
- with coverage-aware calibration loss for well-calibrated uncertainty estimates.
832
-
833
- Inference takes **~5 ms per sample** on CPU, making it suitable for real-time analysis.
834
 
835
  ### Citation
836
 
837
- If you use ECFlow in your research, please cite:
838
  ```
839
- [Citation to be added upon publication]
 
 
840
  ```
 
 
841
  """)
842
 
843
  return app
 
134
  return _run_ec_analysis(potentials, fluxes, sigmas_list, n_samples)
135
 
136
 
137
+ _CURRENT_UNIT_SCALES = {
138
+ "µA": 1e-6,
139
+ "mA": 1e-3,
140
+ "A": 1.0,
141
+ "nA": 1e-9,
142
+ }
143
+
144
+
145
+ def _guess_current_unit(i_values):
146
+ """Guess the current unit from the magnitude of digitized values."""
147
+ i_max = np.max(np.abs(i_values))
148
+ if i_max > 1e3:
149
+ return "nA"
150
+ if i_max > 100:
151
+ return "µA"
152
+ if i_max > 0.1:
153
+ return "µA"
154
+ if i_max > 1e-4:
155
+ return "mA"
156
+ return "A"
157
+
158
+
159
+ def analyze_cv_image(files, scan_rate_text, E0_V, threshold, current_unit,
160
+ n_samples, x_min, x_max, y_min, y_max):
161
+ """Analyze CV from uploaded plot images (one per scan rate).
162
 
163
+ Extracts CV curves via image digitization, then nondimensionalizes
164
  and runs inference identically to the CSV path.
165
+ Axis bounds are auto-detected via OCR — override in Advanced if needed.
166
  """
167
+ if not files:
168
+ return _ec_error("Please upload at least one image.")
169
 
170
  try:
171
  from digitizer import digitize_plot, auto_detect_axis_bounds
172
+ from PIL import Image as PILImage
173
  except ImportError:
174
+ return _ec_error("Required libraries not available for image digitization.")
175
 
176
  scan_rate_text = scan_rate_text.strip() if scan_rate_text else ""
177
  if not scan_rate_text:
178
+ return _ec_error("Please enter the scan rate(s) (V/s), comma-separated.")
179
  try:
180
+ scan_rates = [float(s.strip()) for s in scan_rate_text.split(",")]
181
  except ValueError:
182
+ return _ec_error("Invalid scan rates. Enter comma-separated numbers in V/s.")
183
 
184
+ if len(files) != len(scan_rates):
185
+ return _ec_error(
186
+ f"Number of images ({len(files)}) must match number of "
187
+ f"scan rates ({len(scan_rates)}).")
188
 
 
189
  has_user_bounds = all(
190
  v is not None and v != 0 for v in [x_min, x_max, y_min, y_max]
191
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
192
 
193
+ D = 1e-5
194
+ T = 298.15
195
+ A = 0.0707
196
+ C_molcm3 = 1e-6
197
+ n = 1
 
 
 
198
 
199
+ # First pass: digitize all images and estimate E0 per image
200
+ image_data = []
201
+ e0_estimates = []
202
+ for idx, f in enumerate(files):
203
+ img_arr = np.array(PILImage.open(f.name).convert("RGB"))
204
+ v_Vs = scan_rates[idx]
205
+
206
+ if has_user_bounds:
207
+ bounds = {
208
+ "x_min": float(x_min), "x_max": float(x_max),
209
+ "y_min": float(y_min), "y_max": float(y_max),
210
+ }
211
+ else:
212
+ bounds = auto_detect_axis_bounds(img_arr)
213
+ if bounds is None:
214
+ return _ec_error(
215
+ f"Could not auto-detect axis bounds for image {idx + 1}. "
216
+ "Please enter E min, E max, I min, I max under "
217
+ "'Axis overrides'.")
218
 
219
+ try:
220
+ E_V, I_raw = digitize_plot(
221
+ img_arr, bounds["x_min"], bounds["x_max"],
222
+ bounds["y_min"], bounds["y_max"],
223
+ threshold=int(threshold),
224
+ x_ticks=bounds.get("x_ticks"),
225
+ y_ticks=bounds.get("y_ticks"),
226
+ )
227
+ except Exception as exc:
228
+ return _ec_error(f"Digitization failed for image {idx + 1}: {exc}")
229
+
230
+ if current_unit and current_unit != "auto":
231
+ i_unit = current_unit
232
+ elif "y_unit" in bounds:
233
+ i_unit = bounds["y_unit"]
234
+ else:
235
+ i_unit = _guess_current_unit(I_raw)
236
+
237
+ i_scale = _CURRENT_UNIT_SCALES.get(i_unit, 1e-6)
238
+ i_A = I_raw * i_scale
239
+
240
+ e0_estimates.append(float(estimate_E0(E_V, i_A)))
241
+ image_data.append((E_V, i_A, v_Vs, i_unit, bounds))
242
+
243
+ # Determine E0: user-provided or median of per-image estimates
244
  if E0_V is not None and E0_V != 0:
245
  e0 = float(E0_V)
246
  e0_source = "user"
247
  else:
248
+ e0 = float(np.median(e0_estimates))
249
  e0_source = "auto"
250
 
251
+ # Second pass: nondimensionalize with shared E0
252
+ potentials, fluxes, sigmas_list = [], [], []
253
+ preproc_parts = []
254
+ for E_V, i_A, v_Vs, i_unit, bounds in image_data:
255
+ theta, flux, sigma = nondimensionalize_cv(
256
+ E_V, i_A, v_Vs, e0, T, A, C_molcm3, D, n
257
+ )
258
+ potentials.append(theta)
259
+ fluxes.append(flux)
260
+ sigmas_list.append(sigma)
261
 
262
+ preproc_parts.append(
263
+ f"{v_Vs*1000:.1f} mV/s (σ={sigma:.2f}, "
264
+ f"E=[{bounds['x_min']:.3f}, {bounds['x_max']:.3f}] V, "
265
+ f"I=[{bounds['y_min']:.2f}, {bounds['y_max']:.2f}] {i_unit})"
266
+ )
267
 
268
+ return _run_ec_analysis(potentials, fluxes, sigmas_list, n_samples)
269
 
270
 
271
  def _ec_error(msg=""):
272
  """Return empty outputs for EC error cases."""
273
+ return None, None, gr.Dropdown(choices=[], value=None), None, None, None, None
274
 
275
 
276
  def _run_ec_analysis(potentials, fluxes, sigmas, n_samples):
 
298
 
299
  return (
300
  fig_probs, state,
301
+ gr.Dropdown(choices=mech_choices, value=mech_choices[0]),
302
  fig_post, fig_table, fig_recon, fig_conc,
303
  )
304
 
 
385
  return _run_tpd_analysis(temperatures, rates, betas, n_samples)
386
 
387
 
388
+ def analyze_tpd_image(files, heating_rates_text, threshold, n_samples,
389
  x_min, x_max, y_min, y_max):
390
+ """Analyze TPD from uploaded plot images (one per heating rate).
391
 
392
+ Axis bounds are auto-detected via OCR — override in Advanced if needed.
393
  """
394
+ if not files:
395
+ return _tpd_error("Please upload at least one image.")
396
 
397
  try:
398
  from digitizer import digitize_plot, auto_detect_axis_bounds
399
+ from PIL import Image as PILImage
400
  except ImportError:
401
+ return _tpd_error("Required libraries not available for image digitization.")
402
 
403
  heating_rates_text = heating_rates_text.strip() if heating_rates_text else ""
404
  if not heating_rates_text:
405
  return _tpd_error(
406
+ "Please enter the heating rate(s) (β in K/s), comma-separated. "
407
  "This value is critical for correct inference.")
408
  try:
409
  betas = [float(s.strip()) for s in heating_rates_text.split(",")]
410
  except ValueError:
411
+ return _tpd_error("Invalid heating rates. Enter comma-separated numbers in K/s.")
412
 
413
+ if len(files) != len(betas):
414
+ return _tpd_error(
415
+ f"Number of images ({len(files)}) must match number of "
416
+ f"heating rates ({len(betas)}).")
417
 
418
  has_user_bounds = all(
419
  v is not None and v != 0 for v in [x_min, x_max, y_min, y_max]
420
  )
 
 
 
 
 
 
 
 
 
 
 
 
421
 
422
+ temperatures, rates = [], []
423
+ for idx, f in enumerate(files):
424
+ img_arr = np.array(PILImage.open(f.name).convert("RGB"))
425
+
426
+ if has_user_bounds:
427
+ bounds = {
428
+ "x_min": float(x_min), "x_max": float(x_max),
429
+ "y_min": float(y_min), "y_max": float(y_max),
430
+ }
431
+ else:
432
+ bounds = auto_detect_axis_bounds(img_arr)
433
+ if bounds is None:
434
+ return _tpd_error(
435
+ f"Could not auto-detect axis bounds for image {idx + 1}. "
436
+ "Please enter T min, T max, Signal min, Signal max "
437
+ "under 'Axis overrides'.")
438
+
439
+ try:
440
+ x_data, y_data = digitize_plot(
441
+ img_arr, bounds["x_min"], bounds["x_max"],
442
+ bounds["y_min"], bounds["y_max"],
443
+ threshold=int(threshold),
444
+ x_ticks=bounds.get("x_ticks"),
445
+ y_ticks=bounds.get("y_ticks"),
446
+ )
447
+ except Exception as exc:
448
+ return _tpd_error(f"Digitization failed for image {idx + 1}: {exc}")
449
+
450
+ temperatures.append(x_data)
451
+ rates.append(y_data)
452
 
453
+ return _run_tpd_analysis(temperatures, rates, betas, n_samples)
454
 
455
 
456
  def _tpd_error(msg=""):
457
  """Return empty outputs for TPD error cases."""
458
+ return None, None, gr.Dropdown(choices=[], value=None), None, None, None
459
 
460
 
461
  def _run_tpd_analysis(temperatures, rates, betas, n_samples):
 
481
 
482
  return (
483
  fig_probs, state,
484
+ gr.Dropdown(choices=mech_choices, value=mech_choices[0]),
485
  fig_post, fig_table, fig_recon,
486
  )
487
 
 
546
  def _build_ec_output_section(prefix):
547
  """Build shared output components for one EC input tab.
548
 
549
+ Returns (probs, state, mech_dd, posteriors, param_table, recon, conc).
 
550
  """
551
  gr.Markdown("---")
552
  probs = gr.Plot(label="Mechanism Classification")
 
567
  def _build_tpd_output_section(prefix):
568
  """Build shared output components for one TPD input tab.
569
 
570
+ Returns (probs, state, mech_dd, posteriors, param_table, recon).
 
571
  """
572
  gr.Markdown("---")
573
  probs = gr.Plot(label="Mechanism Classification")
 
584
  return probs, state, mech_dd, posteriors, param_table, recon
585
 
586
 
587
+ CUSTOM_CSS = """
588
+ .main-header { text-align: center; padding: 24px 16px 8px 16px; }
589
+ .main-header h1 { font-size: 2.2em; margin-bottom: 2px; letter-spacing: -0.5px; }
590
+ .main-header p { color: #6B7280; font-size: 1.05em; max-width: 720px; margin: 0 auto; line-height: 1.5; }
591
+ .section-heading { margin-top: 24px !important; margin-bottom: 4px !important; }
592
+ .preproc-card { background: #F0F9FF; border: 1px solid #BAE6FD; border-radius: 8px; padding: 10px 16px; margin-top: 12px; font-size: 0.93em; color: #0C4A6E; }
593
+ .summary-card { border: 1px solid #E5E7EB; border-radius: 10px; padding: 16px 20px; background: #FAFBFC; }
594
+ .summary-card table { width: 100%; font-size: 0.92em; }
595
+ .summary-card td, .summary-card th { padding: 4px 8px; }
596
+ footer { display: none !important; }
597
+ """
598
+
599
+
600
  def build_app():
601
  with gr.Blocks(
602
  title="ECFlow — Bayesian Inference for Electrochemistry & Catalysis",
603
  theme=gr.themes.Soft(
604
  primary_hue="blue",
605
+ secondary_hue="slate",
606
+ font=gr.themes.GoogleFont("Inter"),
607
  ),
608
+ css=CUSTOM_CSS,
609
  ) as app:
610
+ gr.HTML(
611
+ "<div class='main-header'>"
612
+ "<h1>⚡ ECFlow</h1>"
613
+ "<p>Upload cyclic voltammetry or TPD data to <strong>identify the reaction mechanism</strong> "
614
+ "and <strong>infer kinetic parameters</strong> with full Bayesian uncertainty — in milliseconds.</p>"
615
+ "</div>"
616
  )
617
 
618
  with gr.Tabs():
 
625
  with gr.Tab("CSV Data"):
626
  gr.Markdown(
627
  "Upload CSV files exported from your potentiostat. "
 
628
  "One file per scan rate. For best accuracy, upload multiple scan rates.\n\n"
629
+ "**Expected columns:** `Potential (V)`, `Current (A/mA/µA)`, and optionally `Time (s)`.\n\n"
630
+ "Example header: `Time (s), Potential (V), Current (A)`\n\n"
631
+ "If a **Time (s)** column is present, the scan rate is "
632
  "detected automatically. Otherwise, enter scan rates below."
633
  )
634
  cv_files = gr.File(
 
646
  cv_E0 = gr.Number(
647
  label="Formal potential E₀ (V)",
648
  value=None,
649
+ info="Auto-estimated from peak positions if empty",
650
  )
651
  cv_T = gr.Number(label="Temperature (K)", value=298.15)
652
  cv_A = gr.Number(label="Electrode area (cm²)", value=0.0707)
 
663
  100, 2000, value=500, step=100,
664
  label="Posterior samples",
665
  )
666
+ cv_btn = gr.Button("Analyze", variant="primary", scale=2)
667
 
668
  (cv_probs, cv_state,
669
  cv_mech_dd, cv_posteriors, cv_param_table,
 
691
  # --- Image mode ---
692
  with gr.Tab("From Image"):
693
  gr.Markdown(
694
+ "Upload plot images of CVs (potential in V on x-axis, "
695
+ "current in A/mA/µA on y-axis). **One image per scan rate.** "
696
+ "For best accuracy, upload multiple scan rates.\n\n"
697
+ "Axis bounds are **auto-detected** via OCR — "
698
+ "override in Advanced if needed."
699
+ )
700
+ cv_img_files = gr.File(
701
+ label="Plot images (one per scan rate)",
702
+ file_count="multiple",
703
+ file_types=["image"],
704
  )
 
705
  cv_img_scan_rate = gr.Textbox(
706
+ label="Scan rates (V/s), comma-separated",
707
+ placeholder="e.g., 0.01, 0.1, 1.0",
708
  value="",
709
  )
710
  with gr.Accordion("Advanced parameters", open=False):
 
715
  info="Auto-estimated from peaks if empty",
716
  )
717
  cv_img_threshold = gr.Slider(
718
+ 0, 255, value=0, step=1,
719
+ label="Binarization threshold (0 = auto)",
720
  )
721
+ cv_img_current_unit = gr.Dropdown(
722
+ label="Current unit on y-axis",
723
+ choices=["auto", "µA", "mA", "A", "nA"],
724
+ value="auto",
725
+ info="Select the unit shown on the y-axis of your plot",
726
+ )
727
+ with gr.Accordion("Axis overrides", open=False):
728
  gr.Markdown(
729
+ "Leave at 0 to auto-detect from each image. "
730
+ "Override if OCR detection is inaccurate. "
731
+ "Overrides apply to **all** images."
732
  )
733
  with gr.Row():
734
  cv_img_xmin = gr.Number(label="E min (V)", value=None)
 
740
  100, 2000, value=500, step=100,
741
  label="Posterior samples",
742
  )
743
+ cv_img_btn = gr.Button("Analyze", variant="primary", scale=2)
744
 
745
  (cv_img_probs, cv_img_state,
746
  cv_img_mech_dd, cv_img_posteriors, cv_img_param_table,
 
754
  cv_img_btn.click(
755
  analyze_cv_image,
756
  inputs=[
757
+ cv_img_files, cv_img_scan_rate, cv_img_E0,
758
+ cv_img_threshold, cv_img_current_unit,
759
+ cv_img_nsamples,
760
  cv_img_xmin, cv_img_xmax,
761
  cv_img_ymin, cv_img_ymax,
762
  ],
 
776
  # --- CSV mode ---
777
  with gr.Tab("CSV Data"):
778
  gr.Markdown(
779
+ "Upload CSV files with **Temperature (K)** and **Signal** columns. "
780
+ "Optionally include a **Time (s)** column for automatic β detection. "
781
+ "One file per heating rate. For best accuracy, upload multiple heating rates.\n\n"
782
+ "Example header: `Temperature (K), Signal`\n\n"
783
+ "**You must provide the correct β for each file** — "
784
+ "the model uses β to condition inference."
785
  )
786
  tpd_files = gr.File(
787
  label="CSV files (one per heating rate)",
 
789
  file_types=[".csv", ".txt"],
790
  )
791
  tpd_betas = gr.Textbox(
792
+ label="Heating rates β (K/s), comma-separated",
793
+ placeholder="e.g., 0.3, 2.6, 22.1 (leave empty if CSV has time column)",
794
  value="",
795
  )
796
  with gr.Row():
 
798
  100, 2000, value=500, step=100,
799
  label="Posterior samples",
800
  )
801
+ tpd_btn = gr.Button("Analyze", variant="primary", scale=2)
802
 
803
  (tpd_probs, tpd_state,
804
  tpd_mech_dd, tpd_posteriors, tpd_param_table,
 
822
  # --- Image mode ---
823
  with gr.Tab("From Image"):
824
  gr.Markdown(
825
+ "Upload plot images of TPD curves (temperature in K on "
826
+ "x-axis, signal on y-axis). **One image per heating rate.** "
827
+ "For best accuracy, upload multiple heating rates.\n\n"
828
+ "Axis bounds are **auto-detected** via OCR — "
829
+ "override in Advanced if needed."
830
+ )
831
+ tpd_img_files = gr.File(
832
+ label="Plot images (one per heating rate)",
833
+ file_count="multiple",
834
+ file_types=["image"],
835
  )
 
836
  tpd_img_betas = gr.Textbox(
837
+ label="Heating rates β (K/s), comma-separated",
838
+ placeholder="e.g., 0.3, 2.6, 22.1",
839
  value="",
840
  )
841
  with gr.Accordion("Advanced parameters", open=False):
842
  with gr.Row():
843
  tpd_img_threshold = gr.Slider(
844
+ 0, 255, value=0, step=1,
845
+ label="Binarization threshold (0 = auto)",
846
  )
847
+ with gr.Accordion("Axis overrides", open=False):
848
  gr.Markdown(
849
+ "Leave at 0 to auto-detect from each image. "
850
+ "Override if OCR detection is inaccurate. "
851
+ "Overrides apply to **all** images."
852
  )
853
  with gr.Row():
854
  tpd_img_xmin = gr.Number(label="T min (K)", value=None)
 
860
  100, 2000, value=500, step=100,
861
  label="Posterior samples",
862
  )
863
+ tpd_img_btn = gr.Button("Analyze", variant="primary", scale=2)
864
 
865
  (tpd_img_probs, tpd_img_state,
866
  tpd_img_mech_dd, tpd_img_posteriors, tpd_img_param_table,
 
873
  tpd_img_btn.click(
874
  analyze_tpd_image,
875
  inputs=[
876
+ tpd_img_files, tpd_img_betas,
877
  tpd_img_threshold, tpd_img_nsamples,
878
  tpd_img_xmin, tpd_img_xmax,
879
  tpd_img_ymin, tpd_img_ymax,
 
891
  # =================================================================
892
  with gr.Tab("About"):
893
  gr.Markdown("""
894
+ ## How It Works
 
 
 
 
 
 
 
 
895
 
896
+ ECFlow uses **conditional normalizing flows** with a **Set Transformer** encoder to perform amortized Bayesian inference.
897
+ Given one or more experimental curves, it simultaneously classifies the reaction mechanism and produces
898
+ full posterior distributions over kinetic parameters — in a single forward pass.
 
 
 
 
 
899
 
900
+ | | Electrochemistry (CV) | Catalysis (TPD) |
901
+ |---|---|---|
902
+ | **Mechanisms** | Nernst, Butler–Volmer, Marcus–Hush–Chidsey, Adsorption, EC, Langmuir–Hinshelwood | First-order, Second-order, LH Surface, Mars–van Krevelen, Coverage-dependent, Diffusion-limited |
903
+ | **Inference** | ~50 ms on CPU | ~50 ms on CPU |
904
+ | **Calibration** | 89–94 % coverage at 90 % nominal | Conformal coverage verified |
905
 
906
+ Training data is generated from physics-based simulators (Crank–Nicolson for CV, ODE integrators for TPD).
907
+ Posteriors are calibrated via a coverage-aware loss with per-parameter inverse-spread weighting.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
908
 
909
  ### Citation
910
 
 
911
  ```
912
+ Yan, B. (2026). ECFlow: Amortized Bayesian Inference for Mechanism Identification
913
+ and Parameter Estimation in Electrochemistry and Catalysis via Conditional
914
+ Normalizing Flows. [Preprint]
915
  ```
916
+
917
+ Built at MIT. Code and paper at [github.com/bingyan/ECFlow](https://github.com/bingyan/ECFlow).
918
  """)
919
 
920
  return app