Redesign dashboard around leaderboard
Browse filesFiles changed (3)
- README.md+7-8
- app.py+956-689
- assets/styles.css+174-87
123456789101112131415161718---title: BenchDashsdk: dockerapp_port: 7860---# BenchDashInteractive result dashboard for the Tang Lab neural-behavioral modelbenchmark.The dashboard summarizes exported benchmark results across five datasets and23 model variants, including clean prediction, count-noise robustness,cross-session latent consistency, attribution analyses, and compute cost.The bundled files in `data/` are lightweight summary exports for interactiveinspection. The full benchmark artifacts and reproduction workflow live in themain benchmark repository.1234567891011121314151617---title: Neural Model Benchmarksdk: dockerapp_port: 7860---# Neural Model BenchmarkInteractive dashboard for the Tang Lab neural model benchmark.The dashboard compares 23 methods across five datasets, with sortable taskperformance, robustness, cross-session alignment, neuron and trial influence,compute cost, and 3D latent-space views.The bundled files in `data/` are lightweight summary tables for interactiveinspection. The full benchmark artifacts and reproduction workflow live in themain benchmark repository.
12345678910111 unmodified line131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616213 unmodified lines7677787980818 unmodified lines90919293949596974 unmodified lines10210310410510610710810923 unmodified lines13313413513613713817 unmodified lines1561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252266 unmodified lines23323423523623723823924024124224324424524624724824925025125225325425525625725825926026111 unmodified lines2732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183 unmodified lines3223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923936 unmodified lines4004014024034044054064074084094104114121 unmodified line41441541641741841942042142212 unmodified lines4354364374384394404414427 unmodified lines4504514524534544554564574584594604614624634644654664674681 unmodified line47047147247347447547647747813 unmodified lines4924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985993 unmodified lines6036046056066076086096106116121 unmodified line6146156166176186196206216226236246256266276286295 unmodified lines6356366376386396406416426436442 unmodified lines6476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617625 unmodified lines76876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148from __future__ import annotationsfrom pathlib import Pathfrom typing import Iterableimport numpy as npimport pandas as pdimport plotly.express as pximport plotly.graph_objects as gofrom dash import Dash, Input, Output, dash_table, dcc, htmlfrom plotly.subplots import make_subplots1 unmodified lineDATA_DIR = Path(__file__).resolve().parent / "data"MODEL_INFO = {"blend": ("gpu", "full_pipeline", "pytorch_gpu.sif", "stage1, stage2, comprehensive, consistency, neuron_shap"),"blend_ndt": ("gpu", "full_pipeline", "pytorch_gpu.sif", "stage1, stage2, comprehensive, neuron_shap"),"cebra": ("gpu", "full_pipeline", "pytorch_gpu.sif", "stage1, stage2, comprehensive, consistency, neuron_shap"),"dnn": ("gpu", "comprehensive_only", "tensorflow_gpu.sif", "stage1, stage2, comprehensive, neuron_shap"),"dpad": ("gpu", "full_pipeline", "tensorflow_gpu.sif", "comprehensive, consistency, neuron_shap"),"gpfa": ("cpu", "full_pipeline", "sklearn_cpu.sif", "stage1, stage2, comprehensive, consistency, neuron_shap"),"gru": ("gpu", "comprehensive_only", "tensorflow_gpu.sif", "stage1, stage2, comprehensive, neuron_shap"),"langevinflow_ccn": ("gpu", "full_pipeline", "pytorch_gpu.sif", "stage1, stage2, comprehensive, neuron_shap"),"ldns": ("gpu", "full_pipeline", "pytorch_gpu.sif", "stage1, stage2, comprehensive, consistency, neuron_shap"),"lfads_torch": ("gpu", "full_pipeline", "lfads_torch.sif", "stage1, stage2, comprehensive, consistency, neuron_shap"),"lstm": ("gpu", "comprehensive_only", "tensorflow_gpu.sif", "stage1, stage2, comprehensive, neuron_shap"),"marble": ("gpu", "full_pipeline", "marble_h100.sif", "stage1, stage2, comprehensive, consistency, neuron_shap"),"mint": ("cpu", "comprehensive_only", "mint.sif", "comprehensive, neuron_shap, robustness"),"neds": ("gpu", "full_pipeline", "neds.sif", "stage1, stage2, comprehensive, neuron_shap"),"neds_pretrained": ("gpu", "full_pipeline", "neds.sif", "stage1, stage2, comprehensive, neuron_shap"),"neuro_behavior_conditioning": ("gpu", "full_pipeline", "pytorch_gpu.sif", "comprehensive, consistency, neuron_shap"),"pca": ("cpu", "full_pipeline", "sklearn_cpu.sif", "stage1, stage2, comprehensive, consistency, neuron_shap"),"rnn": ("gpu", "comprehensive_only", "tensorflow_gpu.sif", "stage1, stage2, comprehensive, neuron_shap"),"smc_rnns": ("gpu", "full_pipeline", "pytorch_gpu.sif", "stage1, stage2, comprehensive, consistency, neuron_shap"),"svc": ("cpu", "comprehensive_only", "sklearn_cpu.sif", "comprehensive, neuron_shap"),"tndm": ("gpu", "full_pipeline", "tensorflow_gpu.sif", "stage1, stage2, comprehensive, consistency, neuron_shap"),"torchdfine": ("gpu", "full_pipeline", "pytorch_gpu.sif", "comprehensive, consistency, neuron_shap"),"xg": ("cpu", "comprehensive_only", "sklearn_cpu.sif", "comprehensive, neuron_shap"),}DEFAULT_MODELS = ["pca","gpfa","cebra","dpad","ldns","lfads_torch","marble","rnn","svc","xg",]def load_csv(name: str) -> pd.DataFrame:path = DATA_DIR / nameif not path.exists():raise FileNotFoundError(f"Missing bundled dashboard data: {path}")return pd.read_csv(path)13 unmodified linesreturn df[df["status"].fillna("") == "present"].copy()def ordered_unique(values: Iterable[object]) -> list[str]:seen: set[str] = set()out: list[str] = []8 unmodified linesdef build_dataset_labels() -> dict[str, str]:if prediction.empty:return {}pairs = (prediction[["dataset", "dataset_display"]].dropna(subset=["dataset"])4 unmodified linesDATASET_LABELS = build_dataset_labels()DATASETS = ordered_unique(prediction.get("dataset", pd.Series(dtype=str)))MODELS = sorted(set(prediction.get("model", pd.Series(dtype=str)).dropna().astype(str)) | set(MODEL_INFO))DEFAULT_SELECTED_MODELS = [m for m in DEFAULT_MODELS if m in MODELS] or MODELS[:10]CONDITION_LABELS = {"monkey": {23 unmodified lines}def condition_sort_key(value: object) -> tuple[int, float | str]:try:return (0, float(value))17 unmodified linesreturn textdef model_metadata_frame() -> pd.DataFrame:rows = []present = present_rows(prediction)coverage = (present.groupby("model")["dataset"].nunique().rename("present_datasets").to_dict()if not present.emptyelse {})for model in MODELS:accelerator, pipeline, container, stages = MODEL_INFO.get(model, ("unknown", "unknown", "unknown", ""))rows.append({"model": model,"accelerator": accelerator,"pipeline": pipeline,"container": container,"present_datasets": int(coverage.get(model, 0)),"expected_datasets": len(DATASETS),"stages": stages,})return pd.DataFrame(rows).sort_values(["accelerator", "pipeline", "model"])model_inventory = model_metadata_frame()def compact_number(value: float | int | None, *, digits: int = 3) -> str:if value is None or pd.isna(value):return ""value = float(value)if abs(value) >= 1000:return f"{value:,.0f}"return f"{value:.{digits}g}"def selected_models(models: list[str] | None) -> list[str]:if not models:return MODELSreturn [m for m in models if m in MODELS]def filter_models(df: pd.DataFrame, models: list[str] | None) -> pd.DataFrame:if df.empty or "model" not in df.columns:return df.copy()chosen = selected_models(models)return df[df["model"].astype(str).isin(chosen)].copy()def fig_layout(fig: go.Figure, *, height: int = 420) -> go.Figure:fig.update_layout(height=height,paper_bgcolor="white",plot_bgcolor="white",margin=dict(l=18, r=18, t=54, b=36),font=dict(family="Inter, Arial, sans-serif", size=13, color="#1f2933"),legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="left", x=0),)fig.update_xaxes(showgrid=True, gridcolor="#e8edf1", zerolinecolor="#cfd8df")fig.update_yaxes(showgrid=True, gridcolor="#e8edf1", zerolinecolor="#cfd8df")return fig6 unmodified linesxref="paper",yref="paper",showarrow=False,font=dict(size=15, color="#536471"),)fig.update_xaxes(visible=False)fig.update_yaxes(visible=False)return fig_layout(fig)def latent_fig_layout(fig: go.Figure, *, height: int) -> go.Figure:fig.update_layout(height=height,paper_bgcolor="white",plot_bgcolor="white",margin=dict(l=8, r=8, t=76, b=84),font=dict(family="Inter, Arial, sans-serif", size=13, color="#1f2933"),legend=dict(orientation="h",yanchor="top",y=-0.08,xanchor="left",x=0,),)return figdef parse_float_list(value: object) -> list[float]:11 unmodified linesreturn outdef latent_space_figure(dataset: str, models: list[str] | None) -> go.Figure:if latent_samples.empty:return empty_figure("Latent-space samples are not packaged for this build.")chosen = selected_models(models)df = latent_samples[(latent_samples["dataset"].astype(str) == str(dataset))& (latent_samples["model"].astype(str).isin(chosen))].copy()if df.empty:label = DATASET_LABELS.get(dataset, dataset)return empty_figure(f"Latent-space samples are not available for {label}.")score_df = consistency.copy()if "is_active_model" in score_df.columns:score_df = score_df[score_df["is_active_model"].astype(str).str.lower() == "true"]score_df = score_df[(score_df["dataset"].astype(str) == str(dataset))& (score_df["model"].astype(str).isin(df["model"].astype(str).unique()))].copy()if not score_df.empty:score_df["mean_r2"] = pd.to_numeric(score_df["mean_r2"], errors="coerce")model = (score_df.sort_values("mean_r2", ascending=False)["model"].astype(str).iloc[0])else:model = sorted(df["model"].astype(str).unique())[0]plot_df = df[df["model"].astype(str) == model].copy()for col in ["x", "y", "z"]:plot_df[col] = pd.to_numeric(plot_df[col], errors="coerce")plot_df["condition_num"] = pd.to_numeric(plot_df["condition"], errors="coerce")plot_df["condition_label"] = plot_df["condition"].map(lambda value: condition_label(dataset, value))plot_df = plot_df.dropna(subset=["x", "y", "z"])if plot_df.empty:return empty_figure("Latent-space samples are empty after filtering.")trajectory_df = latent_trajectories[(latent_trajectories["dataset"].astype(str) == str(dataset))3 unmodified linesif col in trajectory_df:trajectory_df[col] = pd.to_numeric(trajectory_df[col], errors="coerce")if not trajectory_df.empty:trajectory_df["condition_label"] = trajectory_df["condition"].map(lambda value: condition_label(dataset, value))trajectory_df = trajectory_df.dropna(subset=["x", "y", "z"])sessions = ordered_unique(plot_df["session_label"])n_cols = 2n_rows = int(np.ceil(len(sessions) / n_cols))fig = make_subplots(rows=n_rows,cols=n_cols,specs=[[{"type": "scene"} for _ in range(n_cols)] for _ in range(n_rows)],subplot_titles=sessions,horizontal_spacing=0.035,vertical_spacing=0.105,)condition_values = sorted(plot_df["condition"].astype(str).unique(),key=condition_sort_key,)use_categorical_conditions = len(condition_values) <= 12direction_palette = ["#B23AEE","#3B1C54","#2DD4F6","#289285","#E3D724","#00A65A","#5B8FF9","#F97316","#E45756","#72B7B2","#54A24B","#B279A2",]condition_colors = {condition: direction_palette[idx % len(direction_palette)]for idx, condition in enumerate(condition_values)}if dataset == "monkey":condition_prefix = "Reach direction"elif dataset == "ratinabox":condition_prefix = "Position bin"elif dataset == "allen_neuropixels":condition_prefix = "Orientation"elif dataset == "speech":condition_prefix = "Cue"else:condition_prefix = "Condition"for session_idx, session in enumerate(sessions):session_df = plot_df[plot_df["session_label"].astype(str) == session]if session_df.empty:continuerow = session_idx // n_cols + 1col = session_idx % n_cols + 1if use_categorical_conditions:for condition in condition_values:cond_df = session_df[session_df["condition"].astype(str) == condition]if cond_df.empty:continuetrace_name = condition_label(dataset, condition)session_traj = trajectory_df[(trajectory_df["session_label"].astype(str) == session)& (trajectory_df["condition"].astype(str) == condition)].sort_values("time_index")fig.add_trace(6 unmodified lineslegendgroup=condition,showlegend=session_idx == 0,marker=dict(size=1.9 if not session_traj.empty else 2.6,opacity=0.28 if not session_traj.empty else 0.72,color=condition_colors[condition],),customdata=np.stack([cond_df["session_label"].astype(str),cond_df["condition_label"].astype(str),cond_df["trial_index"].astype(str),cond_df["time_index"].astype(str),1 unmodified lineaxis=-1,),hovertemplate=("session=%{customdata[0]}<br>"f"{condition_prefix.lower()}=%{{customdata[1]}}<br>""trial=%{customdata[2]} time=%{customdata[3]}""<extra></extra>"),),12 unmodified linesshowlegend=False,line=dict(color=condition_colors[condition], width=5),hovertemplate=(f"{condition_prefix.lower()}={trace_name}<br>""time=%{customdata}<extra></extra>"),customdata=session_traj["time_index"],),7 unmodified linesy=session_df["y"],z=session_df["z"],mode="markers",name=session,showlegend=False,marker=dict(size=2.6,opacity=0.72,color=session_df["condition_num"],colorscale="Viridis",showscale=session_idx == 0,colorbar=dict(title=condition_prefix),),customdata=np.stack([session_df["condition"].astype(str),session_df["condition"].map(lambda value: condition_label(dataset, value)).astype(str),session_df["trial_index"].astype(str),session_df["time_index"].astype(str),1 unmodified lineaxis=-1,),hovertemplate=("session=%{fullData.name}<br>"f"{condition_prefix.lower()}=%{{customdata[1]}}<br>""trial=%{customdata[2]} time=%{customdata[3]}""<extra></extra>"),),13 unmodified linesfig.update_layout(**{scene_id: dict(xaxis=dict(title="",range=[-lim, lim],showgrid=False,zeroline=False,showticklabels=False,),yaxis=dict(title="",range=[-lim, lim],showgrid=False,zeroline=False,showticklabels=False,),zaxis=dict(title="",range=[-lim, lim],showgrid=False,zeroline=False,showticklabels=False,),aspectmode="cube",bgcolor="#ffffff",camera=dict(eye=dict(x=1.55, y=1.45, z=1.05)),)})score = Noneif not score_df.empty and model in set(score_df["model"].astype(str)):score = float(score_df.loc[score_df["model"].astype(str) == model, "mean_r2"].iloc[0])score_text = "" if score is None or pd.isna(score) else f" (mean R2={score:.2f})"fig.update_layout(title=(f"{DATASET_LABELS.get(dataset, dataset)} latent samples: {model}{score_text}"),)fig.for_each_annotation(lambda ann: ann.update(font=dict(size=11, color="#536271")))fig.update_layout(legend=dict(title=condition_prefix))return latent_fig_layout(fig, height=720 if n_rows > 1 else 430)def dataframe_table(table_id: str,*,columns: list[str] | None = None,data: list[dict] | None = None,page_size: int = 12,) -> dash_table.DataTable:return dash_table.DataTable(id=table_id,columns=[{"name": c, "id": c} for c in (columns or [])],data=data or [],page_size=page_size,sort_action="native",filter_action="native",style_table={"overflowX": "auto"},style_header={"backgroundColor": "#f6f8fa","fontWeight": "700","border": "1px solid #d9e2e8",},style_cell={"fontFamily": "Inter, Arial, sans-serif","fontSize": "13px","padding": "9px","textAlign": "left","minWidth": "100px","maxWidth": "280px","whiteSpace": "normal","height": "auto","border": "1px solid #e6edf2",},)def stat_card(label: str, value: str, detail: str) -> html.Div:return html.Div([html.Div(label, className="stat-label"),html.Div(value, className="stat-value"),html.Div(detail, className="stat-detail"),],className="stat-card",)def panel(title: str, *children, subtitle: str | None = None) -> html.Div:heading = [html.H2(title)]if subtitle:heading.append(html.P(subtitle, className="panel-subtitle"))return html.Div([html.Div(heading, className="panel-heading"), *children], className="panel")present_prediction = present_rows(prediction)present_cells = len(present_prediction)total_cells = len(prediction)coverage_text = f"{present_cells}/{total_cells}" if total_cells else "0/0"coverage_pct = 100.0 * present_cells / total_cells if total_cells else 0.0runtime_counts = model_inventory["accelerator"].value_counts().to_dict()app = Dash(__name__, title="BenchDash")server = app.serverapp.layout = html.Div(3 unmodified lineshtml.Div([html.Div("Tang Lab", className="eyebrow"),html.H1("Benchmark results"),html.P("Compare neural-behavioral models across prediction, robustness, ""cross-session latent geometry, attribution, and compute cost.",className="lede",),],1 unmodified line),html.Div([stat_card("Models", str(len(MODELS)), "registered benchmark methods"),stat_card("Datasets", str(len(DATASETS)), "neural-behavioral tasks"),stat_card("Result Coverage", coverage_text, f"{coverage_pct:.1f}% complete"),stat_card("Compute Mix",f"{runtime_counts.get('cpu', 0)} CPU / {runtime_counts.get('gpu', 0)} GPU","registered model runtimes",),],className="stat-grid",),],className="hero",5 unmodified lineshtml.Label("Dataset"),dcc.Dropdown(id="dataset-filter",options=[{"label": DATASET_LABELS.get(ds, ds), "value": ds}for ds in DATASETS],value=DATASETS[0] if DATASETS else None,clearable=False,),2 unmodified lines),html.Div([html.Label("Models"),dcc.Dropdown(id="model-filter",options=[{"label": m, "value": m} for m in MODELS],value=DEFAULT_SELECTED_MODELS,multi=True,placeholder="Clear to show all models",),],className="control control-wide",),],className="controls",),dcc.Tabs(id="tabs",value="prediction",className="tabs",children=[dcc.Tab(label="Overview",value="prediction",children=[panel("Clean Prediction Scores",dcc.Graph(id="prediction-heatmap", config={"displayModeBar": False}),dcc.Graph(id="prediction-ranking", config={"displayModeBar": False}),dataframe_table("prediction-table"),subtitle="Scores are shown within dataset. Regression tasks use R2; classification tasks use accuracy.",)],),dcc.Tab(label="Robustness",value="robustness",children=[panel("Count-Noise Robustness",dcc.Graph(id="robustness-curve", config={"displayModeBar": False}),dataframe_table("robustness-table"),subtitle="Curves show score as deterministic count noise increases from the clean condition.",)],),dcc.Tab(label="Consistency",value="consistency",children=[panel("Cross-Session Latent Consistency",dcc.Graph(id="latent-space",config={"displayModeBar": "hover","toImageButtonOptions": {"format": "png","filename": "benchdash_latent_space","height": 900,"width": 1200,"scale": 2,},},),dcc.Graph(id="consistency-bars", config={"displayModeBar": False}),dcc.Graph(id="consistency-heatmap", config={"displayModeBar": False}),dataframe_table("consistency-table"),subtitle="Latent clouds show sampled 3D embeddings from real consistency artifacts. Scores summarize cross-session alignment.",)],),dcc.Tab(label="Runtime",value="runtime",children=[panel("Score, Time, and Memory",dcc.Graph(id="runtime-scatter", config={"displayModeBar": False}),dcc.Graph(id="memory-bars", config={"displayModeBar": False}),dataframe_table("runtime-table"),subtitle="Training time and memory are summarized from benchmark run metadata.",)],),dcc.Tab(label="Attribution",value="attribution",children=[panel("Perturbation and Attribution Summaries",dcc.Graph(id="neuron-shap-bars", config={"displayModeBar": False}),dcc.Graph(id="trial-shapley-bars", config={"displayModeBar": False}),dataframe_table("attribution-table"),subtitle="Signed SHAP and trial-Shapley summaries are shown without absolute-value ranking.",)],),dcc.Tab(label="Methods",value="coverage",children=[panel("Model and Analysis Coverage",dcc.Graph(id="coverage-bars", config={"displayModeBar": False}),dataframe_table("coverage-table",columns=list(model_inventory.columns),data=model_inventory.to_dict("records"),page_size=25,),subtitle="Coverage reports which methods have exported benchmark summaries in this dashboard.",)],),5 unmodified lines@app.callback(Output("prediction-heatmap", "figure"),Output("prediction-ranking", "figure"),Output("prediction-table", "columns"),Output("prediction-table", "data"),Input("dataset-filter", "value"),Input("model-filter", "value"),)def update_prediction(dataset: str, models: list[str] | None):df_all = filter_models(prediction, models)if df_all.empty:cols = [{"name": c, "id": c} for c in ["model", "dataset", "status", "score"]]return empty_figure("No prediction rows found."), empty_figure("No selected models."), cols, []heat_df = df_all.copy()heat_df["score"] = pd.to_numeric(heat_df["score"], errors="coerce")heat_df["dataset_label"] = heat_df["dataset"].map(DATASET_LABELS).fillna(heat_df["dataset"])pivot = heat_df.pivot_table(index="model", columns="dataset_label", values="score", aggfunc="first")if not pivot.empty:preferred = [m for m in selected_models(models) if m in pivot.index]remaining = [m for m in sorted(pivot.index.astype(str)) if m not in preferred]pivot = pivot.loc[preferred + remaining]dataset_order = [DATASET_LABELS.get(ds, ds) for ds in DATASETS if DATASET_LABELS.get(ds, ds) in pivot.columns]pivot = pivot.reindex(columns=dataset_order)text = pivot.map(lambda x: "" if pd.isna(x) else f"{x:.3f}") if not pivot.empty else pivotzmin = min(0.0, float(np.nanmin(pivot.values))) if pivot.size and not np.isnan(pivot.values).all() else 0.0zmax = max(1.0, float(np.nanmax(pivot.values))) if pivot.size and not np.isnan(pivot.values).all() else 1.0heatmap = go.Figure(go.Heatmap(z=pivot.values if not pivot.empty else [[]],x=list(pivot.columns),y=list(pivot.index),text=text.values if not pivot.empty else [[]],texttemplate="%{text}",colorscale=[[0.0, "#b85c38"], [0.5, "#f7f2e8"], [1.0, "#176b5a"]],zmin=zmin,zmax=zmax,colorbar=dict(title="score"),hovertemplate="model=%{y}<br>dataset=%{x}<br>score=%{z:.4f}<extra></extra>",))heatmap.update_layout(title="Clean-score matrix by dataset")fig_layout(heatmap, height=max(430, 28 * len(pivot.index) + 170))rank_df = present_rows(df_all)rank_df = rank_df[rank_df["dataset"] == dataset].copy()rank_df["score"] = pd.to_numeric(rank_df["score"], errors="coerce")rank_df = rank_df.dropna(subset=["score"]).sort_values("score", ascending=True)if rank_df.empty:ranking = empty_figure(f"No clean prediction rows for {DATASET_LABELS.get(dataset, dataset)}.")else:metric = ordered_unique(rank_df["metric"])[0]ranking = go.Figure(go.Bar(x=rank_df["score"],y=rank_df["model"],orientation="h",marker=dict(color=rank_df["score"], colorscale="Teal", colorbar=dict(title=metric)),hovertemplate="model=%{y}<br>score=%{x:.4f}<extra></extra>",))ranking.update_layout(title=f"{DATASET_LABELS.get(dataset, dataset)} ranking ({metric})")ranking.update_xaxes(title=metric)ranking.update_yaxes(title="")fig_layout(ranking, height=max(420, 27 * len(rank_df) + 160))table_cols = ["model","dataset_display","status","metric","score","decoder","latent_dim","n_train_trials","n_test_trials","n_neurons",]table_df = df_all[df_all["dataset"] == dataset].copy()for col in ["score", "latent_dim", "n_train_trials", "n_test_trials", "n_neurons"]:if col in table_df:table_df[col] = table_df[col].map(lambda v: compact_number(v))table_df = table_df[[c for c in table_cols if c in table_df.columns]]return (heatmap,ranking,[{"name": c, "id": c} for c in table_df.columns],table_df.to_dict("records"),)@app.callback(Output("robustness-curve", "figure"),Output("robustness-table", "columns"),Output("robustness-table", "data"),Input("dataset-filter", "value"),Input("model-filter", "value"),)def update_robustness(dataset: str, models: list[str] | None):df = filter_models(present_rows(robustness), models)df = df[df["dataset"] == dataset].copy() if not df.empty else dfif df.empty:cols = [{"name": c, "id": c} for c in ["model", "metric", "raw_auc", "score_at_noise0"]]return empty_figure("No robustness rows for this selection."), cols, []fig = go.Figure()for row in df.sort_values("model").itertuples():xs = parse_float_list(row.noise_levels)ys = parse_float_list(row.scores)if xs and len(xs) == len(ys):fig.add_trace(go.Scatter(x=xs,y=ys,mode="lines+markers",name=row.model,hovertemplate="noise=%{x:.2f}<br>score=%{y:.4f}<extra></extra>",))fig.update_layout(title=f"{DATASET_LABELS.get(dataset, dataset)} robustness curves")fig.update_xaxes(title="noise fraction")fig.update_yaxes(title=ordered_unique(df["metric"])[0] if "metric" in df else "score")fig_layout(fig, height=520)table_cols = ["model", "metric", "score_at_noise0", "score_at_max_noise", "raw_auc", "mean_score"]table_df = df[table_cols].copy()for col in ["score_at_noise0", "score_at_max_noise", "raw_auc", "mean_score"]:table_df[col] = table_df[col].map(lambda v: compact_number(v))return fig, [{"name": c, "id": c} for c in table_df.columns], table_df.to_dict("records")@app.callback(Output("latent-space", "figure"),Output("consistency-bars", "figure"),Output("consistency-heatmap", "figure"),Output("consistency-table", "columns"),Output("consistency-table", "data"),Input("dataset-filter", "value"),Input("model-filter", "value"),)def update_consistency(dataset: str, models: list[str] | None):latent_fig = latent_space_figure(dataset, models)df_all = filter_models(consistency, models)if "is_active_model" in df_all.columns:df_all = df_all[df_all["is_active_model"].astype(str).str.lower() == "true"]df = df_all[df_all["dataset"] == dataset].copy() if not df_all.empty else df_allif df.empty:cols = [{"name": c, "id": c} for c in ["model", "dataset", "mean_r2"]]return (latent_fig,empty_figure("Consistency analysis is not available for this dataset."),empty_figure("Consistency analysis is not available for this dataset."),cols,[],)df["mean_r2"] = pd.to_numeric(df["mean_r2"], errors="coerce")bar_df = df.sort_values("mean_r2", ascending=True)bars = go.Figure(go.Bar(x=bar_df["mean_r2"],y=bar_df["model"],orientation="h",marker=dict(color=bar_df["mean_r2"], colorscale="Bluyl"),hovertemplate="model=%{y}<br>R2=%{x:.4f}<extra></extra>",))bars.update_layout(title=f"{DATASET_LABELS.get(dataset, dataset)} cross-session alignment")bars.update_xaxes(title="mean R2")fig_layout(bars, height=max(420, 27 * len(bar_df) + 150))heat = df_all.copy()heat["mean_r2"] = pd.to_numeric(heat["mean_r2"], errors="coerce")heat["dataset_label"] = heat["dataset"].map(DATASET_LABELS).fillna(heat["dataset"])pivot = heat.pivot_table(index="model", columns="dataset_label", values="mean_r2", aggfunc="first")if not pivot.empty:pivot = pivot.loc[pivot.mean(axis=1, skipna=True).sort_values(ascending=False).index]text = pivot.map(lambda x: "" if pd.isna(x) else f"{x:.2f}") if not pivot.empty else pivotheatmap = go.Figure(go.Heatmap(z=pivot.values if not pivot.empty else [[]],x=list(pivot.columns),y=list(pivot.index),text=text.values if not pivot.empty else [[]],texttemplate="%{text}",colorscale=[[0.0, "#b85c38"], [0.5, "#f7f2e8"], [1.0, "#176b5a"]],colorbar=dict(title="R2"),hovertemplate="model=%{y}<br>dataset=%{x}<br>R2=%{z:.4f}<extra></extra>",))heatmap.update_layout(title="Consistency matrix")fig_layout(heatmap, height=max(410, 28 * len(pivot.index) + 160))table_cols = ["model","dataset","n_sessions","latent_dim","mean_r2","n_pairwise","scoring_modes",]table_df = df[[c for c in table_cols if c in df.columns]].copy()for col in ["mean_r2", "latent_dim", "n_sessions", "n_pairwise"]:if col in table_df:table_df[col] = table_df[col].map(lambda v: compact_number(v))return (latent_fig,bars,heatmap,[{"name": c, "id": c} for c in table_df.columns],table_df.to_dict("records"),)@app.callback(Output("runtime-scatter", "figure"),Output("memory-bars", "figure"),Output("runtime-table", "columns"),Output("runtime-table", "data"),Input("dataset-filter", "value"),Input("model-filter", "value"),)def update_runtime(dataset: str, models: list[str] | None):df = filter_models(present_rows(scalability), models)df = df[df["dataset"] == dataset].copy() if not df.empty else dfif df.empty:cols = [{"name": c, "id": c} for c in ["model", "training_time_sec", "peak_ram_gb"]]return empty_figure("No runtime rows for this selection."), empty_figure("No memory rows."), cols, []pred = present_rows(prediction)[["model", "dataset", "score", "metric"]].copy()df = df.merge(pred, on=["model", "dataset"], how="left")for col in ["training_time_sec", "inference_time_sec", "peak_ram_gb", "peak_vram_gb", "score"]:df[col] = pd.to_numeric(df[col], errors="coerce")df["accelerator"] = df["model"].map(lambda m: MODEL_INFO.get(m, ("unknown", "", "", ""))[0])df["pipeline"] = df["model"].map(lambda m: MODEL_INFO.get(m, ("", "unknown", "", ""))[1])scatter = px.scatter(df,x="training_time_sec",y="score",size="peak_ram_gb",color="accelerator",symbol="pipeline",hover_name="model",hover_data={"training_time_sec": ":.3f","inference_time_sec": ":.3f","peak_ram_gb": ":.3f","peak_vram_gb": ":.3f","score": ":.4f",},log_x=True,title=f"{DATASET_LABELS.get(dataset, dataset)} score vs training time",)scatter.update_xaxes(title="training time (sec, log)")scatter.update_yaxes(title=ordered_unique(df["metric"].dropna())[0] if df["metric"].notna().any() else "score")fig_layout(scatter, height=500)mem_df = df.sort_values("peak_ram_gb", ascending=True)memory = go.Figure()memory.add_trace(go.Bar(x=mem_df["peak_ram_gb"], y=mem_df["model"], orientation="h", name="RAM GB"))memory.add_trace(go.Bar(x=mem_df["peak_vram_gb"], y=mem_df["model"], orientation="h", name="VRAM GB"))memory.update_layout(title=f"{DATASET_LABELS.get(dataset, dataset)} peak memory", barmode="group")memory.update_xaxes(title="GB")fig_layout(memory, height=max(420, 29 * len(mem_df) + 160))table_cols = ["model","accelerator","score","training_time_sec","inference_time_sec","peak_ram_gb","peak_vram_gb",]table_df = df[table_cols].copy()for col in ["score", "training_time_sec", "inference_time_sec", "peak_ram_gb", "peak_vram_gb"]:table_df[col] = table_df[col].map(lambda v: compact_number(v))return scatter, memory, [{"name": c, "id": c} for c in table_df.columns], table_df.to_dict("records")@app.callback(Output("neuron-shap-bars", "figure"),Output("trial-shapley-bars", "figure"),Output("attribution-table", "columns"),Output("attribution-table", "data"),Input("dataset-filter", "value"),Input("model-filter", "value"),)def update_attribution(dataset: str, models: list[str] | None):nshap = filter_models(neuron_shap, models)if "is_active_model" in nshap.columns:nshap = nshap[nshap["is_active_model"].astype(str).str.lower() == "true"]nshap = nshap[nshap["dataset"] == dataset].copy() if not nshap.empty else nshapif nshap.empty:nshap_fig = empty_figure("No neuron-SHAP rows for this dataset.")else:nshap["auc"] = pd.to_numeric(nshap["auc"], errors="coerce")bar_df = nshap.dropna(subset=["auc"]).sort_values("auc", ascending=True)nshap_fig = go.Figure(go.Bar(x=bar_df["auc"],y=bar_df["model"],orientation="h",marker=dict(color=bar_df["auc"], colorscale="Teal"),hovertemplate="model=%{y}<br>AUC=%{x:.4f}<extra></extra>",))nshap_fig.update_layout(title=f"{DATASET_LABELS.get(dataset, dataset)} neuron perturbation AUC")nshap_fig.update_xaxes(title="AUC")fig_layout(nshap_fig, height=max(420, 27 * len(bar_df) + 150))tshap = filter_models(trial_shapley, models)if "is_active_model" in tshap.columns:tshap = tshap[tshap["is_active_model"].astype(str).str.lower() == "true"]tshap = tshap[tshap["dataset"] == dataset].copy() if not tshap.empty else tshapif tshap.empty:tshap_fig = empty_figure("No trial-Shapley rows for this dataset.")else:tshap["perturbation_auc"] = pd.to_numeric(tshap["perturbation_auc"], errors="coerce")trial_df = tshap.dropna(subset=["perturbation_auc"]).sort_values("perturbation_auc", ascending=True)tshap_fig = go.Figure(go.Bar(x=trial_df["perturbation_auc"],y=trial_df["model"],orientation="h",marker=dict(color=trial_df["perturbation_auc"], colorscale="Bluyl"),hovertemplate="model=%{y}<br>perturbation AUC=%{x:.4f}<extra></extra>",))tshap_fig.update_layout(title=f"{DATASET_LABELS.get(dataset, dataset)} trial-Shapley perturbation AUC")tshap_fig.update_xaxes(title="perturbation AUC")fig_layout(tshap_fig, height=max(420, 27 * len(trial_df) + 150))table_cols = ["model","dataset","metric","baseline_score","full_model_score","auc","spearman_corr","shap_mean_value","shap_fraction_positive",]table_df = nshap[[c for c in table_cols if c in nshap.columns]].copy()for col in table_df.columns:if col not in {"model", "dataset", "metric"}:table_df[col] = table_df[col].map(lambda v: compact_number(v))return nshap_fig, tshap_fig, [{"name": c, "id": c} for c in table_df.columns], table_df.to_dict("records")@app.callback(Output("coverage-bars", "figure"), Input("model-filter", "value"))def update_coverage(models: list[str] | None):df = filter_models(model_inventory, models)if df.empty:return empty_figure("No models selected.")counts = (df.groupby(["accelerator", "pipeline"]).size().reset_index(name="n_models").sort_values("n_models", ascending=False))fig = px.bar(counts,x="pipeline",y="n_models",color="accelerator",barmode="group",text="n_models",title="Registered model runtimes",)fig.update_xaxes(title="")fig.update_yaxes(title="models")return fig_layout(fig, height=420)if __name__ == "__main__":12345678910111 unmodified line13141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318413 unmodified lines1981992002012022032042052062072082098 unmodified lines2182192202212222234 unmodified lines22822923023123223323423523623723 unmodified lines26126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229317 unmodified lines3113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004016 unmodified lines40840941041141241341441541641741811 unmodified lines4304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327333 unmodified lines7377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837846 unmodified lines7917927937947957967977987998008018028031 unmodified line80580680780880981081181281312 unmodified lines8268278288298308318328337 unmodified lines8418428438448458468478488498508518528538548558568578588591 unmodified line86186286386486586686786886913 unmodified lines8838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311043 unmodified lines1108110911101111111211131114111511161 unmodified line11181119112011211122112311241125112611275 unmodified lines11331134113511361137113811392 unmodified lines114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812995 unmodified lines130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415from __future__ import annotationsimport refrom pathlib import Pathfrom typing import Iterableimport numpy as npimport pandas as pdimport plotly.graph_objects as gofrom dash import Dash, Input, Output, dash_table, dcc, htmlfrom plotly.subplots import make_subplots1 unmodified lineDATA_DIR = Path(__file__).resolve().parent / "data"PAPER_MODEL_ORDER = ["blend","blend_ndt","cebra","dnn","dpad","gpfa","gru","langevinflow_ccn","ldns","lfads_torch","lstm","marble","mint","neds","neds_pretrained","neuro_behavior_conditioning","pca","rnn","smc_rnns","svc","tndm","torchdfine","xg",]DISPLAY_NAMES = {"blend": "BLEND-LFADS","blend_ndt": "BLEND-NDT","cebra": "CEBRA","dnn": "DNN","dpad": "DPAD","gpfa": "GPFA","gru": "GRU","langevinflow_ccn": "LangevinFlow","ldns": "LDNS","lfads_torch": "AutoLFADS","lstm": "LSTM","marble": "MARBLE","mint": "MINT","neds": "NEDS","neds_pretrained": "NEDS-pt","neuro_behavior_conditioning": "mVAE","pca": "PCA","rnn": "RNN","smc_rnns": "SMC-RNN","svc": "SVC","tndm": "TNDM","torchdfine": "DFINE","xg": "XGBoost",}METHOD_FAMILY = {"pca": "Linear latent","gpfa": "Linear latent","dnn": "Supervised decoder","gru": "Supervised decoder","lstm": "Supervised decoder","rnn": "Supervised decoder","svc": "Supervised decoder","xg": "Supervised decoder","lfads_torch": "Sequential latent","dpad": "Sequential latent","torchdfine": "Sequential latent","smc_rnns": "Sequential latent","tndm": "Sequential latent","langevinflow_ccn": "Sequential latent","ldns": "Sequential latent","neuro_behavior_conditioning": "Sequential latent","blend": "Distillation","blend_ndt": "Distillation","neds": "Foundation model","neds_pretrained": "Foundation model","cebra": "Contrastive","marble": "Geometric","mint": "Non-parametric",}METHOD_HARDWARE = {"gpfa": "CPU","mint": "CPU","pca": "CPU","svc": "CPU","xg": "CPU",}TABLE_LABELS = {"rank": "Rank","method": "Method","family": "Family","hardware": "Hardware","metric": "Metric","task_score": "Task performance","score": "Task performance","robustness_auc": "Robustness AUC","alignment_score": "Cross-session alignment","training_time_sec": "Training time (s)","inference_time_sec": "Evaluation time (s)","peak_ram_gb": "Peak memory (GB)","peak_vram_gb": "Peak GPU memory (GB)","reference_score": "Reference score","highest_noise_score": "Highest-noise score","average_noisy_score": "Average noisy score","latent_dim": "Latent dimensions","n_sessions": "Sessions","n_pairwise": "Session pairs","baseline_score": "Baseline score","full_model_score": "Full-model score","neuron_influence_auc": "Neuron influence AUC","trial_influence_auc": "Trial influence AUC","shap_mean_value": "Mean signed neuron contribution","shap_fraction_positive": "Fraction positive","n_train_trials": "Training trials","n_test_trials": "Test trials","n_neurons": "Neurons","notes": "Notes",}NUMERIC_COLUMNS = {"task_score","score","robustness_auc","alignment_score","training_time_sec","inference_time_sec","peak_ram_gb","peak_vram_gb","reference_score","highest_noise_score","average_noisy_score","latent_dim","n_sessions","n_pairwise","baseline_score","full_model_score","neuron_influence_auc","trial_influence_auc","shap_mean_value","shap_fraction_positive","n_train_trials","n_test_trials","n_neurons",}RIGHT_ALIGNED_COLUMNS = NUMERIC_COLUMNS | {"rank"}SCORE_SCALE = [[0.0, "#9f3a38"], [0.5, "#f3efe4"], [1.0, "#006d77"]]CATEGORICAL_PALETTE = ["#0072B2","#E69F00","#009E73","#CC79A7","#D55E00","#56B4E9","#F0E442","#6A3D9A","#8C564B","#4E79A7","#59A14F","#AF7AA1",]def load_csv(name: str) -> pd.DataFrame:path = DATA_DIR / nameif not path.exists():raise FileNotFoundError(f"Missing dashboard data: {path}")return pd.read_csv(path)13 unmodified linesreturn df[df["status"].fillna("") == "present"].copy()def active_rows(df: pd.DataFrame) -> pd.DataFrame:if df.empty or "is_active_model" not in df.columns:return df.copy()return df[df["is_active_model"].astype(str).str.lower() == "true"].copy()def ordered_unique(values: Iterable[object]) -> list[str]:seen: set[str] = set()out: list[str] = []8 unmodified linesdef build_dataset_labels() -> dict[str, str]:pairs = (prediction[["dataset", "dataset_display"]].dropna(subset=["dataset"])4 unmodified linesDATASET_LABELS = build_dataset_labels()DATASETS = ordered_unique(prediction.get("dataset", pd.Series(dtype=str)))MODEL_SET = set(prediction.get("model", pd.Series(dtype=str)).dropna().astype(str))MODELS = [model for model in PAPER_MODEL_ORDER if model in MODEL_SET]MODELS += sorted(model for model in MODEL_SET if model not in set(MODELS))MODEL_RANK = {model: idx for idx, model in enumerate(MODELS)}CONDITION_LABELS = {"monkey": {23 unmodified lines}def model_label(model: object) -> str:if pd.isna(model):return ""text = str(model)return DISPLAY_NAMES.get(text, text)def model_sort_value(model: object) -> int:return MODEL_RANK.get(str(model), len(MODEL_RANK))def hardware_label(model: object) -> str:return METHOD_HARDWARE.get(str(model), "GPU")def selected_models(models: list[str] | None) -> list[str]:if not models:return MODELS.copy()return [model for model in MODELS if model in set(models)]def filter_models(df: pd.DataFrame, models: list[str] | None) -> pd.DataFrame:if df.empty or "model" not in df.columns:return df.copy()return df[df["model"].astype(str).isin(selected_models(models))].copy()def condition_sort_key(value: object) -> tuple[int, float | str]:try:return (0, float(value))17 unmodified linesreturn textdef condition_axis_label(dataset: str) -> str:return {"monkey": "Reach direction","allen_neuropixels": "Orientation","speech": "Cue","ratinabox": "Position bin",}.get(dataset, "Condition")def session_display_label(dataset: str, session: object) -> str:text = "" if pd.isna(session) else str(session)if dataset == "monkey":match = re.search(r"sub-([A-Za-z])_ses-CO-(\d{4})(\d{2})(\d{2})", text)if match:monkey, year, month, day = match.groups()return f"Monkey {monkey}, {year}-{month}-{day}"if dataset == "ratinabox":match = re.search(r"s(\d+)", text)if match:return f"Run {match.group(1)}"if dataset == "speech":return f"Session {text}"if dataset == "allen_neuropixels":return f"Session {text}"return text or "Session"def add_method_columns(df: pd.DataFrame) -> pd.DataFrame:out = df.copy()if "model" in out.columns:out["method"] = out["model"].map(model_label)out["model_order"] = out["model"].map(model_sort_value)return outdef round_numeric(df: pd.DataFrame, columns: Iterable[str], digits: int = 3) -> pd.DataFrame:out = df.copy()for col in columns:if col in out.columns:out[col] = pd.to_numeric(out[col], errors="coerce").round(digits)return outdef records(df: pd.DataFrame) -> list[dict]:clean = df.astype(object).where(pd.notna(df), None)return clean.to_dict("records")def column_defs(columns: Iterable[str]) -> list[dict]:out = []for col in columns:item = {"name": TABLE_LABELS.get(col, col), "id": col}if col in RIGHT_ALIGNED_COLUMNS:item["type"] = "numeric"out.append(item)return outdef metric_text(value: object) -> str:if pd.isna(value):return "score"return str(value)def value_text(value: object, digits: int = 3) -> str:if value is None or pd.isna(value):return "Not available"number = float(value)if abs(number) >= 1000:return f"{number:,.0f}"return f"{number:.{digits}f}"def fig_layout(fig: go.Figure, *, height: int = 420) -> go.Figure:fig.update_layout(height=height,paper_bgcolor="#ffffff",plot_bgcolor="#ffffff",margin=dict(l=22, r=22, t=52, b=38),font=dict(family="Inter, Arial, sans-serif", size=13, color="#17202a"),title=dict(font=dict(size=15, color="#17202a")),legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="left", x=0),)fig.update_xaxes(showgrid=True, gridcolor="#edf1f4", zerolinecolor="#d7e0e6")fig.update_yaxes(showgrid=True, gridcolor="#edf1f4", zerolinecolor="#d7e0e6")return fig6 unmodified linesxref="paper",yref="paper",showarrow=False,font=dict(size=15, color="#637381"),)fig.update_xaxes(visible=False)fig.update_yaxes(visible=False)return fig_layout(fig, height=360)def parse_float_list(value: object) -> list[float]:11 unmodified linesreturn outdef dataframe_table(table_id: str,*,page_size: int = 8,max_height: str = "520px",) -> dash_table.DataTable:return dash_table.DataTable(id=table_id,columns=[],data=[],page_size=page_size,sort_action="native",cell_selectable=True,style_as_list_view=True,fixed_rows={"headers": True},style_table={"overflowX": "auto", "overflowY": "auto", "maxHeight": max_height},style_header={"backgroundColor": "#f3f6f8","fontWeight": "700","border": "0","borderBottom": "1px solid #cfd8df","color": "#26323f",},style_cell={"fontFamily": "Inter, Arial, sans-serif","fontSize": "13px","padding": "10px 12px","textAlign": "left","minWidth": "90px","maxWidth": "260px","whiteSpace": "normal","height": "auto","border": "0","borderBottom": "1px solid #edf1f4",},style_cell_conditional=[{"if": {"column_id": col}, "textAlign": "right"} for col in RIGHT_ALIGNED_COLUMNS],style_data_conditional=[{"if": {"row_index": "odd"}, "backgroundColor": "#fbfcfd"},{"if": {"state": "active"}, "backgroundColor": "#e5f3f2", "border": "1px solid #4c908b"},],)def panel(title: str, *children, subtitle: str | None = None, className: str = "") -> html.Div:heading = [html.H2(title)]if subtitle:heading.append(html.P(subtitle, className="panel-subtitle"))classes = "panel" if not className else f"panel {className}"return html.Div([html.Div(heading, className="panel-heading"), *children], className=classes)def details_table(summary: str, table: dash_table.DataTable) -> html.Details:return html.Details([html.Summary(summary), html.Div(table, className="details-body")],className="details-table",)def metric_card(label: str, value: str, detail: str | None = None) -> html.Div:children = [html.Div(label, className="metric-label"),html.Div(value, className="metric-value"),]if detail:children.append(html.Div(detail, className="metric-detail"))return html.Div(children, className="metric-card")def leaderboard_frame(dataset: str, models: list[str] | None) -> pd.DataFrame:chosen = selected_models(models)base = pd.DataFrame({"model": chosen})base = add_method_columns(base)pred = filter_models(prediction, chosen)pred = pred[pred["dataset"].astype(str) == str(dataset)].copy()pred["score"] = pd.to_numeric(pred["score"], errors="coerce")pred = pred[["model", "metric", "score", "n_train_trials", "n_test_trials", "n_neurons", "latent_dim"]]pred = pred.rename(columns={"score": "task_score"})rob = filter_models(present_rows(robustness), chosen)rob = rob[rob["dataset"].astype(str) == str(dataset)].copy()rob["raw_auc"] = pd.to_numeric(rob["raw_auc"], errors="coerce")rob = rob[["model", "raw_auc"]].rename(columns={"raw_auc": "robustness_auc"})cons = filter_models(active_rows(consistency), chosen)cons = cons[cons["dataset"].astype(str) == str(dataset)].copy()cons["mean_r2"] = pd.to_numeric(cons["mean_r2"], errors="coerce")cons = cons[["model", "mean_r2"]].rename(columns={"mean_r2": "alignment_score"})scale = filter_models(present_rows(scalability), chosen)scale = scale[scale["dataset"].astype(str) == str(dataset)].copy()scale = scale[["model", "training_time_sec", "inference_time_sec", "peak_ram_gb", "peak_vram_gb"]]for col in ["training_time_sec", "inference_time_sec", "peak_ram_gb", "peak_vram_gb"]:scale[col] = pd.to_numeric(scale[col], errors="coerce")df = base.merge(pred, on="model", how="left")df = df.merge(rob, on="model", how="left")df = df.merge(cons, on="model", how="left")df = df.merge(scale, on="model", how="left")df["notes"] = np.where(df["task_score"].isna(), "Not available", "")available = df["task_score"].notna()order = df.loc[available].sort_values(["task_score", "model_order"], ascending=[False, True]).indexdf["rank"] = Nonefor rank, idx in enumerate(order, start=1):df.at[idx, "rank"] = rankdf = df.sort_values(["task_score", "model_order"], ascending=[False, True], na_position="last")df["id"] = df["model"]return round_numeric(df, NUMERIC_COLUMNS)def leaderboard_summary(dataset: str, table_df: pd.DataFrame) -> list[html.Div]:label = DATASET_LABELS.get(dataset, dataset)metric = metric_text(table_df["metric"].dropna().iloc[0]) if table_df["metric"].notna().any() else "score"available = table_df.dropna(subset=["task_score"]).head(3)cards = [metric_card("Dataset", label, f"Primary metric: {metric}")]for _, row in available.iterrows():cards.append(metric_card(f"Rank {int(row['rank'])}",str(row["method"]),f"{value_text(row['task_score'])} {metric}",))if len(cards) == 1:cards.append(metric_card("Top method", "Not available"))return cardsdef performance_heatmap(dataset: str, models: list[str] | None) -> go.Figure:df = filter_models(prediction, models)if df.empty:return empty_figure("No task performance results are available.")df = add_method_columns(df)df["score"] = pd.to_numeric(df["score"], errors="coerce")df["dataset_label"] = df["dataset"].map(DATASET_LABELS).fillna(df["dataset"])pivot = df.pivot_table(index="method", columns="dataset_label", values="score", aggfunc="first")selected_label = DATASET_LABELS.get(dataset, dataset)order_df = leaderboard_frame(dataset, models)method_order = [m for m in order_df["method"] if m in set(pivot.index)]pivot = pivot.reindex(method_order)dataset_order = [DATASET_LABELS.get(ds, ds) for ds in DATASETS]pivot = pivot.reindex(columns=[label for label in dataset_order if label in pivot.columns])text = pivot.map(lambda x: "" if pd.isna(x) else f"{x:.3f}") if not pivot.empty else pivotzmin = min(0.0, float(np.nanmin(pivot.values))) if pivot.size and not np.isnan(pivot.values).all() else 0.0zmax = max(1.0, float(np.nanmax(pivot.values))) if pivot.size and not np.isnan(pivot.values).all() else 1.0fig = go.Figure(go.Heatmap(z=pivot.values if not pivot.empty else [[]],x=list(pivot.columns),y=list(pivot.index),text=text.values if not pivot.empty else [[]],texttemplate="%{text}",colorscale=SCORE_SCALE,zmin=zmin,zmax=zmax,colorbar=dict(title="Score", thickness=12),hovertemplate="Method=%{y}<br>Dataset=%{x}<br>Score=%{z:.4f}<extra></extra>",))fig.update_layout(title=f"Task performance matrix, sorted by {selected_label}")return fig_layout(fig, height=max(430, 26 * len(pivot.index) + 150))def ranking_figure(dataset: str, table_df: pd.DataFrame) -> go.Figure:rank_df = table_df.dropna(subset=["task_score"]).sort_values("task_score", ascending=True)if rank_df.empty:return empty_figure(f"No task performance results are available for {DATASET_LABELS.get(dataset, dataset)}.")metric = metric_text(rank_df["metric"].dropna().iloc[0]) if rank_df["metric"].notna().any() else "score"fig = go.Figure(go.Bar(x=rank_df["task_score"],y=rank_df["method"],orientation="h",marker=dict(color="#006d77"),hovertemplate="Method=%{y}<br>Score=%{x:.4f}<extra></extra>",))fig.update_layout(title=f"{DATASET_LABELS.get(dataset, dataset)} ranking")fig.update_xaxes(title=metric)fig.update_yaxes(title="")return fig_layout(fig, height=max(420, 25 * len(rank_df) + 150))def consistency_frame(dataset: str, models: list[str] | None) -> pd.DataFrame:chosen = selected_models(models)base = add_method_columns(pd.DataFrame({"model": chosen}))cons = filter_models(active_rows(consistency), chosen)cons = cons[cons["dataset"].astype(str) == str(dataset)].copy()for col in ["mean_r2", "latent_dim", "n_sessions", "n_pairwise"]:cons[col] = pd.to_numeric(cons[col], errors="coerce")cons = cons[["model", "mean_r2", "latent_dim", "n_sessions", "n_pairwise"]]cons = cons.rename(columns={"mean_r2": "alignment_score"})df = base.merge(cons, on="model", how="left")df["notes"] = np.where(df["alignment_score"].isna(), "Not available", "")available = df["alignment_score"].notna()order = df.loc[available].sort_values(["alignment_score", "model_order"], ascending=[False, True]).indexdf["rank"] = Nonefor rank, idx in enumerate(order, start=1):df.at[idx, "rank"] = rankdf = df.sort_values(["alignment_score", "model_order"], ascending=[False, True], na_position="last")df["id"] = df["model"]return round_numeric(df, NUMERIC_COLUMNS)def selected_consistency_model(df: pd.DataFrame, active_cell: dict | None) -> str | None:if active_cell and active_cell.get("row_id") in set(df["model"]):return str(active_cell["row_id"])available = df.dropna(subset=["alignment_score"])if available.empty:return Nonereturn str(available.iloc[0]["model"])def consistency_bar_figure(dataset: str, df: pd.DataFrame) -> go.Figure:bar_df = df.dropna(subset=["alignment_score"]).sort_values("alignment_score", ascending=True)if bar_df.empty:return empty_figure(f"No cross-session alignment results are available for {DATASET_LABELS.get(dataset, dataset)}.")fig = go.Figure(go.Bar(x=bar_df["alignment_score"],y=bar_df["method"],orientation="h",marker=dict(color="#4c908b"),hovertemplate="Method=%{y}<br>Alignment=%{x:.4f}<extra></extra>",))fig.update_layout(title=f"{DATASET_LABELS.get(dataset, dataset)} cross-session alignment")fig.update_xaxes(title="Alignment score")fig.update_yaxes(title="")return fig_layout(fig, height=max(360, 25 * len(bar_df) + 130))def consistency_heatmap(models: list[str] | None) -> go.Figure:df = filter_models(active_rows(consistency), models)if df.empty:return empty_figure("No cross-session alignment results are available.")df = add_method_columns(df)df["mean_r2"] = pd.to_numeric(df["mean_r2"], errors="coerce")df["dataset_label"] = df["dataset"].map(DATASET_LABELS).fillna(df["dataset"])pivot = df.pivot_table(index="method", columns="dataset_label", values="mean_r2", aggfunc="first")if not pivot.empty:pivot = pivot.loc[pivot.mean(axis=1, skipna=True).sort_values(ascending=False).index]text = pivot.map(lambda x: "" if pd.isna(x) else f"{x:.2f}") if not pivot.empty else pivotfig = go.Figure(go.Heatmap(z=pivot.values if not pivot.empty else [[]],x=list(pivot.columns),y=list(pivot.index),text=text.values if not pivot.empty else [[]],texttemplate="%{text}",colorscale=SCORE_SCALE,colorbar=dict(title="Score", thickness=12),hovertemplate="Method=%{y}<br>Dataset=%{x}<br>Alignment=%{z:.4f}<extra></extra>",))fig.update_layout(title="Alignment across datasets")return fig_layout(fig, height=max(360, 25 * len(pivot.index) + 135))def latent_space_figure(dataset: str, model: str | None) -> go.Figure:if not model:return empty_figure("No latent-space view is available for this selection.")if latent_samples.empty:return empty_figure("Latent-space samples are unavailable in this view.")plot_df = latent_samples[(latent_samples["dataset"].astype(str) == str(dataset))& (latent_samples["model"].astype(str) == str(model))].copy()if plot_df.empty:return empty_figure(f"No latent-space samples are available for {model_label(model)} on {DATASET_LABELS.get(dataset, dataset)}.")for col in ["x", "y", "z"]:plot_df[col] = pd.to_numeric(plot_df[col], errors="coerce")plot_df["condition_num"] = pd.to_numeric(plot_df["condition"], errors="coerce")plot_df["condition_label"] = plot_df["condition"].map(lambda value: condition_label(dataset, value))plot_df["session_display"] = plot_df["session_label"].map(lambda value: session_display_label(dataset, value))plot_df = plot_df.dropna(subset=["x", "y", "z"])if plot_df.empty:return empty_figure("No latent-space samples match this selection.")trajectory_df = latent_trajectories[(latent_trajectories["dataset"].astype(str) == str(dataset))3 unmodified linesif col in trajectory_df:trajectory_df[col] = pd.to_numeric(trajectory_df[col], errors="coerce")if not trajectory_df.empty:trajectory_df["condition_label"] = trajectory_df["condition"].map(lambda value: condition_label(dataset, value))trajectory_df["session_display"] = trajectory_df["session_label"].map(lambda value: session_display_label(dataset, value))trajectory_df = trajectory_df.dropna(subset=["x", "y", "z"])sessions = ordered_unique(plot_df["session_label"])session_titles = [session_display_label(dataset, session) for session in sessions]n_cols = 2 if len(sessions) > 1 else 1n_rows = int(np.ceil(len(sessions) / n_cols))specs = [[{"type": "scene"} for _ in range(n_cols)] for _ in range(n_rows)]fig = make_subplots(rows=n_rows,cols=n_cols,specs=specs,subplot_titles=session_titles,horizontal_spacing=0.045,vertical_spacing=0.12,)condition_values = sorted(plot_df["condition"].astype(str).unique(), key=condition_sort_key)use_categorical = len(condition_values) <= 12condition_colors = {condition: CATEGORICAL_PALETTE[idx % len(CATEGORICAL_PALETTE)]for idx, condition in enumerate(condition_values)}condition_name = condition_axis_label(dataset)for session_idx, session in enumerate(sessions):session_df = plot_df[plot_df["session_label"].astype(str) == str(session)]if session_df.empty:continuerow = session_idx // n_cols + 1col = session_idx % n_cols + 1display_session = session_display_label(dataset, session)if use_categorical:for condition in condition_values:cond_df = session_df[session_df["condition"].astype(str) == condition]if cond_df.empty:continuetrace_name = condition_label(dataset, condition)session_traj = trajectory_df[(trajectory_df["session_label"].astype(str) == str(session))& (trajectory_df["condition"].astype(str) == condition)].sort_values("time_index")fig.add_trace(6 unmodified lineslegendgroup=condition,showlegend=session_idx == 0,marker=dict(size=2.4 if not session_traj.empty else 3.0,opacity=0.32 if not session_traj.empty else 0.78,color=condition_colors[condition],),customdata=np.stack([np.repeat(display_session, len(cond_df)),cond_df["condition_label"].astype(str),cond_df["trial_index"].astype(str),cond_df["time_index"].astype(str),1 unmodified lineaxis=-1,),hovertemplate=("Session=%{customdata[0]}<br>"f"{condition_name}=%{{customdata[1]}}<br>""Trial=%{customdata[2]} time=%{customdata[3]}""<extra></extra>"),),12 unmodified linesshowlegend=False,line=dict(color=condition_colors[condition], width=5),hovertemplate=(f"{condition_name}={trace_name}<br>""Time=%{customdata}<extra></extra>"),customdata=session_traj["time_index"],),7 unmodified linesy=session_df["y"],z=session_df["z"],mode="markers",name=display_session,showlegend=False,marker=dict(size=2.8,opacity=0.72,color=session_df["condition_num"],colorscale="Viridis",showscale=session_idx == 0,colorbar=dict(title=condition_name, thickness=12),),customdata=np.stack([np.repeat(display_session, len(session_df)),session_df["condition"].map(lambda value: condition_label(dataset, value)).astype(str),session_df["trial_index"].astype(str),session_df["time_index"].astype(str),1 unmodified lineaxis=-1,),hovertemplate=("Session=%{customdata[0]}<br>"f"{condition_name}=%{{customdata[1]}}<br>""Trial=%{customdata[2]} time=%{customdata[3]}""<extra></extra>"),),13 unmodified linesfig.update_layout(**{scene_id: dict(xaxis=dict(title="", range=[-lim, lim], showgrid=False, zeroline=False, showticklabels=False),yaxis=dict(title="", range=[-lim, lim], showgrid=False, zeroline=False, showticklabels=False),zaxis=dict(title="", range=[-lim, lim], showgrid=False, zeroline=False, showticklabels=False),aspectmode="cube",bgcolor="#ffffff",camera=dict(eye=dict(x=1.55, y=1.45, z=1.05)),)})score_df = active_rows(consistency)score_df = score_df[(score_df["dataset"].astype(str) == str(dataset))& (score_df["model"].astype(str) == str(model))].copy()score = Noneif not score_df.empty:score = pd.to_numeric(score_df["mean_r2"], errors="coerce").dropna()score = float(score.iloc[0]) if not score.empty else Nonescore_suffix = "" if score is None else f" | alignment {score:.2f}"fig.update_layout(title=f"{model_label(model)} latent space on {DATASET_LABELS.get(dataset, dataset)}{score_suffix}",height=760 if n_rows > 1 else 520,paper_bgcolor="#ffffff",plot_bgcolor="#ffffff",margin=dict(l=8, r=8, t=78, b=92),font=dict(family="Inter, Arial, sans-serif", size=13, color="#17202a"),legend=dict(orientation="h", yanchor="top", y=-0.08, xanchor="left", x=0, title=condition_name),)fig.for_each_annotation(lambda ann: ann.update(font=dict(size=12, color="#526171")))return figdef robustness_figure(dataset: str, models: list[str] | None) -> go.Figure:df = filter_models(present_rows(robustness), models)df = df[df["dataset"].astype(str) == str(dataset)].copy() if not df.empty else dfif df.empty:return empty_figure("No robustness results are available for this selection.")df = add_method_columns(df).sort_values("model_order")fig = go.Figure()for idx, row in enumerate(df.itertuples()):xs = parse_float_list(row.noise_levels)ys = parse_float_list(row.scores)if xs and len(xs) == len(ys):fig.add_trace(go.Scatter(x=xs,y=ys,mode="lines+markers",name=row.method,line=dict(color=CATEGORICAL_PALETTE[idx % len(CATEGORICAL_PALETTE)], width=2),marker=dict(size=5),hovertemplate="Noise=%{x:.2f}<br>Score=%{y:.4f}<extra></extra>",))fig.update_layout(title=f"{DATASET_LABELS.get(dataset, dataset)} robustness curves")fig.update_xaxes(title="Noise fraction")fig.update_yaxes(title=metric_text(df["metric"].dropna().iloc[0]) if df["metric"].notna().any() else "score")return fig_layout(fig, height=520)def robustness_table_frame(dataset: str, models: list[str] | None) -> pd.DataFrame:df = filter_models(present_rows(robustness), models)df = df[df["dataset"].astype(str) == str(dataset)].copy() if not df.empty else dfif df.empty:return pd.DataFrame(columns=["method", "metric", "reference_score", "highest_noise_score", "robustness_auc", "average_noisy_score"])df = add_method_columns(df)df = df.rename(columns={"score_at_noise0": "reference_score","score_at_max_noise": "highest_noise_score","raw_auc": "robustness_auc","mean_score": "average_noisy_score",})cols = ["method", "metric", "reference_score", "highest_noise_score", "robustness_auc", "average_noisy_score"]return round_numeric(df[cols].sort_values("robustness_auc", ascending=False), NUMERIC_COLUMNS)def compute_figures(dataset: str, models: list[str] | None) -> tuple[go.Figure, go.Figure, pd.DataFrame]:df = filter_models(present_rows(scalability), models)df = df[df["dataset"].astype(str) == str(dataset)].copy() if not df.empty else dfif df.empty:empty = pd.DataFrame(columns=["method", "hardware", "training_time_sec", "inference_time_sec", "peak_ram_gb", "peak_vram_gb"])return (empty_figure("No compute results are available for this selection."),empty_figure("No memory results are available for this selection."),empty,)pred = present_rows(prediction)[["model", "dataset", "score", "metric"]].copy()df = df.merge(pred, on=["model", "dataset"], how="left")df = add_method_columns(df)df["hardware"] = df["model"].map(hardware_label)for col in ["training_time_sec", "inference_time_sec", "peak_ram_gb", "peak_vram_gb", "score"]:df[col] = pd.to_numeric(df[col], errors="coerce")scatter = go.Figure(go.Scatter(x=df["training_time_sec"],y=df["score"],mode="markers",text=df["method"],marker=dict(size=np.clip(df["peak_ram_gb"].fillna(1.0) * 4, 8, 26),color=df["hardware"].map({"CPU": "#8a6f2a", "GPU": "#006d77"}).fillna("#637381"),opacity=0.82,line=dict(color="#ffffff", width=1),),customdata=np.stack([df["method"].astype(str),df["hardware"].astype(str),df["peak_ram_gb"].round(3).astype(str),df["peak_vram_gb"].round(3).astype(str),],axis=-1,),hovertemplate=("Method=%{customdata[0]}<br>""Hardware=%{customdata[1]}<br>""Training time=%{x:.3f} s<br>""Score=%{y:.4f}<br>""Peak memory=%{customdata[2]} GB<br>""Peak GPU memory=%{customdata[3]} GB""<extra></extra>"),))scatter.update_layout(title=f"{DATASET_LABELS.get(dataset, dataset)} performance and training time")scatter.update_xaxes(title="Training time (s, log scale)", type="log")scatter.update_yaxes(title=metric_text(df["metric"].dropna().iloc[0]) if df["metric"].notna().any() else "score")fig_layout(scatter, height=500)mem_df = df.sort_values("peak_ram_gb", ascending=True)memory = go.Figure()memory.add_trace(go.Bar(x=mem_df["peak_ram_gb"], y=mem_df["method"], orientation="h", name="RAM"))memory.add_trace(go.Bar(x=mem_df["peak_vram_gb"], y=mem_df["method"], orientation="h", name="GPU memory"))memory.update_layout(title=f"{DATASET_LABELS.get(dataset, dataset)} peak memory", barmode="group")memory.update_xaxes(title="GB")memory.update_yaxes(title="")fig_layout(memory, height=max(420, 26 * len(mem_df) + 150))table = df[["method", "hardware", "score", "training_time_sec", "inference_time_sec", "peak_ram_gb", "peak_vram_gb"]]return scatter, memory, round_numeric(table.sort_values("training_time_sec"), NUMERIC_COLUMNS)def influence_figures(dataset: str, models: list[str] | None) -> tuple[go.Figure, go.Figure, pd.DataFrame]:nshap = filter_models(active_rows(neuron_shap), models)nshap = nshap[nshap["dataset"].astype(str) == str(dataset)].copy() if not nshap.empty else nshapif nshap.empty:neuron_fig = empty_figure("No neuron-influence results are available for this dataset.")table = pd.DataFrame(columns=["method", "metric", "baseline_score", "full_model_score", "neuron_influence_auc", "shap_mean_value", "shap_fraction_positive"])else:nshap = add_method_columns(nshap)nshap["auc"] = pd.to_numeric(nshap["auc"], errors="coerce")bar_df = nshap.dropna(subset=["auc"]).sort_values("auc", ascending=True)neuron_fig = go.Figure(go.Bar(x=bar_df["auc"],y=bar_df["method"],orientation="h",marker=dict(color="#006d77"),hovertemplate="Method=%{y}<br>AUC=%{x:.4f}<extra></extra>",))neuron_fig.update_layout(title=f"{DATASET_LABELS.get(dataset, dataset)} neuron influence")neuron_fig.update_xaxes(title="Neuron influence AUC")neuron_fig.update_yaxes(title="")fig_layout(neuron_fig, height=max(420, 25 * len(bar_df) + 150))table = nshap.rename(columns={"auc": "neuron_influence_auc"})table = table[["method", "metric", "baseline_score", "full_model_score", "neuron_influence_auc", "shap_mean_value", "shap_fraction_positive"]]tshap = filter_models(active_rows(trial_shapley), models)tshap = tshap[tshap["dataset"].astype(str) == str(dataset)].copy() if not tshap.empty else tshapif tshap.empty:trial_fig = empty_figure("No trial-influence results are available for this dataset.")else:tshap = add_method_columns(tshap)tshap["perturbation_auc"] = pd.to_numeric(tshap["perturbation_auc"], errors="coerce")trial_df = tshap.dropna(subset=["perturbation_auc"]).sort_values("perturbation_auc", ascending=True)trial_fig = go.Figure(go.Bar(x=trial_df["perturbation_auc"],y=trial_df["method"],orientation="h",marker=dict(color="#8a6f2a"),hovertemplate="Method=%{y}<br>AUC=%{x:.4f}<extra></extra>",))trial_fig.update_layout(title=f"{DATASET_LABELS.get(dataset, dataset)} trial influence")trial_fig.update_xaxes(title="Trial influence AUC")trial_fig.update_yaxes(title="")fig_layout(trial_fig, height=max(420, 25 * len(trial_df) + 150))return neuron_fig, trial_fig, round_numeric(table, NUMERIC_COLUMNS)def methods_frame(models: list[str] | None) -> pd.DataFrame:chosen = selected_models(models)rows = []for model in chosen:rows.append({"id": model,"method": model_label(model),"family": METHOD_FAMILY.get(model, "Model"),"hardware": hardware_label(model),})return pd.DataFrame(rows).sort_values("method")app = Dash(__name__, title="Neural Model Benchmark")server = app.serverapp.layout = html.Div(3 unmodified lineshtml.Div([html.Div("Tang Lab", className="eyebrow"),html.H1("Neural Model Benchmark"),html.P("Explore task performance, robustness, latent alignment, neuron and trial influence, and compute cost across 23 benchmarked methods.",className="lede",),],1 unmodified line),html.Div([metric_card("Methods", str(len(MODELS)), "Benchmarked in the paper"),metric_card("Datasets", str(len(DATASETS)), "Selectable below"),],className="hero-metrics",),],className="hero",5 unmodified lineshtml.Label("Dataset"),dcc.Dropdown(id="dataset-filter",options=[{"label": DATASET_LABELS.get(ds, ds), "value": ds} for ds in DATASETS],value=DATASETS[0] if DATASETS else None,clearable=False,),2 unmodified lines),html.Div([html.Label("Method filter"),dcc.Dropdown(id="model-filter",options=[{"label": model_label(model), "value": model} for model in MODELS],value=[],multi=True,placeholder="All methods",),],className="control control-wide",),],className="toolbar",),dcc.Tabs(id="tabs",value="leaderboard",className="tabs",children=[dcc.Tab(label="Leaderboard",value="leaderboard",className="tab",selected_className="tab tab-selected",children=[panel("Leaderboard",html.Div(id="leaderboard-top", className="top-strip"),html.Div([html.Div(dataframe_table("leaderboard-table", page_size=23, max_height="680px"),className="leaderboard-table-wrap",),dcc.Graph(id="dataset-ranking", config={"displayModeBar": False}),],className="leaderboard-grid",),dcc.Graph(id="performance-heatmap", config={"displayModeBar": False}),subtitle="Sorted by the selected dataset. Regression datasets use R2; classification datasets use accuracy. Higher is better.",className="leaderboard-panel",)],),dcc.Tab(label="Consistency",value="consistency",className="tab",selected_className="tab tab-selected",children=[panel("Cross-session alignment",html.Div([html.Div([dataframe_table("consistency-table", page_size=23, max_height="520px"),html.P("Click a method to update the 3D latent view.", className="table-hint"),],className="consistency-table-wrap",),dcc.Graph(id="latent-space",config={"displayModeBar": "hover","toImageButtonOptions": {"format": "png","filename": "benchdash_latent_space","height": 900,"width": 1200,"scale": 2,},},),],className="latent-grid",),html.Div([dcc.Graph(id="consistency-bars", config={"displayModeBar": False}),dcc.Graph(id="consistency-heatmap", config={"displayModeBar": False}),],className="chart-grid two",),subtitle="Each latent panel shows one recording session. Colors indicate task condition, stimulus, cue, or spatial bin.",)],),dcc.Tab(label="Robustness",value="robustness",className="tab",selected_className="tab tab-selected",children=[panel("Robustness",dcc.Graph(id="robustness-curve", config={"displayModeBar": False}),details_table("View robustness rows", dataframe_table("robustness-table")),subtitle="Curves show how task performance changes as neural count noise increases.",)],),dcc.Tab(label="Influence",value="influence",className="tab",selected_className="tab tab-selected",children=[panel("Neuron and trial influence",html.Div([dcc.Graph(id="neuron-influence-bars", config={"displayModeBar": False}),dcc.Graph(id="trial-influence-bars", config={"displayModeBar": False}),],className="chart-grid two",),details_table("View neuron-influence rows", dataframe_table("influence-table")),subtitle="Signed contribution summaries preserve whether neurons or trials helped or hurt prediction.",)],),dcc.Tab(label="Compute",value="compute",className="tab",selected_className="tab tab-selected",children=[panel("Performance and compute cost",html.Div([dcc.Graph(id="compute-scatter", config={"displayModeBar": False}),dcc.Graph(id="memory-bars", config={"displayModeBar": False}),],className="chart-grid two",),details_table("View compute rows", dataframe_table("compute-table")),subtitle="Shows training time and peak memory for each method on the selected dataset.",)],),dcc.Tab(label="Methods",value="methods",className="tab",selected_className="tab tab-selected",children=[panel("Benchmarked methods",dataframe_table("methods-table", page_size=23, max_height="600px"),subtitle="Paper-facing method names and broad method families.",)],),5 unmodified lines@app.callback(Output("leaderboard-top", "children"),Output("leaderboard-table", "columns"),Output("leaderboard-table", "data"),Output("dataset-ranking", "figure"),Output("performance-heatmap", "figure"),Input("dataset-filter", "value"),Input("model-filter", "value"),)def update_leaderboard(dataset: str, models: list[str] | None):df = leaderboard_frame(dataset, models)visible_cols = ["rank","method","task_score","metric","robustness_auc","alignment_score","training_time_sec","peak_ram_gb","notes",]table_df = df[[c for c in visible_cols + ["id", "model"] if c in df.columns]]return (leaderboard_summary(dataset, df),column_defs([c for c in visible_cols if c in table_df.columns]),records(table_df),ranking_figure(dataset, df),performance_heatmap(dataset, models),)@app.callback(Output("consistency-table", "columns"),Output("consistency-table", "data"),Output("latent-space", "figure"),Output("consistency-bars", "figure"),Output("consistency-heatmap", "figure"),Input("dataset-filter", "value"),Input("model-filter", "value"),Input("consistency-table", "active_cell"),)def update_consistency(dataset: str, models: list[str] | None, active_cell: dict | None):df = consistency_frame(dataset, models)model = selected_consistency_model(df, active_cell)visible_cols = ["rank", "method", "alignment_score", "n_sessions", "latent_dim", "n_pairwise", "notes"]table_df = df[[c for c in visible_cols + ["id", "model"] if c in df.columns]]return (column_defs([c for c in visible_cols if c in table_df.columns]),records(table_df),latent_space_figure(dataset, model),consistency_bar_figure(dataset, df),consistency_heatmap(models),)@app.callback(Output("robustness-curve", "figure"),Output("robustness-table", "columns"),Output("robustness-table", "data"),Input("dataset-filter", "value"),Input("model-filter", "value"),)def update_robustness(dataset: str, models: list[str] | None):table = robustness_table_frame(dataset, models)return (robustness_figure(dataset, models),column_defs(table.columns),records(table),)@app.callback(Output("compute-scatter", "figure"),Output("memory-bars", "figure"),Output("compute-table", "columns"),Output("compute-table", "data"),Input("dataset-filter", "value"),Input("model-filter", "value"),)def update_compute(dataset: str, models: list[str] | None):scatter, memory, table = compute_figures(dataset, models)return scatter, memory, column_defs(table.columns), records(table)@app.callback(Output("neuron-influence-bars", "figure"),Output("trial-influence-bars", "figure"),Output("influence-table", "columns"),Output("influence-table", "data"),Input("dataset-filter", "value"),Input("model-filter", "value"),)def update_influence(dataset: str, models: list[str] | None):neuron_fig, trial_fig, table = influence_figures(dataset, models)return neuron_fig, trial_fig, column_defs(table.columns), records(table)@app.callback(Output("methods-table", "columns"),Output("methods-table", "data"),Input("model-filter", "value"),)def update_methods(models: list[str] | None):table = methods_frame(models)return column_defs(table.columns), records(table)if __name__ == "__main__":
3 unmodified lines456789101112131415161718192021222324252627281 unmodified line30313233343536378 unmodified lines4647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811823 unmodified lines1861871881891901911921931941951961971981992002012022032042053 unmodified linesbody {margin: 0;background: #f7f8fa;color: #18212b;font-family: Inter, Arial, sans-serif;}.app-shell {min-height: 100vh;padding: 22px;}.hero {display: grid;grid-template-columns: minmax(340px, 1fr) minmax(420px, 0.9fr);gap: 28px;align-items: end;margin: 0 auto 18px;max-width: 1500px;padding: 14px 4px 18px;border-bottom: 1px solid #dfe6eb;}.hero-copy {1 unmodified line}.eyebrow {margin-bottom: 8px;color: #536271;font-size: 12px;font-weight: 800;letter-spacing: 0;8 unmodified lines}h1 {margin-bottom: 10px;font-size: 44px;line-height: 1.05;letter-spacing: 0;}h2 {margin-bottom: 4px;font-size: 20px;letter-spacing: 0;}h3 {margin-bottom: 8px;font-size: 15px;letter-spacing: 0;}.lede {max-width: 760px;margin-bottom: 0;color: #536271;font-size: 16px;line-height: 1.5;}.stat-grid {display: grid;grid-template-columns: repeat(4, minmax(110px, 1fr));gap: 0;align-items: end;border: 1px solid #dfe6eb;border-radius: 8px;background: #ffffff;}.stat-card {min-height: 108px;padding: 18px;border-right: 1px solid #e6ecef;}.stat-card:last-child {border-right: 0;}.stat-label {color: #617282;font-size: 11px;font-weight: 800;letter-spacing: 0;text-transform: uppercase;}.stat-value {margin-top: 9px;color: #111827;font-size: 28px;font-weight: 800;line-height: 1;}.stat-detail {margin-top: 8px;color: #657483;font-size: 12px;line-height: 1.35;}.controls {display: grid;grid-template-columns: minmax(240px, 320px) minmax(320px, 1fr);gap: 18px;margin: 0 auto 18px;max-width: 1500px;padding: 14px;border: 1px solid #dfe6eb;border-radius: 8px;background: #ffffff;}.control label {display: block;margin-bottom: 7px;color: #394756;font-size: 12px;font-weight: 800;letter-spacing: 0;text-transform: uppercase;}.tabs {margin: 0 auto;max-width: 1500px;}.panel {margin-top: 14px;padding: 18px;border: 1px solid #dfe6eb;border-radius: 8px;background: #ffffff;}.panel-heading {margin-bottom: 12px;}.panel-subtitle {margin-bottom: 0;color: #5b6b7b;font-size: 13px;line-height: 1.45;}@media (max-width: 1050px) {.hero,.controls {grid-template-columns: 1fr;}.stat-grid {grid-template-columns: repeat(2, minmax(120px, 1fr));}.stat-card:nth-child(2) {border-right: 0;}.stat-card:nth-child(-n + 2) {border-bottom: 1px solid #e6ecef;}}3 unmodified lines}h1 {font-size: 34px;}.stat-grid {grid-template-columns: 1fr;}.stat-card,.stat-card:nth-child(2) {border-right: 0;border-bottom: 1px solid #e6ecef;}.stat-card:last-child {border-bottom: 0;}}3 unmodified lines456789101112131415161718192021222324252627282930313233341 unmodified line36373839404142438 unmodified lines5253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722733 unmodified lines2772782792802812822832842852862872882892902912923 unmodified linesbody {margin: 0;background: #f4f6f7;color: #17202a;font-family: Inter, Arial, sans-serif;}.app-shell {min-height: 100vh;padding: 18px 22px 28px;}.hero,.toolbar,.tabs {max-width: 1560px;margin-left: auto;margin-right: auto;}.hero {display: grid;grid-template-columns: minmax(360px, 1fr) auto;gap: 26px;align-items: end;padding: 8px 2px 14px;border-bottom: 1px solid #d8e1e7;}.hero-copy {1 unmodified line}.eyebrow {margin-bottom: 7px;color: #526171;font-size: 12px;font-weight: 800;letter-spacing: 0;8 unmodified lines}h1 {margin-bottom: 8px;font-size: 40px;line-height: 1.05;letter-spacing: 0;}h2 {margin-bottom: 5px;font-size: 20px;letter-spacing: 0;}.lede {max-width: 840px;margin-bottom: 0;color: #526171;font-size: 15px;line-height: 1.45;}.hero-metrics,.top-strip {display: flex;gap: 10px;align-items: stretch;flex-wrap: wrap;}.metric-card {min-width: 145px;padding: 12px 14px;border: 1px solid #d8e1e7;border-radius: 8px;background: #ffffff;}.metric-label {color: #607080;font-size: 11px;font-weight: 800;letter-spacing: 0;text-transform: uppercase;}.metric-value {margin-top: 7px;color: #101820;font-size: 22px;font-weight: 800;line-height: 1.1;}.metric-detail {margin-top: 6px;color: #647383;font-size: 12px;line-height: 1.35;}.toolbar {position: sticky;top: 0;z-index: 10;display: grid;grid-template-columns: minmax(230px, 310px) minmax(360px, 1fr);gap: 16px;margin-top: 14px;margin-bottom: 14px;padding: 12px;border: 1px solid #d8e1e7;border-radius: 8px;background: rgba(255, 255, 255, 0.96);box-shadow: 0 8px 24px rgba(18, 28, 38, 0.06);backdrop-filter: blur(6px);}.control label {display: block;margin-bottom: 6px;color: #344452;font-size: 12px;font-weight: 800;letter-spacing: 0;text-transform: uppercase;}.Select--multi .Select-value {margin-top: 3px;}.Select-multi-value-wrapper {max-height: 86px;overflow-y: auto;}.tabs {border: 0;}.tab {padding: 11px 18px !important;border: 0 !important;border-bottom: 2px solid transparent !important;background: transparent !important;color: #637381 !important;font-size: 14px;font-weight: 700;}.tab-selected {color: #12302f !important;border-bottom-color: #006d77 !important;background: #ffffff !important;}.panel {margin-top: 14px;padding: 18px;border: 1px solid #d8e1e7;border-radius: 8px;background: #ffffff;}.panel-heading {margin-bottom: 14px;}.panel-subtitle {max-width: 980px;margin-bottom: 0;color: #526171;font-size: 13px;line-height: 1.45;}.leaderboard-panel {padding-top: 16px;}.top-strip {margin-bottom: 14px;}.leaderboard-grid {display: grid;grid-template-columns: minmax(560px, 1.08fr) minmax(360px, 0.92fr);gap: 16px;align-items: start;}.leaderboard-table-wrap,.consistency-table-wrap {min-width: 0;}.latent-grid {display: grid;grid-template-columns: minmax(360px, 0.42fr) minmax(620px, 1fr);gap: 16px;align-items: start;}.chart-grid {display: grid;gap: 16px;align-items: start;}.chart-grid.two {grid-template-columns: repeat(2, minmax(320px, 1fr));}.table-hint {margin: 10px 2px 0;color: #647383;font-size: 12px;}.details-table {margin-top: 12px;border-top: 1px solid #e5ebef;}.details-table summary {cursor: pointer;padding: 12px 0 8px;color: #344452;font-size: 13px;font-weight: 800;}.details-body {padding-top: 4px;}.dash-table-container .dash-spreadsheet-container .dash-spreadsheet-inner th {background: #f3f6f8 !important;}.dash-table-container .previous-next-container {margin-top: 8px;color: #526171;font-size: 12px;}@media (max-width: 1180px) {.hero,.toolbar,.leaderboard-grid,.latent-grid,.chart-grid.two {grid-template-columns: 1fr;}.hero-metrics {justify-content: flex-start;}}3 unmodified lines}h1 {font-size: 32px;}.panel {padding: 14px;}.tab {padding-left: 10px !important;padding-right: 10px !important;font-size: 13px;}}
README.md+7-8
app.py+956-689
assets/styles.css+174-87