Commit ·
fce6c09
1
Parent(s): ad36a58
latest updates except data
Browse filesFiles changed (13)
- .cache/known_methods_snapshot.jsonAdded+43
- .streamlit/config.tomlAdded+2
- examples/lorenz.py-1
- examples/lorenz_demo.ipynb
- requirements.txt+3-1
- src/__init__.pyAdded
- src/common/__init__.pyAdded
- src/common/method_registry.pyAdded+79
- src/data_store.pyAdded+114
- src/pages/MethodDetails.py+106-87
- src/pages/RawData.pyAdded+72
- src/pages/__init__.pyAdded
- src/streamlit_app.py+306-207
12345678910111213141516171819202122232425262728293031323334353637383940414243{ "known_methods": { "teki": { "abbreviation": "TEKI", "Method": "Tikhonov Regularized Ensemble Kalman Inversion", "family": "Kalman", "aliases": [ "teki" ] }, "etki": { "abbreviation": "ETKI", "Method": "Ensemble Transform Kalman Inversion", "family": "Kalman", "aliases": [ "etki" ] }, "iekf": { "abbreviation": "IEKF", "Method": "Iterative Ensemble Kalman Filter", "family": "Kalman", "aliases": [ "iekf", "gnsl" ] }, "uki": { "abbreviation": "UKI", "Method": "Unscented Kalman Inversion", "family": "Kalman", "aliases": [ "uki" ] } }, "observed_methods": [ "etki", "iekf", "teki" ], "unmapped_observed_methods": []}12[client]showSidebarNavigation = false21 unmodified lines2223242526272821 unmodified linesreturn y + (k1 + 2 * k2 + 2 * k3 + k4) / 6def integrate_lorenz(params,y0,t,dt):def step(y_i,t_i):y_next = rk4_step(lorenz63_step, y_i,t_i, params, dt)return y_next, y_next21 unmodified lines22232425262721 unmodified linesreturn y + (k1 + 2 * k2 + 2 * k3 + k4) / 6def integrate_lorenz(params,y0,t,dt):def step(y_i,t_i):y_next = rk4_step(lorenz63_step, y_i,t_i, params, dt)return y_next, y_next
2 unmodified lines34562 unmodified linesstreamlitjaxgpjaxmatplotlib2 unmodified lines3456782 unmodified linesstreamlitjaxgpjaxmatplotlibxarraynetCDF4
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879from __future__ import annotations
import jsonfrom pathlib import Path
KNOWN_METHODS = { "teki": { "abbreviation": "TEKI", "Method": "Tikhonov Regularized Ensemble Kalman Inversion", "family": "Kalman", "aliases": ["teki"], }, "etki": { "abbreviation": "ETKI", "Method": "Ensemble Transform Kalman Inversion", "family": "Kalman", "aliases": ["etki"], }, "iekf": { "abbreviation": "IEKF", "Method": "Iterative Ensemble Kalman Filter", "family": "Kalman", "aliases": ["iekf", "gnsl"], }, "uki": { "abbreviation": "UKI", "Method": "Unscented Kalman Inversion", "family": "Kalman", "aliases": ["uki"], },}
def build_alias_lookup() -> dict[str, str]: lookup: dict[str, str] = {} for canonical_name, meta in KNOWN_METHODS.items(): lookup[canonical_name] = canonical_name lookup[canonical_name.upper()] = canonical_name for alias in meta.get("aliases", []): lookup[alias.lower()] = canonical_name lookup[alias.upper()] = canonical_name return lookup
ALIAS_TO_CANONICAL = build_alias_lookup()
def normalize_method_name(name: object) -> str: text = str(name).strip()
if text.startswith("b'") and text.endswith("'"): text = text[2:-1] elif text.startswith('b"') and text.endswith('"'): text = text[2:-1]
text = text.strip("\"'").strip() return text.lower()
def canonicalize_method_name(name: object) -> str: normalized = normalize_method_name(name) return ALIAS_TO_CANONICAL.get(normalized, normalized)
def get_method_meta(canonical_name: str) -> dict[str, str]: return KNOWN_METHODS.get(canonical_name, {})
def dump_method_registry_snapshot(project_root: Path, observed_methods: set[str]) -> None: snapshot = { "known_methods": KNOWN_METHODS, "observed_methods": sorted(observed_methods), "unmapped_observed_methods": sorted([method for method in observed_methods if method not in KNOWN_METHODS]), } cache_dir = project_root / ".cache" cache_dir.mkdir(parents=True, exist_ok=True) target_file = cache_dir / "known_methods_snapshot.json" target_file.write_text(json.dumps(snapshot, indent=2), encoding="utf-8")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114from __future__ import annotations
import importlibfrom pathlib import Path
import pandas as pdimport streamlit as st
try: from common.method_registry import ( dump_method_registry_snapshot, canonicalize_method_name, get_method_meta, normalize_method_name, )except ModuleNotFoundError: from src.common.method_registry import ( dump_method_registry_snapshot, canonicalize_method_name, get_method_meta, normalize_method_name, )
DATASET_FILES = { "L63": "l63_ensemble_results.nc", "L96": "l96_ensemble_results.nc", "L96_NN_FORCING": "l96_nn_forcing_ensemble_results.nc", "L96_SPATIAL_FORCING": "l96_spatial_forcing_ensemble_results.nc",}
EXPECTED_DIMS = ("algorithm_type", "rmse_target", "ensemble_size", "random_seed")
@st.cache_data(show_spinner=False)def load_metric_store() -> pd.DataFrame: xr = importlib.import_module("xarray")
project_root = Path(__file__).resolve().parent.parent data_dir = project_root / "data"
records: list[pd.DataFrame] = []
for benchmark_name, filename in DATASET_FILES.items(): file_path = data_dir / filename if not file_path.exists(): continue
with xr.open_dataset(file_path) as dataset: if "metric" not in dataset: continue
metric = dataset["metric"]
missing_dims = [dim for dim in EXPECTED_DIMS if dim not in metric.dims] if missing_dims: st.warning( f"Skipping {file_path.name}: metric dims are {metric.dims}, missing {missing_dims}" ) continue
metric_mean = metric.mean(dim="random_seed", skipna=True) df = metric_mean.to_series().reset_index(name="metric")
df["benchmark"] = benchmark_name records.append(df[["benchmark", "algorithm_type", "rmse_target", "ensemble_size", "metric"]])
if not records: return pd.DataFrame(columns=["benchmark", "algorithm_type", "rmse_target", "ensemble_size", "metric"])
merged = pd.concat(records, ignore_index=True) merged["algorithm_alias"] = merged["algorithm_type"].map(normalize_method_name) merged["algorithm_type"] = merged["algorithm_alias"].map(canonicalize_method_name) merged["ensemble_size"] = pd.to_numeric(merged["ensemble_size"], errors="coerce") merged["metric"] = pd.to_numeric(merged["metric"], errors="coerce") merged = merged.dropna(subset=["ensemble_size", "metric"]) merged["ensemble_size"] = merged["ensemble_size"].astype(int) merged["forward_model_runs"] = merged["metric"]
merged["abbreviation"] = merged["algorithm_type"].map(lambda method: get_method_meta(method).get("abbreviation")) merged["Method"] = merged["algorithm_type"].map(lambda method: get_method_meta(method).get("Method")) merged["family"] = merged["algorithm_type"].map(lambda method: get_method_meta(method).get("family")) merged["abbreviation"] = merged["abbreviation"].fillna(merged["algorithm_type"].str.upper()) merged["Method"] = merged["Method"].fillna(merged["abbreviation"]) merged["family"] = merged["family"].fillna("Kalman")
try: dump_method_registry_snapshot(project_root=project_root, observed_methods=set(merged["algorithm_type"].unique())) except OSError: st.warning("Unable to write method registry snapshot to .cache/known_methods_snapshot.json")
return merged
def build_leaderboard(metric_store: pd.DataFrame) -> pd.DataFrame: if metric_store.empty: return pd.DataFrame( columns=[ "family", "Method", "abbreviation", "benchmark", "Forward Model Runs", "Optimal Ensemble Size", "Target Level", ] )
best_idx = metric_store.groupby(["benchmark", "algorithm_type"])["metric"].idxmin() best = metric_store.loc[best_idx].copy() best = best.rename(columns={"metric": "Forward Model Runs", "rmse_target": "Target Level", "ensemble_size": "Optimal Ensemble Size"}) return best[["family", "Method", "abbreviation", "benchmark", "Forward Model Runs", "Optimal Ensemble Size", "Target Level"]].sort_values( ["benchmark", "Forward Model Runs"], ascending=[True, True] )1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021033 unmodified lines107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137import pandas as pdimport streamlit as stst.set_page_config(page_title="Method Details", page_icon="📘")st.title("Method Details")st.caption("Metadata, citation, and benchmark slice by method abbreviation")# Read selected method from query paramsabbr = st.query_params.get("method")if not isinstance(abbr, str):abbr = None# Demo dataset (should be refactored to shared source or file)eki_rmse = 0.56hm_rmse = 0.124methods_df = pd.DataFrame([{"family": "Kalman","Method": "Ensemble Kalman Inversion","RMSE": eki_rmse,"abbreviation": "EKI","Forward Runs": 250,"Optimal Ensemble Size": 64,"uses_emulator": False,},{"family": "Kalman","Method": "Tikhonov Regularized Ensemble Kalman Inversion","RMSE": eki_rmse,"abbreviation": "TEKI","Forward Runs": 250,"Optimal Ensemble Size": 64,"uses_emulator": False,},{"family": "Kalman","Method": "Unscented Kalman Inversion","RMSE": eki_rmse,"abbreviation": "UKI","Forward Runs": 250,"Optimal Ensemble Size": 64,"uses_emulator": False,},{"family": "Approx Bayesian","Method": "History Matching","RMSE": hm_rmse,"abbreviation": "HM","Forward Runs": 180,"Optimal Ensemble Size": 32,"uses_emulator": False,},{"family": "Approx Bayesian","Method": "Approx Bayesian Computation","RMSE": hm_rmse,"abbreviation": "ABC","Forward Runs": 1800,"Optimal Ensemble Size": 32,"uses_emulator": True,},])abbrs = methods_df["abbreviation"].tolist()# Metadata dictionary (can be moved to a JSON/YAML later)method_meta = {"EKI": {"citation": "Iglesias et al., Inverse Problems, 2013","url": "https://doi.org/10.1088/0266-5611/29/8/085009","summary": "Ensemble-based gradient-free inversion using Kalman updates.",},"TEKI": {"citation": "Chada et al., SIAM/ASA J. UQ, 2018","url": "https://doi.org/10.1137/17M114402X","summary": "EKI variant with Tikhonov regularization for stability.",},"UKI": {"citation": "Unscented transform-based inversion (placeholder)","url": "https://example.com/uki","summary": "Uses sigma points to propagate uncertainty without linearization.",},"HM": {"citation": "Craig et al., Technometrics, 1997","url": "https://doi.org/10.1080/00401706.1997.10485256","summary": "Eliminates implausible regions via emulator-guided screening.",},"ABC": {"citation": "Beaumont et al., Genetics, 2002","url": "https://doi.org/10.1093/genetics/162.4.2025","summary": "Likelihood-free Bayesian inference via simulation and distance.",},}# Selection UI (defaults to query param if valid)default_idx = 0if isinstance(abbr, str) and abbr in abbrs:default_idx = abbrs.index(abbr)sel = st.selectbox("Choose a method", options=abbrs, index=default_idx)# Persist selection to URLst.query_params["method"] = sel3 unmodified linesmeta = method_meta.get(sel, {})st.subheader(f"{sel} — {row['Method']}")col1, col2 = st.columns(2)with col1:st.markdown("**Citation:**")st.write(meta.get("citation", "Citation pending"))st.markdown("**Summary:**")st.write(meta.get("summary", "Summary pending"))with col2:st.markdown("**Link:**")st.link_button("Open reference", meta.get("url", "https://example.com"))st.markdown("**Benchmark Slice (Lorenz63)**")slice_df = methods_df[methods_df["abbreviation"] == sel].copy()st.dataframe(slice_df,width='stretch',hide_index=True,column_config={"family": st.column_config.TextColumn("Family"),"Method": st.column_config.TextColumn("Method"),"RMSE": st.column_config.NumberColumn("RMSE", format="%.3f"),"Forward Runs": st.column_config.NumberColumn("Forward Runs"),"Optimal Ensemble Size": st.column_config.NumberColumn("Optimal Ensemble Size"),"uses_emulator": st.column_config.CheckboxColumn("Uses Emulator"),"abbreviation": None,},)st.page_link("../streamlit_app.py", label="⬅ Back to Leaderboard", icon="↩️")1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768693 unmodified lines737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156from pathlib import Pathimport sysimport altair as altimport streamlit as sttry:from data_store import load_metric_storeexcept ModuleNotFoundError:sys.path.append(str(Path(__file__).resolve().parents[1]))from data_store import load_metric_storest.set_page_config(page_title="Method Details", page_icon="📘", layout="wide")# Sidebar navigationst.sidebar.title("Navigation")st.sidebar.page_link("streamlit_app.py", label="Home", icon="🏠")st.sidebar.page_link("pages/MethodDetails.py", label="Methods", icon="📘")st.sidebar.page_link("pages/RawData.py", label="Get Data", icon="🧾")st.title("Method Details")st.caption("Method-level view from NetCDF forward-model-run metrics averaged over random seeds")# Read selected method from query paramsabbr = st.query_params.get("method")if not isinstance(abbr, str):abbr = Nonemetric_store = load_metric_store()if metric_store.empty:st.warning("No metric data found. Expected NetCDF files in `data/` with a `metric` variable.")st.stop()methods_df = metric_store[["family", "Method", "abbreviation"]].drop_duplicates().sort_values("abbreviation")abbrs = methods_df["abbreviation"].tolist()# Metadata dictionary (can be moved to a JSON/YAML later)method_meta = {"TEKI": {"citation": "Chada et al., SIAM/ASA J. UQ, 2018","url": "https://doi.org/10.1137/17M114402X","summary": "EKI variant with Tikhonov regularization for stability.",},"ETKI": {"citation": "Ensemble transform variant (citation to be added)","url": "https://example.com/etki","summary": "Transform-based Kalman inversion using ensemble-space updates.",},"IEKF": {"citation": "Iterative ensemble Kalman filter (citation to be added)","url": "https://example.com/iekf","summary": "Iterative Kalman updates for nonlinear inverse problems.",},"UKI": {"citation": "Unscented transform-based inversion (placeholder)","url": "https://example.com/uki","summary": "Uses sigma points to propagate uncertainty without linearization.",},}# Selection UI (defaults to query param if valid)default_idx = 0if isinstance(abbr, str) and abbr in abbrs:default_idx = abbrs.index(abbr)sel = str(st.selectbox("Choose a method", options=abbrs, index=default_idx))# Persist selection to URLst.query_params["method"] = sel3 unmodified linesmeta = method_meta.get(sel, {})st.subheader(f"{sel} — {row['Method']}")col1, col2, col3 = st.columns(3)with col1:with st.container(border=True):st.markdown("**Citation**")st.write(meta.get("citation", "Citation pending"))with col2:with st.container(border=True):st.markdown("**Link**")st.link_button("Open reference", meta.get("url", "https://example.com"))with col3:with st.container(border=True):st.markdown("**Summary**")st.write(meta.get("summary", "Summary pending"))st.markdown("**Benchmark Slice**")slice_df = metric_store[metric_store["abbreviation"] == sel].copy()slice_df = slice_df.sort_values(["benchmark", "rmse_target", "ensemble_size"])target_options = ["1.0", "1.1", "1.2"]selected_target = st.radio("RMSE Target Level", options=target_options, horizontal=True)best_table_view = slice_df[slice_df["rmse_target"].astype(str) == selected_target]best_idx = best_table_view.groupby("benchmark")["metric"].idxmin()best_by_benchmark = (best_table_view.loc[best_idx, ["benchmark", "metric", "ensemble_size"]].rename(columns={"metric": "Best Mean Forward Model Runs","ensemble_size": "Optimal Ensemble Size",}).sort_values("benchmark"))st.markdown("**Best by Benchmark**")st.dataframe(best_by_benchmark,hide_index=True,width="stretch",column_config={"benchmark": st.column_config.TextColumn("Benchmark"),"Best Mean Forward Model Runs": st.column_config.NumberColumn("Best Mean Forward Model Runs", format="%.4f"),"Optimal Ensemble Size": st.column_config.NumberColumn("Optimal Ensemble Size"),},)st.markdown("**Scaling by Benchmark**")chart_view = slice_df[slice_df["rmse_target"].astype(str) == selected_target]chart_df = (chart_view.groupby(["benchmark", "ensemble_size"], as_index=False).agg(mean_forward_runs=("metric", "mean")))chart = (alt.Chart(chart_df).mark_line(point=True).encode(x=alt.X("ensemble_size:Q", title="Ensemble Size"),y=alt.Y("mean_forward_runs:Q", title="Mean Forward Model Runs"),color=alt.Color("benchmark:N", title="Benchmark"),tooltip=["benchmark", "ensemble_size", alt.Tooltip("mean_forward_runs:Q", format=".4f")],))st.altair_chart(chart, width="stretch")st.markdown("**All Averaged Configurations for Method**")st.dataframe(slice_df[["benchmark", "algorithm_alias", "rmse_target", "ensemble_size", "metric"]],hide_index=True,width="stretch",column_config={"benchmark": st.column_config.TextColumn("Benchmark"),"algorithm_alias": st.column_config.TextColumn("Source Alias"),"rmse_target": st.column_config.TextColumn("RMSE Target"),"ensemble_size": st.column_config.NumberColumn("Ensemble Size"),"metric": st.column_config.NumberColumn("Mean Forward Model Runs", format="%.4f"),},)st.page_link("streamlit_app.py", label="⬅ Back to Leaderboard", icon="↩️")
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172from pathlib import Pathimport sys
import streamlit as st
try: from data_store import load_metric_storeexcept ModuleNotFoundError: sys.path.append(str(Path(__file__).resolve().parents[1])) from data_store import load_metric_store
st.set_page_config(page_title="Raw Data", page_icon="🧾", layout="wide")
# Sidebar navigationst.sidebar.title("Navigation")st.sidebar.page_link("streamlit_app.py", label="Home", icon="🏠")st.sidebar.page_link("pages/MethodDetails.py", label="Methods", icon="📘")st.sidebar.page_link("pages/RawData.py", label="Get Data", icon="🧾")
st.title("Raw Averaged Forward Model Runs")st.caption("All rows are averaged over random seeds during ingestion; `metric` represents forward model runs")
metric_store = load_metric_store()if metric_store.empty: st.warning("No metric data found. Expected NetCDF files in `data/` with a `metric` variable.") st.stop()
benchmark_options = sorted(metric_store["benchmark"].unique().tolist())default_benchmark_index = benchmark_options.index("L63") if "L63" in benchmark_options else 0selected_benchmark = str(st.selectbox("Benchmark", options=benchmark_options, index=default_benchmark_index))
filtered = metric_store[metric_store["benchmark"] == selected_benchmark].copy()filtered = filtered.sort_values(["abbreviation", "rmse_target", "ensemble_size"])
st.dataframe( filtered[ [ "benchmark", "abbreviation", "Method", "family", "algorithm_type", "algorithm_alias", "rmse_target", "ensemble_size", "metric", ] ], hide_index=True, width="stretch", column_config={ "benchmark": st.column_config.TextColumn("Benchmark"), "abbreviation": st.column_config.TextColumn("Abbrev."), "Method": st.column_config.TextColumn("Method"), "family": st.column_config.TextColumn("Family"), "algorithm_type": st.column_config.TextColumn("Canonical Type"), "algorithm_alias": st.column_config.TextColumn("Source Alias"), "rmse_target": st.column_config.TextColumn("RMSE Target"), "ensemble_size": st.column_config.NumberColumn("Ensemble Size"), "metric": st.column_config.NumberColumn("Mean Forward Model Runs", format="%.6f"), },)
csv_data = filtered.to_csv(index=False).encode("utf-8")st.download_button( label=f"Download {selected_benchmark} averaged metrics (CSV)", data=csv_data, file_name=f"{selected_benchmark.lower()}_averaged_metrics.csv", mime="text/csv",)
st.page_link("streamlit_app.py", label="⬅ Back to Leaderboard", icon="↩️")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225import altair as altimport numpy as npimport pandas as pdimport streamlit as st"""# Calibration Benchmark"""# Sidebar navigationst.sidebar.title("Benchmarks")# Robust in-app navigation without page_linkif "nav" not in st.session_state:st.session_state.nav = "Leaderboard"toggle_label = "📘 Open Method Details" if st.session_state.nav == "Leaderboard" else "↩️ Back to Leaderboard"if st.sidebar.button(toggle_label):st.session_state.nav = "Method Details" if st.session_state.nav == "Leaderboard" else "Leaderboard"st.rerun()if st.session_state.nav == "Leaderboard":st.header("Lorenz63 Calibration: Mock Leaderboard")st.caption("Placeholder RMSE values for methods (demo)")# Placeholder RMSE values for methodseki_rmse = 0.56hm_rmse = 0.124leaderboard_df = pd.DataFrame([{"family": "Kalman","Method": "Ensemble Kalman Inversion","RMSE": eki_rmse,"abbreviation": "EKI","Forward Runs": 250,"Optimal Ensemble Size": 64,"uses_emulator":False,},{"family": "Kalman","Method": "Tikhonov Regularized Ensemble Kalman Inversion","abbreviation": "TEKI","RMSE": eki_rmse,"Forward Runs": 250,"Optimal Ensemble Size": 64,"uses_emulator":False,},{"family": "Kalman","Method": "Unscented Kalman Inversion","abbreviation": "UKI","RMSE": eki_rmse,"Forward Runs": 250,"Optimal Ensemble Size": 64,"uses_emulator":False,},{"family": "Approx Bayesian","Method": "History Matching","abbreviation": "HM","RMSE": hm_rmse,"Forward Runs": 180,"Optimal Ensemble Size": 32,"uses_emulator":False,},{"family": "Approx Bayesian","Method": "Approx Bayesian Computation","abbreviation": "ABC","RMSE": hm_rmse,"Forward Runs": 1800,"Optimal Ensemble Size": 32,"uses_emulator":True,},])# Sort by RMSE ascending (lower is better)leaderboard_df = leaderboard_df.sort_values(by="RMSE", ascending=True).reset_index(drop=True)st.subheader("All Methods (Sortable)")# Use data_editor to enable row selection and navigate on clickif "selected_method" not in st.session_state:st.session_state.selected_method = None# Add a non-interactive details column (placeholder)display_df = leaderboard_df.copy()display_df["Details"] = display_df["abbreviation"].apply(lambda a: f"Method Details — {a}")st.data_editor(display_df,width='stretch',hide_index=True,disabled=True,key="all_methods_editor",use_container_width=False,column_config={"Method": st.column_config.TextColumn("Method"),"abbreviation": st.column_config.TextColumn("Abbrev.", help="Method abbreviation (hover for details)"),"family": st.column_config.TextColumn("Family",help="Method family grouping (e.g., Kalman, Approx Bayesian)",),"RMSE": st.column_config.NumberColumn("RMSE",help="Root Mean Squared Error (lower is better)",format="%.3f",),"Forward Runs": st.column_config.NumberColumn("Forward Runs",help="Total forward model evaluations",),"Optimal Ensemble Size": st.column_config.NumberColumn("Optimal Ensemble Size",help="Best-performing ensemble size (placeholder)",),"uses_emulator": st.column_config.CheckboxColumn("Uses Emulator",help="Indicates whether an emulator/surrogate was used",),"Details": st.column_config.TextColumn("Details"),},)# Per-family breakdownsst.subheader("Per-Family Breakdowns")for fam in sorted(leaderboard_df["family"].unique()):st.markdown(f"**{fam} Methods**")fam_df = leaderboard_df[leaderboard_df["family"] == fam]st.data_editor(fam_df,width='stretch',hide_index=True,disabled=True,key=f"fam_editor_{fam}",use_container_width=False,column_config={"Method": st.column_config.TextColumn("Method"),"abbreviation": st.column_config.TextColumn("Abbrev."),"RMSE": st.column_config.NumberColumn("RMSE", format="%.3f"),"Forward Runs": st.column_config.NumberColumn("Forward Runs"),"Optimal Ensemble Size": st.column_config.NumberColumn("Optimal Ensemble Size"),"uses_emulator": st.column_config.CheckboxColumn("Uses Emulator"),},)# Optional: small glossary preview from abbreviationsst.caption("Hover over 'Abbrev.' header for a hint. A full glossary page can be added later.")# else:# # Method Details inline view# st.header("Method Details")# st.caption("Metadata, citation, and benchmark slice by method abbreviation")# # Same dataset and metadata as leaderboard# abbrs = leaderboard_df["abbreviation"].tolist()# default_idx = 0# qp_method = st.query_params.get("method")# if isinstance(qp_method, str) and qp_method in abbrs:# default_idx = abbrs.index(qp_method)# sel = st.selectbox("Choose a method", options=abbrs, index=default_idx)# st.query_params["method"] = sel# method_meta = {# "EKI": {# "citation": "Iglesias et al., Inverse Problems, 2013",# "url": "https://doi.org/10.1088/0266-5611/29/8/085009",# "summary": "Ensemble-based gradient-free inversion using Kalman updates.",# },# "TEKI": {# "citation": "Chada et al., SIAM/ASA J. UQ, 2018",# "url": "https://doi.org/10.1137/17M114402X",# "summary": "EKI variant with Tikhonov regularization for stability.",# },# "UKI": {# "citation": "Unscented transform-based inversion (placeholder)",# "url": "https://example.com/uki",# "summary": "Uses sigma points to propagate uncertainty without linearization.",# },# "HM": {# "citation": "Craig et al., Technometrics, 1997",# "url": "https://doi.org/10.1080/00401706.1997.10485256",# "summary": "Eliminates implausible regions via emulator-guided screening.",# },# "ABC": {# "citation": "Beaumont et al., Genetics, 2002",# "url": "https://doi.org/10.1093/genetics/162.4.2025",# "summary": "Likelihood-free Bayesian inference via simulation and distance.",# },# }# row = leaderboard_df.loc[leaderboard_df["abbreviation"] == sel].iloc[0]# meta = method_meta.get(sel, {})# st.subheader(f"{sel} — {row['Method']}")# col1, col2 = st.columns(2)# with col1:# st.markdown("**Citation:**")# st.write(meta.get("citation", "Citation pending"))# st.markdown("**Summary:**")# st.write(meta.get("summary", "Summary pending"))# with col2:# st.markdown("**Link:**")# st.link_button("Open reference", meta.get("url", "https://example.com"))# st.markdown("**Benchmark Slice (Lorenz63)**")# slice_df = leaderboard_df[leaderboard_df["abbreviation"] == sel].copy()# st.dataframe(# slice_df,# width='stretch',# hide_index=True,# column_config={# "family": st.column_config.TextColumn("Family"),# "Method": st.column_config.TextColumn("Method"),# "RMSE": st.column_config.NumberColumn("RMSE", format="%.3f"),# "Forward Runs": st.column_config.NumberColumn("Forward Runs"),# "Optimal Ensemble Size": st.column_config.NumberColumn("Optimal Ensemble Size"),# "uses_emulator": st.column_config.CheckboxColumn("Uses Emulator"),# "abbreviation": None,# },# )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324import altair as altimport importlibimport pandas as pdimport streamlit as stst.set_page_config(layout="wide")if __package__:data_store = importlib.import_module(f"{__package__}.data_store")else:data_store = importlib.import_module("data_store")load_metric_store = data_store.load_metric_storest.title("Calibration Benchmark")# Sidebar navigationst.sidebar.title("Navigation")st.sidebar.page_link("streamlit_app.py", label="Home", icon="🏠")st.sidebar.page_link("pages/MethodDetails.py", label="Methods", icon="📘")st.sidebar.page_link("pages/RawData.py", label="Get Data", icon="🧾")show_home = st.session_state.get("show_home", True)if show_home:st.header("Calibration Leaderboard")metric_store = load_metric_store()if metric_store.empty:st.warning("No metric data found. Expected NetCDF files in `data/` with a `metric` variable.")st.stop()benchmark_values = sorted(metric_store["benchmark"].unique().tolist())benchmark_options = ["All"] + benchmark_valuesdefault_benchmark_index = 0selected_benchmark = st.selectbox("Benchmark", options=benchmark_options, index=default_benchmark_index)filtered = metric_store.copy() if selected_benchmark == "All" else metric_store[metric_store["benchmark"] == selected_benchmark].copy()filtered["rmse_target_str"] = filtered["rmse_target"].astype(str)target_options = ["All targets"] + sorted(metric_store["rmse_target"].astype(str).unique().tolist())scoring_options = ["Mean Forward Model Runs","Minimum Forward Model Runs","Smallest Optimal Ensemble Size","Custom Blend",]current_target = st.session_state.get("selected_target", "All targets")if current_target not in target_options:current_target = target_options[0]current_scoring_mode = st.session_state.get("scoring_mode", "Mean Forward Model Runs")if current_scoring_mode not in scoring_options:current_scoring_mode = scoring_options[0]current_rmse_weight_percent = int(st.session_state.get("rmse_weight_percent", 80))current_rmse_weight_percent = max(0, min(100, current_rmse_weight_percent))selected_target = current_targetscoring_mode = current_scoring_modermse_weight = current_rmse_weight_percent / 100.0ensemble_weight = 1.0 - rmse_weightdef build_scored_table(input_df, add_rank=True):ranking_source = input_df if selected_target == "All targets" else input_df[input_df["rmse_target_str"] == selected_target]if ranking_source.empty:return ranking_sourcescored_df = ranking_source.groupby(["algorithm_type", "abbreviation", "Method", "family"], as_index=False).agg(**{"Mean Forward Model Runs": ("metric", "mean")},**{"Minimum Forward Model Runs": ("metric", "min")},**{"Targets Used": ("rmse_target_str", "nunique")},**{"Ensemble Sizes Used": ("ensemble_size", "nunique")},)best_per_target = (ranking_source.sort_values(["algorithm_type", "rmse_target_str", "metric", "ensemble_size"]).groupby(["algorithm_type", "abbreviation", "Method", "family", "rmse_target_str"], as_index=False).first()[["algorithm_type","abbreviation","Method","family","rmse_target_str","ensemble_size",]])optimal_ensemble = best_per_target.groupby(["algorithm_type", "abbreviation", "Method", "family"], as_index=False).agg(**{"Optimal Ensemble Size": ("ensemble_size", "mean")})scored_df = scored_df.merge(optimal_ensemble,on=["algorithm_type", "abbreviation", "Method", "family"],how="left",)scored_df["Optimal Ensemble Size"] = scored_df["Optimal Ensemble Size"].round(2)scored_df["Mean Forward Model Runs"] = scored_df["Mean Forward Model Runs"].round(4)scored_df["Minimum Forward Model Runs"] = scored_df["Minimum Forward Model Runs"].round(4)mean_runs_min = scored_df["Mean Forward Model Runs"].min()mean_runs_max = scored_df["Mean Forward Model Runs"].max()if mean_runs_max > mean_runs_min:scored_df["mean_runs_score"] = 100.0 * (mean_runs_max - scored_df["Mean Forward Model Runs"]) / (mean_runs_max - mean_runs_min)else:scored_df["mean_runs_score"] = 100.0minimum_runs_min = scored_df["Minimum Forward Model Runs"].min()minimum_runs_max = scored_df["Minimum Forward Model Runs"].max()if minimum_runs_max > minimum_runs_min:scored_df["minimum_runs_score"] = 100.0 * (minimum_runs_max - scored_df["Minimum Forward Model Runs"]) / (minimum_runs_max - minimum_runs_min)else:scored_df["minimum_runs_score"] = 100.0ens_min = scored_df["Optimal Ensemble Size"].min()ens_max = scored_df["Optimal Ensemble Size"].max()if ens_max > ens_min:scored_df["ensemble_score"] = 100.0 * (ens_max - scored_df["Optimal Ensemble Size"]) / (ens_max - ens_min)else:scored_df["ensemble_score"] = 100.0if scoring_mode == "Mean Forward Model Runs":scored_df["Score"] = scored_df["mean_runs_score"]sort_columns = ["Mean Forward Model Runs", "Optimal Ensemble Size", "abbreviation"]ascending = [True, True, True]elif scoring_mode == "Minimum Forward Model Runs":scored_df["Score"] = scored_df["minimum_runs_score"]sort_columns = ["Minimum Forward Model Runs", "Optimal Ensemble Size", "abbreviation"]ascending = [True, True, True]elif scoring_mode == "Smallest Optimal Ensemble Size":scored_df["Score"] = scored_df["ensemble_score"]sort_columns = ["Optimal Ensemble Size", "Mean Forward Model Runs", "abbreviation"]ascending = [True, True, True]else:scored_df["Score"] = (rmse_weight * scored_df["mean_runs_score"]+ ensemble_weight * scored_df["ensemble_score"])sort_columns = ["Score", "Mean Forward Model Runs", "Optimal Ensemble Size", "abbreviation"]ascending = [False, True, True, True]scored_df = scored_df.sort_values(sort_columns, ascending=ascending).reset_index(drop=True)if add_rank:scored_df["Rank"] = scored_df.index + 1scored_df["Placement"] = scored_df["Rank"].apply(lambda rank: f"{ {1: '🥇', 2: '🥈', 3: '🥉'}.get(rank, '')} #{rank}".strip())return scored_dfif selected_benchmark == "All":benchmark_scores = []for benchmark_name in benchmark_values:benchmark_df = metric_store[metric_store["benchmark"] == benchmark_name].copy()benchmark_df["rmse_target_str"] = benchmark_df["rmse_target"].astype(str)scored = build_scored_table(benchmark_df, add_rank=False)if scored.empty:continuescored["benchmark"] = benchmark_namebenchmark_scores.append(scored)if benchmark_scores:combined_scores = benchmark_scores[0].copy() if len(benchmark_scores) == 1 else pd.concat(benchmark_scores, ignore_index=True)leaderboard_df = combined_scores.groupby(["algorithm_type", "abbreviation", "Method", "family"], as_index=False).agg(Score=("Score", "mean"),**{"Mean Forward Model Runs": ("Mean Forward Model Runs", "mean")},**{"Minimum Forward Model Runs": ("Minimum Forward Model Runs", "mean")},**{"Optimal Ensemble Size": ("Optimal Ensemble Size", "mean")},**{"Targets Used": ("Targets Used", "mean")},**{"Ensemble Sizes Used": ("Ensemble Sizes Used", "mean")},**{"Benchmarks Used": ("benchmark", "nunique")},)leaderboard_df["Mean Forward Model Runs"] = leaderboard_df["Mean Forward Model Runs"].round(4)leaderboard_df["Minimum Forward Model Runs"] = leaderboard_df["Minimum Forward Model Runs"].round(4)leaderboard_df["Optimal Ensemble Size"] = leaderboard_df["Optimal Ensemble Size"].round(2)leaderboard_df["Targets Used"] = leaderboard_df["Targets Used"].round().astype(int)leaderboard_df["Ensemble Sizes Used"] = leaderboard_df["Ensemble Sizes Used"].round().astype(int)leaderboard_df = leaderboard_df.sort_values(["Score", "Mean Forward Model Runs", "abbreviation"], ascending=[False, True, True]).reset_index(drop=True)leaderboard_df["Rank"] = leaderboard_df.index + 1leaderboard_df["Placement"] = leaderboard_df["Rank"].apply(lambda rank: f"{ {1: '🥇', 2: '🥈', 3: '🥉'}.get(rank, '')} #{rank}".strip())else:leaderboard_df = pd.DataFrame(columns=["Placement","abbreviation","Method","family","Mean Forward Model Runs","Minimum Forward Model Runs","Score","Optimal Ensemble Size","Targets Used","Ensemble Sizes Used","Benchmarks Used",])else:leaderboard_df = build_scored_table(filtered, add_rank=True)leaderboard_df["Benchmarks Used"] = 1if scoring_mode == "Mean Forward Model Runs":score_basis = "normalized mean of best forward model runs over selected target levels (lower is better)"elif scoring_mode == "Minimum Forward Model Runs":score_basis = "normalized minimum of forward model runs over selected targets and ensemble sizes (lower is better)"elif scoring_mode == "Smallest Optimal Ensemble Size":score_basis = "normalized mean optimal ensemble size over selected target levels (lower is better)"else:score_basis = ("weighted blend of normalized forward-model-runs score and normalized ensemble-size score "f"(forward-runs weight {rmse_weight:.0%}, ensemble-size weight {ensemble_weight:.0%})")if selected_benchmark == "All":score_basis = f"{score_basis}; in All mode, each method's final score is the mean of its per-benchmark scores"if leaderboard_df.empty:st.warning("No rows available for the current benchmark/target selection.")st.stop()if selected_benchmark == "All":table_column_order = ["Placement","abbreviation","Method","family","Score","Targets Used","Ensemble Sizes Used","Benchmarks Used",]else:table_column_order = ["Placement","abbreviation","Method","family","Score","Mean Forward Model Runs","Minimum Forward Model Runs","Optimal Ensemble Size","Targets Used","Ensemble Sizes Used","Benchmarks Used",]st.subheader(f"Ranked Leaderboard — {selected_benchmark}")st.dataframe(leaderboard_df,hide_index=True,width="stretch",column_config={"Placement": st.column_config.TextColumn("Placement"),"family": st.column_config.TextColumn("Family"),"Method": st.column_config.TextColumn("Method"),"abbreviation": st.column_config.TextColumn("Abbrev."),"Mean Forward Model Runs": st.column_config.NumberColumn("Mean Forward Model Runs", format="%.4f"),"Minimum Forward Model Runs": st.column_config.NumberColumn("Minimum Forward Model Runs", format="%.4f"),"Score": st.column_config.ProgressColumn("Score (0-100)", min_value=0.0, max_value=100.0, format="%.1f"),"Optimal Ensemble Size": st.column_config.NumberColumn("Mean Optimal Ensemble Size", format="%.2f"),"Targets Used": st.column_config.NumberColumn("Targets Used", format="%d"),"Ensemble Sizes Used": st.column_config.NumberColumn("Ensemble Sizes Used", format="%d"),"Benchmarks Used": st.column_config.NumberColumn("Benchmarks Used", format="%d"),},column_order=table_column_order,)with st.expander("Scoring & Target Controls", expanded=False):st.radio("RMSE Target Level",options=target_options,horizontal=True,key="selected_target",)st.radio("Scoring Method",options=scoring_options,horizontal=True,key="scoring_mode",)if st.session_state.get("scoring_mode", "Mean Forward Model Runs") == "Custom Blend":st.slider("Blend Weight: Forward Runs vs Ensemble Size",min_value=0,max_value=100,step=5,key="rmse_weight_percent",help="Higher forward-runs weight prioritizes fewer model evaluations; higher ensemble-size weight prioritizes smaller ensembles.",)st.info(f"Score is a normalized 0–100 ranking based on **{score_basis}**. ""For Mean/Minimum forward-runs scoring, values are computed from all selected metric target levels and all ensemble sizes ""after averaging over random seeds.")if selected_benchmark != "All":st.subheader("Mean Forward Model Runs vs Ensemble Size")chart_source = filtered if selected_target == "All targets" else filtered[filtered["rmse_target_str"] == selected_target]chart_df = chart_source.groupby(["abbreviation", "ensemble_size"], as_index=False).agg(mean_forward_runs=("metric", "mean"))chart = (alt.Chart(chart_df).mark_line(point=True).encode(x=alt.X("ensemble_size:Q", title="Ensemble Size"),y=alt.Y("mean_forward_runs:Q", title="Mean Forward Model Runs"),color=alt.Color("abbreviation:N", title="Method"),tooltip=["abbreviation", "ensemble_size", alt.Tooltip("mean_forward_runs:Q", format=".4f")],))st.altair_chart(chart, width="stretch")st.caption("Top 3 are shown as podium spots; remaining methods are directly comparable via normalized score.")st.page_link("pages/RawData.py", label="Open Raw Data & CSV Export", icon="🧾")
.cache/known_methods_snapshot.jsonAdded+43
.streamlit/config.tomlAdded+2
examples/lorenz.py-1
examples/lorenz_demo.ipynb
requirements.txt+3-1
src/__init__.pyAdded
src/common/__init__.pyAdded
src/common/method_registry.pyAdded+79
src/data_store.pyAdded+114
src/pages/MethodDetails.py+106-87
src/pages/RawData.pyAdded+72
src/pages/__init__.pyAdded
src/streamlit_app.py+306-207