-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1799 lines (1499 loc) · 63 KB
/
Copy pathapp.py
File metadata and controls
1799 lines (1499 loc) · 63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Streamlit App for Collecting Chemist Feedback on Kinetic Fitting Results
OPTIMIZED VERSION with:
1. Cached ODE simulations to avoid redundant computation
2. Data downsampling for faster rendering
3. Aggregated traces instead of per-experiment traces
4. Lazy loading of visualizations
5. WebGL renderer for large datasets
Storage layout on GitHub:
feedback/{username_slug}/{run_type_slug}.json
"""
import streamlit as st
import regex as re
import glob
import json
import base64
import warnings
import hashlib
from datetime import datetime
from pathlib import Path
from typing import Optional, Tuple, List, Dict, Any
from dataclasses import dataclass, field
from functools import lru_cache
import pandas as pd
import numpy as np
import requests
import plotly.graph_objects as go
from plotly.subplots import make_subplots
from scipy.integrate import odeint
import h5py
# =============================================================================
# Configuration
# =============================================================================
RUN_TEMPLATES = {
"No Feedback (Claude Sonnet 4.5)": "kinetic_fitting_no_fb_claudesonnet45_*",
"No Feedback (GPT-4o)": "kinetic_fitting_no_fb_gpt4o_feedback_*",
"Text Feedback (Claude Sonnet 4.5)": "kinetic_fitting_with_fb_claudesonnet45_*",
"Text+Vision Feedback (Claude Sonnet 4.5)": "kinetic_fitting_with_visionfb_claudesonnet45_*",
"Text+Vision+Chemistry Feedback (Claude Sonnet 4.5)": "kinetic_fitting_with_visionfb_claudesonnet45_with_opus_fb_*",
"Text+Chemistry Feedback every round (Claude Sonnet 4.5)": "kinetic_fitting_tasks_with_visionfb_and_chemistryopus_no_text_*",
}
EXCLUDE_PATTERNS = {
"kinetic_fitting_with_visionfb_claudesonnet45_*": [
"kinetic_fitting_with_visionfb_claudesonnet45_with_opus_fb_*"
],
}
BASE_DIR = Path("round1")
VIZ_DIR = Path("round_1_viz")
DATA_PATH = "data/experimental_data.h5"
# GitHub configuration
GITHUB_API = "https://api.github.com"
FEEDBACK_ROOT = "feedback"
# Performance settings
MAX_POINTS_PER_TRACE = 200 # Downsample to this many points
USE_WEBGL = True # Use WebGL for scatter plots
# Color scheme for species
SPECIES_COLORS = {
"O2": "#2ecc71",
"H2O2": "#3498db",
"Ru_Dimer": "#27ae60",
"Ru2_dim": "#27ae60",
"Inactive": "#9b59b6",
"Ru_inactive": "#9b59b6",
"Ru2_inactive": "#9b59b6",
"RuII": "#e67e22",
"RuIII": "#e74c3c",
"RuII_ex": "#f1c40f",
"S2O8": "#8e44ad",
"SO4": "#d35400",
}
# Parameter variation colors (Viridis-like)
PARAM_COLORS = [
"#440154", "#482878", "#3e4989", "#31688e", "#26838f",
"#1f9e89", "#35b779", "#6ece58", "#b5de2b", "#fde725"
]
# =============================================================================
# Performance Utilities
# =============================================================================
def downsample_data(x: np.ndarray, y: np.ndarray, max_points: int = MAX_POINTS_PER_TRACE) -> Tuple[np.ndarray, np.ndarray]:
"""Downsample data to max_points using LTTB-like algorithm for visual fidelity."""
if len(x) <= max_points:
return x, y
# Use simple uniform sampling with preserved endpoints
indices = np.linspace(0, len(x) - 1, max_points, dtype=int)
return x[indices], y[indices]
def hash_params(params: dict, conditions: dict) -> str:
"""Create a hash key for caching simulations."""
key_str = json.dumps({"p": params, "c": conditions}, sort_keys=True, default=str)
return hashlib.md5(key_str.encode()).hexdigest()[:16]
# =============================================================================
# Reaction Parsing
# =============================================================================
@dataclass
class Reaction:
"""Represents a chemical reaction in the kinetic network."""
equation: str
type: str
reactants: List[str]
products: List[str]
stoichiometry: Dict[str, float]
k_range: Optional[Tuple[float, float]] = None
quantum_yield: Optional[Tuple[float, float]] = None
fitted_k: Optional[float] = None
fitted_quantum_yield: Optional[float] = None
@classmethod
def from_dict(cls, rxn_dict: dict) -> "Reaction":
equation = rxn_dict["equation"]
if "<->" in equation:
equation = equation.replace("<->", "->")
if "->" not in equation:
raise ValueError(f"Invalid equation format: '{equation}'")
left, right = equation.split("->")
reactants = [s.strip() for s in left.split("+") if s.strip()]
products = [s.strip() for s in right.split("+") if s.strip()]
ignored = {"hv", "H2O", "OH", "products", "H", "H+", ""}
stoich = {}
def parse_species_with_coeff(species_str):
species_str = species_str.strip()
if not species_str:
return 1, ""
parts = species_str.split(" ", 1)
if len(parts) == 2 and parts[0].isdigit():
return int(parts[0]), parts[1]
return 1, species_str
for r in reactants:
if r and r not in ignored:
coeff, species = parse_species_with_coeff(r)
if species and species not in ignored:
stoich[species] = stoich.get(species, 0) - coeff
for p in products:
if p and p not in ignored:
coeff, species = parse_species_with_coeff(p)
if species and species not in ignored:
stoich[species] = stoich.get(species, 0) + coeff
return cls(
equation=rxn_dict["equation"],
type=rxn_dict["type"],
reactants=reactants,
products=products,
stoichiometry=stoich,
k_range=rxn_dict.get("k_range"),
quantum_yield=rxn_dict.get("quantum_yield"),
fitted_k=rxn_dict.get("fitted_k"),
fitted_quantum_yield=rxn_dict.get("fitted_quantum_yield"),
)
# =============================================================================
# ODE System (Cached)
# =============================================================================
@st.cache_data(ttl=3600, show_spinner=False)
def create_ode_system_cached(network_json: str):
"""Create ODE system from network JSON (cached)."""
network = json.loads(network_json)
reactions = [Reaction.from_dict(r) for r in network.get("reactions", [])]
all_species = set()
for rxn in reactions:
all_species.update(rxn.stoichiometry.keys())
all_species = {s for s in all_species if s and s.strip()}
species_list = sorted(all_species)
species_idx = {sp: i for i, sp in enumerate(species_list)}
return species_list, species_idx, network_json
def create_ode_func(reactions: List[Reaction], species_idx: Dict[str, int]):
"""Create the ODE function for integration."""
PATHLENGTH = 2.25
EPSILON_RU_II = 8500.0
EPSILON_RU_III = 540.0
AVOGADRO_NUMBER = 6.022e23
VOLUME_L = PATHLENGTH * 1e-3
def ode_func(y: np.ndarray, t: float, params: dict, conditions: dict) -> np.ndarray:
dydt = np.zeros_like(y)
c_ru_ii_M = y[species_idx["RuII"]] * 1e-6 if "RuII" in species_idx else 0
c_ru_iii_M = y[species_idx["RuIII"]] * 1e-6 if "RuIII" in species_idx else 0
absorbance_tot = (
(c_ru_ii_M * EPSILON_RU_II) + (c_ru_iii_M * EPSILON_RU_III)
) * PATHLENGTH
if absorbance_tot < 1e-9:
absorptance_factor = 0
fraction_ru_ii = 0
fraction_ru_iii = 0
else:
absorptance_factor = 1 - 10 ** (-absorbance_tot)
fraction_ru_ii = (c_ru_ii_M * EPSILON_RU_II * PATHLENGTH) / absorbance_tot
fraction_ru_iii = (c_ru_iii_M * EPSILON_RU_III * PATHLENGTH) / absorbance_tot
if conditions.get("photon_flux") is not None:
photon_flux_photons_s = conditions["photon_flux"]
photon_flux_mol_s = photon_flux_photons_s / AVOGADRO_NUMBER
incident_flux_M_s = photon_flux_mol_s / VOLUME_L
incident_flux = incident_flux_M_s * 1e6
else:
irradiance_W_m2 = conditions.get("irradiance", 1000)
irradiance_W_cm2 = irradiance_W_m2 * 1e-4
E_photon_J = 4.41e-19
photon_flux_approx = irradiance_W_cm2 / E_photon_J
photon_flux_vol_photons_s_cm3 = photon_flux_approx / PATHLENGTH
photon_flux_vol_mol_s_cm3 = photon_flux_vol_photons_s_cm3 / AVOGADRO_NUMBER
photon_flux_vol_M_s = photon_flux_vol_mol_s_cm3 * 1000
incident_flux = photon_flux_vol_M_s * 1e6
for i, rxn in enumerate(reactions):
rate = 0.0
if rxn.type == "light":
is_ru_ii_absorber = "RuII" in rxn.reactants
is_ru_iii_absorber = "RuIII" in rxn.reactants
absorbed_flux = 0.0
if is_ru_ii_absorber:
absorbed_flux = incident_flux * absorptance_factor * fraction_ru_ii
elif is_ru_iii_absorber:
absorbed_flux = incident_flux * absorptance_factor * fraction_ru_iii
qy = params.get(f"qy_{i}", rxn.quantum_yield[0] if rxn.quantum_yield else 0.1)
rate = absorbed_flux * qy
else:
k = params.get(f"k_{i}", 1.0)
rate = k
for reactant in rxn.reactants:
if reactant in species_idx:
if rxn.equation.startswith(f"2 {reactant}"):
rate *= y[species_idx[reactant]] ** 2
else:
rate *= y[species_idx[reactant]]
elif reactant in ["H2O", "H+"]:
rate *= 1.0
for species, coeff in rxn.stoichiometry.items():
if species in species_idx:
dydt[species_idx[species]] += coeff * rate
return dydt
return ode_func
@st.cache_data(ttl=3600, show_spinner=False)
def simulate_species_evolution_cached(
network_json: str,
params_json: str,
conditions_json: str,
time_min: float,
time_max: float,
n_points: int = 200,
) -> Tuple[List[List[float]], List[str], Dict[str, int]]:
"""Cached simulation of species evolution."""
network = json.loads(network_json)
params = json.loads(params_json)
conditions = json.loads(conditions_json)
reactions = [Reaction.from_dict(r) for r in network.get("reactions", [])]
all_species = set()
for rxn in reactions:
all_species.update(rxn.stoichiometry.keys())
all_species = {s for s in all_species if s and s.strip()}
species_list = sorted(all_species)
species_idx = {sp: i for i, sp in enumerate(species_list)}
ode_func = create_ode_func(reactions, species_idx)
time_points = np.linspace(time_min, time_max, n_points)
y0 = np.zeros(len(species_list))
if "RuII" in species_idx:
y0[species_idx["RuII"]] = conditions.get("c_Ru", 10)
if "S2O8" in species_idx:
y0[species_idx["S2O8"]] = conditions.get("c_S2O8", 6000)
with warnings.catch_warnings():
warnings.simplefilter("ignore")
y_solution = odeint(
ode_func,
y0,
time_points,
args=(params, conditions),
rtol=1e-6,
atol=1e-8,
)
return y_solution.tolist(), species_list, species_idx, time_points.tolist()
def build_params_from_network(network: dict) -> dict:
"""Build parameter dictionary from fitted values in the network."""
params = {}
for i, rxn in enumerate(network.get("reactions", [])):
if rxn.get("type") == "light":
if rxn.get("fitted_quantum_yield") is not None:
params[f"qy_{i}"] = rxn["fitted_quantum_yield"]
else:
if rxn.get("fitted_k") is not None:
params[f"k_{i}"] = rxn["fitted_k"]
return params
# =============================================================================
# Data Loading (Cached)
# =============================================================================
@dataclass
class ExperimentMetadata:
experiment_name: str
power_output: float
ru_concentration: float
oxidant_concentration: float
buffer_concentration: float
pH: float
buffer_used: int
photon_flux: Optional[float] = None
annotations: str = ""
color: str = "#ce1480"
@dataclass
class TimeSeriesData:
time_reaction: np.ndarray
data_reaction: np.ndarray
y_fit: np.ndarray
baseline_y: np.ndarray
lbc_fit_y: np.ndarray
full_x_values: np.ndarray
full_y_corrected: np.ndarray
x_diff: np.ndarray
y_diff: np.ndarray
y_diff_smoothed: np.ndarray
y_diff_fit: np.ndarray
time_full: np.ndarray
data_full: np.ndarray
@dataclass
class AnalysisMetadata:
p: np.ndarray
max_rate: float
max_rate_ydiff: float
initial_state: np.ndarray
matrix: str
rate_constant: float
rxn_start: int
rxn_end: int
residual: np.ndarray
idx_for_fitting: int
@dataclass
class DataSets:
data_corrected: np.ndarray
@dataclass
class ExperimentalData:
time_series_data: TimeSeriesData
experiment_metadata: ExperimentMetadata
analysis_metadata: AnalysisMetadata
datasets: DataSets
@dataclass
class ExperimentalDataset:
experiments: Dict[str, "ExperimentalData"] = field(default_factory=dict)
overview_df: pd.DataFrame = field(default_factory=lambda: pd.DataFrame())
@classmethod
def load_from_hdf5(cls, filename: str):
dataset = cls()
try:
dataset.overview_df = pd.read_hdf(filename, key="overview_df")
except (KeyError, ValueError):
dataset.overview_df = pd.DataFrame()
with h5py.File(filename, "r") as f:
for exp_name in f.keys():
if exp_name == "overview_df":
continue
try:
time_series_dict = dict(f[f"{exp_name}/time_series_data"].attrs)
time_series_data = TimeSeriesData(**time_series_dict)
exp_metadata_dict = dict(f[f"{exp_name}/experiment_metadata"].attrs)
valid_fields = ExperimentMetadata.__annotations__.keys()
filtered_metadata = {
k: v for k, v in exp_metadata_dict.items() if k in valid_fields
}
experiment_metadata = ExperimentMetadata(**filtered_metadata)
analysis_metadata_dict = dict(f[f"{exp_name}/analysis_metadata"].attrs)
analysis_metadata = AnalysisMetadata(**analysis_metadata_dict)
datasets_dict = dict(f[f"{exp_name}/datasets"].attrs)
datasets = DataSets(**datasets_dict)
experimental_data = ExperimentalData(
time_series_data,
experiment_metadata,
analysis_metadata,
datasets,
)
dataset.experiments[exp_name] = experimental_data
except Exception:
continue
return dataset
@st.cache_data(ttl=3600, show_spinner=False)
def load_experimental_data_cached(data_path: str) -> Dict[str, Any]:
"""Load and cache experimental data from HDF5 file."""
try:
dataset = ExperimentalDataset.load_from_hdf5(data_path)
data = {}
for exp_name, exp_data in dataset.experiments.items():
time = exp_data.time_series_data.time_reaction
oxygen = exp_data.time_series_data.data_reaction
if not dataset.overview_df.empty:
overview_row = dataset.overview_df[
dataset.overview_df["Experiment"] == exp_name
]
if not overview_row.empty:
row = overview_row.iloc[0]
standardized_metadata = {
"c_Ru": row.get("c([Ru(bpy(3]Cl2) [M]", 0) * 1e6,
"c_S2O8": row.get("c(Na2S2O8) [M]", 0) * 1e6,
"power_output": row.get("Power output [W/m^2]", 1000),
"pH": row.get("pH [-]", 7.0),
"irradiance": row.get("Power output [W/m^2]", 1000),
"photon_flux": row.get("photon_flux", exp_data.experiment_metadata.photon_flux),
}
else:
standardized_metadata = {
"c_Ru": exp_data.experiment_metadata.ru_concentration,
"c_S2O8": exp_data.experiment_metadata.oxidant_concentration,
"power_output": exp_data.experiment_metadata.power_output,
"pH": exp_data.experiment_metadata.pH,
"irradiance": exp_data.experiment_metadata.power_output,
"photon_flux": exp_data.experiment_metadata.photon_flux,
}
else:
standardized_metadata = {
"c_Ru": exp_data.experiment_metadata.ru_concentration,
"c_S2O8": exp_data.experiment_metadata.oxidant_concentration,
"power_output": exp_data.experiment_metadata.power_output,
"pH": exp_data.experiment_metadata.pH,
"irradiance": exp_data.experiment_metadata.power_output,
"photon_flux": exp_data.experiment_metadata.photon_flux,
}
data[exp_name] = {
"time": time.tolist() if hasattr(time, "tolist") else time,
"oxygen": oxygen.tolist() if hasattr(oxygen, "tolist") else oxygen,
"metadata": standardized_metadata,
}
return data
except Exception as e:
raise ValueError(f"Could not load experimental data: {e}")
# =============================================================================
# Slug helper
# =============================================================================
def _slugify(text: str) -> str:
text = text.lower().strip()
text = re.sub(r"[^a-z0-9]+", "_", text)
text = text.strip("_")
return text
# =============================================================================
# GitHub-backed storage
# =============================================================================
def _github_headers() -> dict:
token = st.secrets.get("GITHUB_TOKEN", "")
if not token:
st.error("⚠️ `GITHUB_TOKEN` is not set in Streamlit secrets.")
st.stop()
return {
"Authorization": f"token {token}",
"Accept": "application/vnd.github+json",
}
def _github_branch() -> str:
return st.secrets.get("GITHUB_BRANCH", "main")
def _github_repo() -> str:
return st.secrets.get("GITHUB_REPO", "")
def _feedback_file_path(username: str, run_type: str) -> str:
return f"{FEEDBACK_ROOT}/{_slugify(username)}/{_slugify(run_type)}.json"
def _github_contents_url(repo_path: str) -> str:
repo = _github_repo()
return f"{GITHUB_API}/repos/{repo}/contents/{repo_path}"
def _load_json_from_github(repo_path: str) -> Tuple[list, Optional[str]]:
url = _github_contents_url(repo_path)
params = {"ref": _github_branch()}
resp = requests.get(url, headers=_github_headers(), params=params)
if resp.status_code == 200:
payload = resp.json()
content = base64.b64decode(payload["content"]).decode("utf-8")
return json.loads(content), payload["sha"]
elif resp.status_code == 404:
return [], None
else:
st.error(f"GitHub API error ({resp.status_code}): {resp.text}")
return [], None
def _save_json_to_github(repo_path: str, data: list, sha: Optional[str] = None) -> bool:
url = _github_contents_url(repo_path)
content_bytes = json.dumps(data, indent=2, default=str).encode("utf-8")
encoded = base64.b64encode(content_bytes).decode("utf-8")
body = {
"message": f"feedback: {repo_path} @ {datetime.now().isoformat()}",
"content": encoded,
"branch": _github_branch(),
}
if sha is not None:
body["sha"] = sha
resp = requests.put(url, headers=_github_headers(), json=body)
if resp.status_code not in (200, 201):
st.error(f"Failed to save feedback ({resp.status_code}): {resp.text}")
return False
return True
def load_user_run_feedback(username: str, run_type: str) -> Tuple[list, Optional[str]]:
path = _feedback_file_path(username, run_type)
return _load_json_from_github(path)
def save_user_run_feedback(username: str, run_type: str, entries: list, sha: Optional[str] = None) -> bool:
path = _feedback_file_path(username, run_type)
return _save_json_to_github(path, entries, sha)
def _list_github_dir(repo_path: str) -> List[dict]:
url = _github_contents_url(repo_path)
params = {"ref": _github_branch()}
resp = requests.get(url, headers=_github_headers(), params=params)
if resp.status_code == 200:
return resp.json()
return []
def list_all_feedback_users() -> List[str]:
items = _list_github_dir(FEEDBACK_ROOT)
return sorted(item["name"] for item in items if item.get("type") == "dir")
def list_user_run_files(user_slug: str) -> List[str]:
items = _list_github_dir(f"{FEEDBACK_ROOT}/{user_slug}")
return sorted(
item["name"]
for item in items
if item.get("type") == "file" and item["name"].endswith(".json")
)
def load_all_feedback() -> List[dict]:
all_entries = []
for user_slug in list_all_feedback_users():
for filename in list_user_run_files(user_slug):
repo_path = f"{FEEDBACK_ROOT}/{user_slug}/{filename}"
entries, _ = _load_json_from_github(repo_path)
for entry in entries:
entry.setdefault("_user_slug", user_slug)
entry.setdefault("_file", filename)
all_entries.extend(entries)
return all_entries
# =============================================================================
# Result loading helpers
# =============================================================================
def _find_best_phenomenological_result(output_dir: Path) -> Tuple[Optional[Path], Optional[dict], Optional[Path]]:
output_dir = Path(output_dir)
pattern = f"{output_dir.as_posix()}/phenomenologic_result.json.*"
result_files = glob.glob(pattern)
if not result_files:
return None, None, None
best_score = -1.0
best_file = None
best_data = None
best_timestamp = None
for filepath in result_files:
match = re.search(r"phenomenologic_result\.json\.(\d+)$", filepath)
if not match:
continue
timestamp = match.group(1)
try:
with open(filepath, "r") as f:
data = json.load(f)
overall_score = data.get("phenomenological_trends", {}).get("overall_score", -1)
if overall_score > best_score:
best_score = overall_score
best_file = Path(filepath)
best_data = data
best_timestamp = timestamp
except (json.JSONDecodeError, IOError):
continue
best_image = None
if best_timestamp is not None:
candidate = output_dir / f"phenomenological_trends_{best_timestamp}.png"
if candidate.exists():
best_image = candidate
return best_file, best_data, best_image
def get_available_runs(template: str) -> List[Path]:
pattern = BASE_DIR / template
matched_dirs = set(glob.glob(str(pattern)))
for exclude_tmpl in EXCLUDE_PATTERNS.get(template, []):
exclude_pattern = BASE_DIR / exclude_tmpl
exclude_dirs = set(glob.glob(str(exclude_pattern)))
matched_dirs -= exclude_dirs
return sorted(Path(d) for d in matched_dirs if Path(d).is_dir())
def format_reaction_for_display(reaction: dict) -> dict:
formatted = {
"Equation": reaction.get("equation", "N/A"),
"Type": reaction.get("type", "N/A"),
"Description": reaction.get("description", "N/A"),
}
if reaction.get("type") == "light":
qy = reaction.get("fitted_quantum_yield")
qy_range = reaction.get("quantum_yield", [])
formatted["Fitted Parameter"] = f"QY = {qy:.4f}" if qy else "N/A"
formatted["Range"] = f"[{qy_range[0]}, {qy_range[1]}]" if len(qy_range) == 2 else "N/A"
else:
k = reaction.get("fitted_k")
k_range = reaction.get("k_range", [])
formatted["Fitted Parameter"] = f"k = {k:.4e}" if k else "N/A"
formatted["Range"] = f"[{k_range[0]:.0e}, {k_range[1]:.0e}]" if len(k_range) == 2 else "N/A"
return formatted
def extract_run_number(name: str) -> str:
match = re.search(r"_(\d+)$", name)
if match:
return f"Run {match.group(1)}"
return name
# =============================================================================
# OPTIMIZED Interactive Plotly Visualizations
# =============================================================================
def create_interactive_concentration_plot(
network: dict,
params: dict,
exp_data: dict,
experiment_name: str = "Representative Experiment",
) -> go.Figure:
"""
OPTIMIZED: Create interactive concentration-time plot using Plotly.
Uses cached simulations and downsampled data.
Each subplot has its own legend positioned below it.
"""
time_exp = np.array(exp_data["time"])
oxygen_exp = np.array(exp_data["oxygen"])
conditions = exp_data["metadata"]
# Downsample experimental data
time_ds, oxygen_ds = downsample_data(time_exp, oxygen_exp)
# Use cached simulation
network_json = json.dumps(network, sort_keys=True, default=str)
params_json = json.dumps(params, sort_keys=True, default=str)
conditions_json = json.dumps(conditions, sort_keys=True, default=str)
y_solution, species_list, species_idx, time_sim = simulate_species_evolution_cached(
network_json, params_json, conditions_json,
float(time_exp.min()), float(time_exp.max()), n_points=MAX_POINTS_PER_TRACE
)
y_solution = np.array(y_solution)
time_sim = np.array(time_sim)
# Species to exclude (bulk species)
bulk_species = {"S2O8", "SO4"}
panel_a_species = [s for s in species_list if s and s not in bulk_species]
catalyst_species_names = {
"RuII", "RuIII", "Ru_Dimer", "Ru2_dim", "Inactive",
"Ru_inactive", "Ru2_inactive", "RuII_ex",
}
panel_b_species = [s for s in species_list if s and s in catalyst_species_names]
# Create subplots with more space for legends
fig = make_subplots(
rows=1, cols=2,
subplot_titles=("A: Products & Intermediates", "B: Catalyst Species"),
horizontal_spacing=0.12,
)
# Use Scattergl for WebGL rendering (faster)
ScatterClass = go.Scattergl if USE_WEBGL else go.Scatter
# Panel A: Products and intermediates with experimental O2
fig.add_trace(
ScatterClass(
x=time_ds,
y=oxygen_ds,
mode="markers",
name="[O₂] Exp",
marker=dict(color="rgba(128, 128, 128, 0.7)", size=5),
legend="legend1",
),
row=1, col=1,
)
for species in panel_a_species:
if species not in species_idx:
continue
idx = species_idx[species]
color = SPECIES_COLORS.get(species, "#666666")
fig.add_trace(
go.Scatter(
x=time_sim,
y=y_solution[:, idx],
mode="lines",
name=f"[{species}]",
line=dict(color=color, width=2),
legend="legend1",
),
row=1, col=1,
)
# Panel B: Catalyst species
for species in panel_b_species:
if species not in species_idx:
continue
idx = species_idx[species]
color = SPECIES_COLORS.get(species, "#666666")
fig.add_trace(
go.Scatter(
x=time_sim,
y=y_solution[:, idx],
mode="lines",
name=f"[{species}]",
line=dict(color=color, width=2),
legend="legend2",
),
row=1, col=2,
)
fig.update_layout(
title=dict(
text=f"Species Evolution: {experiment_name}",
font=dict(size=16),
),
height=500,
template="plotly_white",
margin=dict(l=60, r=40, t=60, b=120),
# Legend for Panel A (left subplot)
legend1=dict(
orientation="h",
yanchor="top",
y=-0.15,
xanchor="center",
x=0.22,
font=dict(size=9),
bgcolor="rgba(255,255,255,0.8)",
bordercolor="rgba(0,0,0,0.1)",
borderwidth=1,
title=dict(text="Panel A", font=dict(size=10)),
),
# Legend for Panel B (right subplot)
legend2=dict(
orientation="h",
yanchor="top",
y=-0.15,
xanchor="center",
x=0.78,
font=dict(size=9),
bgcolor="rgba(255,255,255,0.8)",
bordercolor="rgba(0,0,0,0.1)",
borderwidth=1,
title=dict(text="Panel B", font=dict(size=10)),
),
)
fig.update_xaxes(title_text="Time / s", row=1, col=1)
fig.update_xaxes(title_text="Time / s", row=1, col=2)
fig.update_yaxes(title_text="Concentration / µM", row=1, col=1)
fig.update_yaxes(title_text="Concentration / µM", row=1, col=2)
return fig
def create_interactive_rate_plots_optimized(
network: dict,
params: dict,
all_exp_data: Dict[str, dict],
selected_curves: Optional[Dict[str, List[str]]] = None,
) -> go.Figure:
"""
OPTIMIZED: Create interactive rate-time plots using Plotly.
Each subplot has its own legend positioned inside the plot area.
"""
# Pre-group experiments by parameter
groups = {
"c_Ru": {},
"c_S2O8": {},
"irradiance": {},
}
for exp_name, exp_data in all_exp_data.items():
meta = exp_data["metadata"]
c_ru = meta.get("c_Ru", 0)
c_s2o8 = meta.get("c_S2O8", 0)
irradiance = meta.get("irradiance", 1000)
groups["c_Ru"].setdefault(c_ru, []).append((exp_name, exp_data))
groups["c_S2O8"].setdefault(c_s2o8, []).append((exp_name, exp_data))
groups["irradiance"].setdefault(irradiance, []).append((exp_name, exp_data))
# Create subplots
fig = make_subplots(
rows=2, cols=2,
subplot_titles=(
"A: [Ru(bpy)₃]Cl₂ Variation",
"B: Na₂S₂O₈ Variation",
"C: Irradiance Variation",
"",
),
horizontal_spacing=0.10,
vertical_spacing=0.12,
)
panel_configs = [
("c_Ru", "µM", (1, 1), "legend1"),
("c_S2O8", "µM", (1, 2), "legend2"),
("irradiance", "Wm⁻²", (2, 1), "legend3"),
]
ScatterClass = go.Scattergl if USE_WEBGL else go.Scatter
network_json = json.dumps(network, sort_keys=True, default=str)
params_json = json.dumps(params, sort_keys=True, default=str)
for param_key, unit, (row, col), legend_name in panel_configs:
param_groups = groups[param_key]
if not param_groups:
continue
sorted_values = sorted(param_groups.keys())
n_colors = max(len(sorted_values), 2)
colors = [PARAM_COLORS[int(i * (len(PARAM_COLORS) - 1) / (n_colors - 1))] for i in range(n_colors)]
for i, param_val in enumerate(sorted_values):
exp_list = param_groups[param_val]
color = colors[i]
label = f"{param_val:.0f} {unit}"
# Check if this curve should be visible
visible = True
if selected_curves and param_key in selected_curves:
visible = label in selected_curves[param_key]
# OPTIMIZATION: Aggregate all experiments with same param into single traces
all_time_exp = []
all_rate_exp = []
all_time_model = []
all_rate_model = []
for exp_name, exp_data in exp_list:
time_exp = np.array(exp_data["time"])
oxygen_exp = np.array(exp_data["oxygen"])
conditions = exp_data["metadata"]
# Downsample
time_ds, oxygen_ds = downsample_data(time_exp, oxygen_exp, max_points=50)
# Calculate experimental rate
rate_exp = np.gradient(oxygen_ds, time_ds)
all_time_exp.extend(time_ds.tolist())
all_rate_exp.extend(rate_exp.tolist())
# Add NaN to create gaps between experiments
all_time_exp.append(None)
all_rate_exp.append(None)
# Cached simulation
conditions_json = json.dumps(conditions, sort_keys=True, default=str)
y_solution, species_list, species_idx, time_sim = simulate_species_evolution_cached(
network_json, params_json, conditions_json,
float(time_exp.min()), float(time_exp.max()), n_points=50
)
y_solution = np.array(y_solution)
time_sim = np.array(time_sim)
o2_pred = (
y_solution[:, species_idx["O2"]]
if "O2" in species_idx
else np.zeros_like(time_sim)
)
rate_pred = np.gradient(o2_pred, time_sim)
all_time_model.extend(time_sim.tolist())
all_rate_model.extend(rate_pred.tolist())
all_time_model.append(None)
all_rate_model.append(None)
# Single aggregated trace for experimental points
fig.add_trace(
ScatterClass(
x=all_time_exp,
y=all_rate_exp,
mode="markers",
name=f"{label}",
marker=dict(color=color, size=4, opacity=0.6),
legendgroup=f"{param_key}_{param_val}",
showlegend=True,
visible=visible,
hovertemplate=f"{label}<br>Time: %{{x:.1f}} s<br>Rate: %{{y:.3f}} µM/s<extra></extra>",
legend=legend_name,
),
row=row, col=col,
)
# Single aggregated trace for model lines
fig.add_trace(
go.Scatter(
x=all_time_model,
y=all_rate_model,
mode="lines",
name=f"{label} (fit)",
line=dict(color=color, width=2),
legendgroup=f"{param_key}_{param_val}",
showlegend=False,