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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from typing import Dict, List, Tuple
|
| 4 |
+
import math
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
import pandas as pd
|
| 8 |
+
import plotly.graph_objects as go
|
| 9 |
+
from dash import Dash, Input, Output, callback, dash_table, dcc, html
|
| 10 |
+
from plotly.subplots import make_subplots
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
SIGFIGS = 3
|
| 14 |
+
|
| 15 |
+
COLUMN_COLORS = {
|
| 16 |
+
"r2": "rgb(230, 245, 255)",
|
| 17 |
+
"rmse": "rgb(240, 255, 230)",
|
| 18 |
+
"mae": "rgb(255, 245, 230)",
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
BEHAVIORS = ["Behavior A", "Behavior B", "Behavior C"]
|
| 22 |
+
BEHAVIOR_COLORS = {
|
| 23 |
+
"Behavior A": "#636EFA",
|
| 24 |
+
"Behavior B": "#EF553B",
|
| 25 |
+
"Behavior C": "#00CC96",
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
METRIC_DIRECTION = {
|
| 29 |
+
"r2": "high_is_good",
|
| 30 |
+
"rmse": "low_is_good",
|
| 31 |
+
"mae": "low_is_good",
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
# Universal axis limits for better comparison across panels
|
| 35 |
+
XYZ_RANGE: Tuple[float, float] = (-25.0, 25.0)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def build_toy_benchmark() -> Dict[str, pd.DataFrame]:
|
| 39 |
+
return {
|
| 40 |
+
"Dataset 1": pd.DataFrame(
|
| 41 |
+
[
|
| 42 |
+
{"model": "Model 1", "r2": 0.62, "rmse": 4.10, "mae": 3.20},
|
| 43 |
+
{"model": "Model 2", "r2": 0.71, "rmse": 3.60, "mae": 2.90},
|
| 44 |
+
{"model": "Model 3", "r2": 0.68, "rmse": 3.85, "mae": 3.05},
|
| 45 |
+
]
|
| 46 |
+
),
|
| 47 |
+
"Dataset 2": pd.DataFrame(
|
| 48 |
+
[
|
| 49 |
+
{"model": "Model 1", "r2": 0.55, "rmse": 4.55, "mae": 3.55},
|
| 50 |
+
{"model": "Model 2", "r2": 0.66, "rmse": 3.95, "mae": 3.10},
|
| 51 |
+
{"model": "Model 3", "r2": 0.63, "rmse": 4.05, "mae": 3.20},
|
| 52 |
+
]
|
| 53 |
+
),
|
| 54 |
+
"Dataset 3": pd.DataFrame(
|
| 55 |
+
[
|
| 56 |
+
{"model": "Model 1", "r2": 0.49, "rmse": 5.05, "mae": 3.95},
|
| 57 |
+
{"model": "Model 2", "r2": 0.61, "rmse": 4.25, "mae": 3.35},
|
| 58 |
+
{"model": "Model 3", "r2": 0.59, "rmse": 4.40, "mae": 3.50},
|
| 59 |
+
]
|
| 60 |
+
),
|
| 61 |
+
}
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def compute_mock_score(
|
| 65 |
+
df: pd.DataFrame,
|
| 66 |
+
*,
|
| 67 |
+
metric_direction: Dict[str, str],
|
| 68 |
+
metric_weights: Dict[str, float] | None = None,
|
| 69 |
+
eps: float = 1e-12,
|
| 70 |
+
) -> pd.Series:
|
| 71 |
+
if metric_weights is None:
|
| 72 |
+
metric_weights = {}
|
| 73 |
+
|
| 74 |
+
metrics = [m for m in metric_direction.keys() if m in df.columns]
|
| 75 |
+
if not metrics:
|
| 76 |
+
return pd.Series([0.0] * len(df), index=df.index)
|
| 77 |
+
|
| 78 |
+
parts = []
|
| 79 |
+
weights = []
|
| 80 |
+
|
| 81 |
+
for m in metrics:
|
| 82 |
+
x = df[m].astype(float)
|
| 83 |
+
x_min = float(x.min())
|
| 84 |
+
x_max = float(x.max())
|
| 85 |
+
|
| 86 |
+
if (x_max - x_min) < eps:
|
| 87 |
+
x_norm = pd.Series([0.5] * len(df), index=df.index)
|
| 88 |
+
else:
|
| 89 |
+
x_norm = (x - x_min) / (x_max - x_min)
|
| 90 |
+
|
| 91 |
+
if metric_direction[m] == "low_is_good":
|
| 92 |
+
x_norm = 1.0 - x_norm
|
| 93 |
+
|
| 94 |
+
w = float(metric_weights.get(m, 1.0))
|
| 95 |
+
parts.append(x_norm * w)
|
| 96 |
+
weights.append(w)
|
| 97 |
+
|
| 98 |
+
return sum(parts) / (sum(weights) + eps)
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def generate_mock_embedding(
|
| 102 |
+
dataset_name: str,
|
| 103 |
+
model_name: str,
|
| 104 |
+
*,
|
| 105 |
+
noise_level: float,
|
| 106 |
+
n_points_per_behavior: int = 250,
|
| 107 |
+
# Behavior geometry knobs (at noise=0)
|
| 108 |
+
base_center_spread: float = 7.5,
|
| 109 |
+
base_noise_scale: float = 1.0,
|
| 110 |
+
transform_strength: float = 0.55,
|
| 111 |
+
shift_strength: float = 2.0,
|
| 112 |
+
warp_strength: float = 0.35,
|
| 113 |
+
# Noise injection knobs
|
| 114 |
+
max_replace_frac: float = 0.60,
|
| 115 |
+
background_scale: float = 9.0,
|
| 116 |
+
) -> pd.DataFrame:
|
| 117 |
+
"""
|
| 118 |
+
Mock 3D embedding with a "noise spike" control.
|
| 119 |
+
|
| 120 |
+
noise_level in [0,1]:
|
| 121 |
+
- reduces inter-behavior separation (centers collapse)
|
| 122 |
+
- increases within-cluster spread
|
| 123 |
+
- replaces a fraction of points with background noise points
|
| 124 |
+
"""
|
| 125 |
+
nl = float(np.clip(noise_level, 0.0, 1.0))
|
| 126 |
+
|
| 127 |
+
seed = abs(hash((dataset_name, model_name))) % (2**32)
|
| 128 |
+
rng = np.random.default_rng(seed)
|
| 129 |
+
|
| 130 |
+
# Base behavior centers in a canonical triangle in 3D
|
| 131 |
+
base_centers = {
|
| 132 |
+
"Behavior A": np.array([0.0, 0.0, 0.0]),
|
| 133 |
+
"Behavior B": np.array([1.0, 0.2, 0.1]),
|
| 134 |
+
"Behavior C": np.array([0.5, 1.1, -0.2]),
|
| 135 |
+
}
|
| 136 |
+
|
| 137 |
+
# As noise increases, pull centers toward a common centroid
|
| 138 |
+
centroid = sum(base_centers.values()) / len(base_centers)
|
| 139 |
+
center_spread = base_center_spread * (1.0 - 0.80 * nl)
|
| 140 |
+
centers = {}
|
| 141 |
+
for beh, c0 in base_centers.items():
|
| 142 |
+
c_collapsed = (1.0 - 0.85 * nl) * c0 + (0.85 * nl) * centroid
|
| 143 |
+
centers[beh] = c_collapsed * center_spread
|
| 144 |
+
|
| 145 |
+
# Within-cluster spread increases with noise
|
| 146 |
+
noise_scale = base_noise_scale * (1.0 + 2.25 * nl)
|
| 147 |
+
|
| 148 |
+
# Stronger per-panel transforms so different (dataset, model) look different
|
| 149 |
+
angles = rng.uniform(low=-np.pi, high=np.pi, size=3)
|
| 150 |
+
cx, cy, cz = np.cos(angles)
|
| 151 |
+
sx, sy, sz = np.sin(angles)
|
| 152 |
+
|
| 153 |
+
Rx = np.array([[1, 0, 0], [0, cx, -sx], [0, sx, cx]])
|
| 154 |
+
Ry = np.array([[cy, 0, sy], [0, 1, 0], [-sy, 0, cy]])
|
| 155 |
+
Rz = np.array([[cz, -sz, 0], [sz, cz, 0], [0, 0, 1]])
|
| 156 |
+
R = Rz @ Ry @ Rx
|
| 157 |
+
|
| 158 |
+
scales = np.diag(1.0 + transform_strength * rng.normal(size=3))
|
| 159 |
+
shear = np.eye(3)
|
| 160 |
+
shear[0, 1] = 0.25 * transform_strength * rng.normal()
|
| 161 |
+
shear[0, 2] = 0.25 * transform_strength * rng.normal()
|
| 162 |
+
shear[1, 2] = 0.25 * transform_strength * rng.normal()
|
| 163 |
+
|
| 164 |
+
A = (R @ scales @ shear)
|
| 165 |
+
b = shift_strength * rng.normal(size=(3,))
|
| 166 |
+
|
| 167 |
+
# How many points get replaced by background "noise spikes"
|
| 168 |
+
replace_frac = max_replace_frac * nl
|
| 169 |
+
|
| 170 |
+
rows: List[dict] = []
|
| 171 |
+
for beh in BEHAVIORS:
|
| 172 |
+
X = centers[beh] + noise_scale * rng.normal(size=(n_points_per_behavior, 3))
|
| 173 |
+
|
| 174 |
+
# Apply affine transform
|
| 175 |
+
X = X @ A.T + b
|
| 176 |
+
|
| 177 |
+
# Nonlinear warp (twist + bend); stays even with noise
|
| 178 |
+
theta = warp_strength * (0.15 * X[:, 0] + 0.10 * X[:, 1])
|
| 179 |
+
ct = np.cos(theta)
|
| 180 |
+
st = np.sin(theta)
|
| 181 |
+
x_new = ct * X[:, 0] - st * X[:, 1]
|
| 182 |
+
y_new = st * X[:, 0] + ct * X[:, 1]
|
| 183 |
+
z_new = X[:, 2] + warp_strength * np.tanh(0.25 * X[:, 0]) * 2.0
|
| 184 |
+
X = np.stack([x_new, y_new, z_new], axis=1)
|
| 185 |
+
|
| 186 |
+
# Replace a fraction with background noise points
|
| 187 |
+
n_replace = int(round(replace_frac * n_points_per_behavior))
|
| 188 |
+
if n_replace > 0:
|
| 189 |
+
idx_replace = rng.choice(n_points_per_behavior, size=n_replace, replace=False)
|
| 190 |
+
|
| 191 |
+
# Background noise: heavy-ish tails + broad scale, centered near origin
|
| 192 |
+
# This creates global "salt-and-pepper" points that mix behaviors.
|
| 193 |
+
noise_bg = background_scale * rng.standard_t(df=3, size=(n_replace, 3))
|
| 194 |
+
X[idx_replace] = noise_bg
|
| 195 |
+
|
| 196 |
+
for i in range(n_points_per_behavior):
|
| 197 |
+
rows.append(
|
| 198 |
+
{
|
| 199 |
+
"x": float(X[i, 0]),
|
| 200 |
+
"y": float(X[i, 1]),
|
| 201 |
+
"z": float(X[i, 2]),
|
| 202 |
+
"behavior": beh,
|
| 203 |
+
}
|
| 204 |
+
)
|
| 205 |
+
|
| 206 |
+
return pd.DataFrame(rows)
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
def _parse_rgb(rgb: str) -> tuple[int, int, int]:
|
| 210 |
+
vals = rgb.strip().lower().replace("rgb(", "").replace(")", "").split(",")
|
| 211 |
+
return int(vals[0]), int(vals[1]), int(vals[2])
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
def _darken(rgb: str, factor: float = 0.65) -> str:
|
| 215 |
+
r, g, b = _parse_rgb(rgb)
|
| 216 |
+
r = int(max(0, min(255, round(r * factor))))
|
| 217 |
+
g = int(max(0, min(255, round(g * factor))))
|
| 218 |
+
b = int(max(0, min(255, round(b * factor))))
|
| 219 |
+
return f"rgb({r},{g},{b})"
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
def _blend_rgb(rgb_a: str, rgb_b: str, t: float) -> str:
|
| 223 |
+
t = max(0.0, min(1.0, float(t)))
|
| 224 |
+
ra, ga, ba = _parse_rgb(rgb_a)
|
| 225 |
+
rb, gb, bb = _parse_rgb(rgb_b)
|
| 226 |
+
r = round(ra + (rb - ra) * t)
|
| 227 |
+
g = round(ga + (gb - ga) * t)
|
| 228 |
+
b = round(ba + (bb - ba) * t)
|
| 229 |
+
return f"rgb({r},{g},{b})"
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
def make_column_gradient_styles(
|
| 233 |
+
df: pd.DataFrame,
|
| 234 |
+
*,
|
| 235 |
+
id_col: str,
|
| 236 |
+
n_bins: int,
|
| 237 |
+
column_base_colors: Dict[str, str],
|
| 238 |
+
metric_direction: Dict[str, str],
|
| 239 |
+
darken_factor: float = 0.65,
|
| 240 |
+
) -> List[dict]:
|
| 241 |
+
numeric_cols = [
|
| 242 |
+
c
|
| 243 |
+
for c in df.columns
|
| 244 |
+
if c != id_col and c in column_base_colors and pd.api.types.is_numeric_dtype(df[c])
|
| 245 |
+
]
|
| 246 |
+
|
| 247 |
+
styles: List[dict] = []
|
| 248 |
+
white = "rgb(255, 255, 255)"
|
| 249 |
+
|
| 250 |
+
for col in numeric_cols:
|
| 251 |
+
col_min = float(df[col].min())
|
| 252 |
+
col_max = float(df[col].max())
|
| 253 |
+
if not (col_max > col_min):
|
| 254 |
+
continue
|
| 255 |
+
|
| 256 |
+
base = column_base_colors[col]
|
| 257 |
+
dark_base = _darken(base, factor=darken_factor)
|
| 258 |
+
direction = metric_direction.get(col, "high_is_good")
|
| 259 |
+
|
| 260 |
+
for i in range(n_bins):
|
| 261 |
+
low = col_min + (col_max - col_min) * (i / n_bins)
|
| 262 |
+
high = col_min + (col_max - col_min) * ((i + 1) / n_bins)
|
| 263 |
+
|
| 264 |
+
t = (i + 1) / n_bins
|
| 265 |
+
if direction == "low_is_good":
|
| 266 |
+
t = 1.0 - t
|
| 267 |
+
|
| 268 |
+
styles.append(
|
| 269 |
+
{
|
| 270 |
+
"if": {
|
| 271 |
+
"column_id": col,
|
| 272 |
+
"filter_query": f"{{{col}}} >= {low} && {{{col}}} < {high}",
|
| 273 |
+
},
|
| 274 |
+
"backgroundColor": _blend_rgb(white, dark_base, t),
|
| 275 |
+
}
|
| 276 |
+
)
|
| 277 |
+
|
| 278 |
+
best_val = col_max if direction == "high_is_good" else col_min
|
| 279 |
+
worst_val = col_min if direction == "high_is_good" else col_max
|
| 280 |
+
|
| 281 |
+
styles.append(
|
| 282 |
+
{
|
| 283 |
+
"if": {"column_id": col, "filter_query": f"{{{col}}} = {best_val}"},
|
| 284 |
+
"backgroundColor": _blend_rgb(white, dark_base, 1.0),
|
| 285 |
+
}
|
| 286 |
+
)
|
| 287 |
+
styles.append(
|
| 288 |
+
{
|
| 289 |
+
"if": {"column_id": col, "filter_query": f"{{{col}}} = {worst_val}"},
|
| 290 |
+
"backgroundColor": _blend_rgb(white, dark_base, 0.0),
|
| 291 |
+
}
|
| 292 |
+
)
|
| 293 |
+
|
| 294 |
+
return styles
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
def _apply_universal_scene_ranges(fig: go.Figure, *, n_scenes: int) -> None:
|
| 298 |
+
"""
|
| 299 |
+
Apply the same x/y/z ranges to every 3D scene in a subplot grid.
|
| 300 |
+
"""
|
| 301 |
+
for idx in range(n_scenes):
|
| 302 |
+
scene_id = "scene" if idx == 0 else f"scene{idx + 1}"
|
| 303 |
+
fig.update_layout(
|
| 304 |
+
**{
|
| 305 |
+
scene_id: dict(
|
| 306 |
+
xaxis=dict(title="", range=list(XYZ_RANGE)),
|
| 307 |
+
yaxis=dict(title="", range=list(XYZ_RANGE)),
|
| 308 |
+
zaxis=dict(title="", range=list(XYZ_RANGE)),
|
| 309 |
+
)
|
| 310 |
+
}
|
| 311 |
+
)
|
| 312 |
+
|
| 313 |
+
|
| 314 |
+
def _embedding_grid_figure(
|
| 315 |
+
*,
|
| 316 |
+
titles: List[str],
|
| 317 |
+
dataset_for_each_panel: List[str],
|
| 318 |
+
model_for_each_panel: List[str],
|
| 319 |
+
noise_level: float,
|
| 320 |
+
n_cols: int = 3,
|
| 321 |
+
) -> go.Figure:
|
| 322 |
+
n_panels = len(titles)
|
| 323 |
+
n_rows = int(math.ceil(n_panels / n_cols))
|
| 324 |
+
|
| 325 |
+
specs = [[{"type": "scene"} for _ in range(n_cols)] for _ in range(n_rows)]
|
| 326 |
+
fig = make_subplots(
|
| 327 |
+
rows=n_rows,
|
| 328 |
+
cols=n_cols,
|
| 329 |
+
specs=specs,
|
| 330 |
+
subplot_titles=titles,
|
| 331 |
+
horizontal_spacing=0.02,
|
| 332 |
+
vertical_spacing=0.06,
|
| 333 |
+
)
|
| 334 |
+
|
| 335 |
+
for idx in range(n_panels):
|
| 336 |
+
r = (idx // n_cols) + 1
|
| 337 |
+
c = (idx % n_cols) + 1
|
| 338 |
+
|
| 339 |
+
ds = dataset_for_each_panel[idx]
|
| 340 |
+
md = model_for_each_panel[idx]
|
| 341 |
+
df_emb = generate_mock_embedding(ds, md, noise_level=noise_level)
|
| 342 |
+
|
| 343 |
+
for beh in BEHAVIORS:
|
| 344 |
+
df_b = df_emb[df_emb["behavior"] == beh]
|
| 345 |
+
fig.add_trace(
|
| 346 |
+
go.Scatter3d(
|
| 347 |
+
x=df_b["x"],
|
| 348 |
+
y=df_b["y"],
|
| 349 |
+
z=df_b["z"],
|
| 350 |
+
mode="markers",
|
| 351 |
+
name=beh,
|
| 352 |
+
legendgroup=beh,
|
| 353 |
+
showlegend=(idx == 0),
|
| 354 |
+
marker={
|
| 355 |
+
"size": 2.5,
|
| 356 |
+
"opacity": 0.75,
|
| 357 |
+
"color": BEHAVIOR_COLORS[beh],
|
| 358 |
+
},
|
| 359 |
+
hovertemplate=(
|
| 360 |
+
"behavior=%{text}<br>"
|
| 361 |
+
"x=%{x:.3f}<br>y=%{y:.3f}<br>z=%{z:.3f}<extra></extra>"
|
| 362 |
+
),
|
| 363 |
+
text=[beh] * len(df_b),
|
| 364 |
+
),
|
| 365 |
+
row=r,
|
| 366 |
+
col=c,
|
| 367 |
+
)
|
| 368 |
+
|
| 369 |
+
_apply_universal_scene_ranges(fig, n_scenes=n_panels)
|
| 370 |
+
|
| 371 |
+
fig.update_layout(
|
| 372 |
+
height=320 * n_rows,
|
| 373 |
+
margin=dict(l=10, r=10, t=40, b=10),
|
| 374 |
+
)
|
| 375 |
+
return fig
|
| 376 |
+
|
| 377 |
+
|
| 378 |
+
TOY_STORE = build_toy_benchmark()
|
| 379 |
+
ALL_DATASETS = list(TOY_STORE.keys())
|
| 380 |
+
ALL_MODELS = sorted({m for df in TOY_STORE.values() for m in df["model"].astype(str).tolist()})
|
| 381 |
+
|
| 382 |
+
app = Dash(__name__)
|
| 383 |
+
|
| 384 |
+
app.layout = html.Div(
|
| 385 |
+
[
|
| 386 |
+
html.H3("Neural Decoder Benchmarking"),
|
| 387 |
+
|
| 388 |
+
html.Div(
|
| 389 |
+
[
|
| 390 |
+
html.Div("Mode"),
|
| 391 |
+
dcc.RadioItems(
|
| 392 |
+
id="mode-radio",
|
| 393 |
+
options=[
|
| 394 |
+
{"label": "By dataset", "value": "by_dataset"},
|
| 395 |
+
{"label": "By model", "value": "by_model"},
|
| 396 |
+
],
|
| 397 |
+
value="by_dataset",
|
| 398 |
+
inline=True,
|
| 399 |
+
),
|
| 400 |
+
],
|
| 401 |
+
style={"marginBottom": "12px"},
|
| 402 |
+
),
|
| 403 |
+
|
| 404 |
+
html.Div(
|
| 405 |
+
[
|
| 406 |
+
html.Div(
|
| 407 |
+
[
|
| 408 |
+
html.Div("Dataset"),
|
| 409 |
+
dcc.Dropdown(
|
| 410 |
+
id="dataset-dropdown",
|
| 411 |
+
options=[{"label": k, "value": k} for k in ALL_DATASETS],
|
| 412 |
+
value=ALL_DATASETS[0],
|
| 413 |
+
clearable=False,
|
| 414 |
+
style={"width": "100%"},
|
| 415 |
+
),
|
| 416 |
+
],
|
| 417 |
+
id="dataset-dropdown-container",
|
| 418 |
+
style={
|
| 419 |
+
"width": "520px",
|
| 420 |
+
"minWidth": "520px",
|
| 421 |
+
"flexShrink": 0,
|
| 422 |
+
"marginBottom": "12px",
|
| 423 |
+
},
|
| 424 |
+
),
|
| 425 |
+
html.Div(
|
| 426 |
+
[
|
| 427 |
+
html.Div("Model"),
|
| 428 |
+
dcc.Dropdown(
|
| 429 |
+
id="model-dropdown",
|
| 430 |
+
options=[{"label": m, "value": m} for m in ALL_MODELS],
|
| 431 |
+
value=ALL_MODELS[0] if ALL_MODELS else None,
|
| 432 |
+
clearable=False,
|
| 433 |
+
style={"width": "100%"},
|
| 434 |
+
),
|
| 435 |
+
],
|
| 436 |
+
id="model-dropdown-container",
|
| 437 |
+
style={
|
| 438 |
+
"width": "520px",
|
| 439 |
+
"minWidth": "520px",
|
| 440 |
+
"flexShrink": 0,
|
| 441 |
+
"marginBottom": "12px",
|
| 442 |
+
"display": "none",
|
| 443 |
+
},
|
| 444 |
+
),
|
| 445 |
+
],
|
| 446 |
+
style={"display": "flex", "gap": "16px", "alignItems": "flex-end"},
|
| 447 |
+
),
|
| 448 |
+
|
| 449 |
+
dash_table.DataTable(
|
| 450 |
+
id="metrics-table",
|
| 451 |
+
columns=[],
|
| 452 |
+
data=[],
|
| 453 |
+
sort_action="native",
|
| 454 |
+
page_action="none",
|
| 455 |
+
style_table={"overflowX": "auto"},
|
| 456 |
+
style_cell={
|
| 457 |
+
"padding": "8px",
|
| 458 |
+
"fontFamily": "Arial",
|
| 459 |
+
"fontSize": "14px",
|
| 460 |
+
"textAlign": "left",
|
| 461 |
+
"minWidth": "120px",
|
| 462 |
+
"width": "120px",
|
| 463 |
+
"maxWidth": "200px",
|
| 464 |
+
},
|
| 465 |
+
style_header={"fontWeight": "600"},
|
| 466 |
+
style_data_conditional=[],
|
| 467 |
+
sort_by=[{"column_id": "score", "direction": "desc"}],
|
| 468 |
+
),
|
| 469 |
+
|
| 470 |
+
html.Div(
|
| 471 |
+
[
|
| 472 |
+
html.Div("Noise level (fraction of spikes replaced / corrupted)"),
|
| 473 |
+
dcc.Slider(
|
| 474 |
+
id="noise-slider",
|
| 475 |
+
min=0.0,
|
| 476 |
+
max=1.0,
|
| 477 |
+
step=0.05,
|
| 478 |
+
value=0.0,
|
| 479 |
+
marks={0.0: "0", 0.25: "0.25", 0.5: "0.5", 0.75: "0.75", 1.0: "1.0"},
|
| 480 |
+
tooltip={"placement": "bottom", "always_visible": False},
|
| 481 |
+
),
|
| 482 |
+
],
|
| 483 |
+
style={"maxWidth": "1100px", "marginTop": "10px", "marginBottom": "10px"},
|
| 484 |
+
),
|
| 485 |
+
|
| 486 |
+
dcc.Graph(
|
| 487 |
+
id="embeddings-grid",
|
| 488 |
+
style={"height": "800px"},
|
| 489 |
+
config={"displayModeBar": False},
|
| 490 |
+
),
|
| 491 |
+
],
|
| 492 |
+
style={"padding": "16px"},
|
| 493 |
+
)
|
| 494 |
+
|
| 495 |
+
|
| 496 |
+
@callback(
|
| 497 |
+
Output("dataset-dropdown-container", "style"),
|
| 498 |
+
Output("model-dropdown-container", "style"),
|
| 499 |
+
Input("mode-radio", "value"),
|
| 500 |
+
)
|
| 501 |
+
def toggle_controls(mode: str):
|
| 502 |
+
base_box = {
|
| 503 |
+
"width": "520px",
|
| 504 |
+
"minWidth": "520px",
|
| 505 |
+
"flexShrink": 0,
|
| 506 |
+
"marginBottom": "12px",
|
| 507 |
+
}
|
| 508 |
+
if mode == "by_model":
|
| 509 |
+
return {**base_box, "display": "none"}, {**base_box, "display": "block"}
|
| 510 |
+
return {**base_box, "display": "block"}, {**base_box, "display": "none"}
|
| 511 |
+
|
| 512 |
+
|
| 513 |
+
@callback(
|
| 514 |
+
Output("metrics-table", "columns"),
|
| 515 |
+
Output("metrics-table", "data"),
|
| 516 |
+
Output("metrics-table", "style_data_conditional"),
|
| 517 |
+
Output("embeddings-grid", "figure"),
|
| 518 |
+
Input("mode-radio", "value"),
|
| 519 |
+
Input("dataset-dropdown", "value"),
|
| 520 |
+
Input("model-dropdown", "value"),
|
| 521 |
+
Input("noise-slider", "value"),
|
| 522 |
+
)
|
| 523 |
+
def update_outputs(mode: str, dataset_name: str, model_name: str, noise_level: float):
|
| 524 |
+
column_colors = dict(COLUMN_COLORS)
|
| 525 |
+
column_colors["score"] = "rgb(220, 220, 220)"
|
| 526 |
+
|
| 527 |
+
metric_direction_for_colors = dict(METRIC_DIRECTION)
|
| 528 |
+
metric_direction_for_colors["score"] = "high_is_good"
|
| 529 |
+
|
| 530 |
+
if mode == "by_model":
|
| 531 |
+
# Rows = datasets (fixed model)
|
| 532 |
+
rows = []
|
| 533 |
+
for ds_name, df_ds in TOY_STORE.items():
|
| 534 |
+
df_row = df_ds[df_ds["model"] == model_name]
|
| 535 |
+
if df_row.empty:
|
| 536 |
+
continue
|
| 537 |
+
rec = df_row.iloc[0].to_dict()
|
| 538 |
+
rows.append({"dataset": ds_name, **{k: rec[k] for k in rec if k != "model"}})
|
| 539 |
+
|
| 540 |
+
df = pd.DataFrame(rows)
|
| 541 |
+
if df.empty:
|
| 542 |
+
return [], [], [], go.Figure()
|
| 543 |
+
|
| 544 |
+
df["score"] = compute_mock_score(
|
| 545 |
+
df,
|
| 546 |
+
metric_direction=METRIC_DIRECTION,
|
| 547 |
+
metric_weights={"r2": 1.0, "rmse": 1.0, "mae": 1.0},
|
| 548 |
+
)
|
| 549 |
+
df = df.sort_values("score", ascending=False).reset_index(drop=True)
|
| 550 |
+
df = df[["dataset", "score"] + [c for c in df.columns if c not in {"dataset", "score"}]]
|
| 551 |
+
|
| 552 |
+
id_col = "dataset"
|
| 553 |
+
titles = df["dataset"].tolist()
|
| 554 |
+
|
| 555 |
+
fig_grid = _embedding_grid_figure(
|
| 556 |
+
titles=titles,
|
| 557 |
+
dataset_for_each_panel=titles,
|
| 558 |
+
model_for_each_panel=[model_name] * len(titles),
|
| 559 |
+
noise_level=float(noise_level),
|
| 560 |
+
n_cols=3,
|
| 561 |
+
)
|
| 562 |
+
|
| 563 |
+
else:
|
| 564 |
+
# Rows = models (fixed dataset)
|
| 565 |
+
df = TOY_STORE[dataset_name].copy()
|
| 566 |
+
|
| 567 |
+
df["score"] = compute_mock_score(
|
| 568 |
+
df,
|
| 569 |
+
metric_direction=METRIC_DIRECTION,
|
| 570 |
+
metric_weights={"r2": 1.0, "rmse": 1.0, "mae": 1.0},
|
| 571 |
+
)
|
| 572 |
+
df = df.sort_values("score", ascending=False).reset_index(drop=True)
|
| 573 |
+
df = df[["model", "score"] + [c for c in df.columns if c not in {"model", "score"}]]
|
| 574 |
+
|
| 575 |
+
id_col = "model"
|
| 576 |
+
titles = df["model"].tolist()
|
| 577 |
+
|
| 578 |
+
fig_grid = _embedding_grid_figure(
|
| 579 |
+
titles=titles,
|
| 580 |
+
dataset_for_each_panel=[dataset_name] * len(titles),
|
| 581 |
+
model_for_each_panel=titles,
|
| 582 |
+
noise_level=float(noise_level),
|
| 583 |
+
n_cols=3,
|
| 584 |
+
)
|
| 585 |
+
|
| 586 |
+
# DataTable columns + trailing zeros formatting
|
| 587 |
+
num_cols = [c for c in df.columns if c != id_col and pd.api.types.is_numeric_dtype(df[c])]
|
| 588 |
+
|
| 589 |
+
columns = [{"name": id_col, "id": id_col}]
|
| 590 |
+
for c in df.columns:
|
| 591 |
+
if c == id_col:
|
| 592 |
+
continue
|
| 593 |
+
col_def = {"name": c, "id": c}
|
| 594 |
+
if c in num_cols:
|
| 595 |
+
col_def["type"] = "numeric"
|
| 596 |
+
col_def["format"] = {"specifier": f".{SIGFIGS}f"}
|
| 597 |
+
columns.append(col_def)
|
| 598 |
+
|
| 599 |
+
data = df.to_dict("records")
|
| 600 |
+
|
| 601 |
+
styles = make_column_gradient_styles(
|
| 602 |
+
df,
|
| 603 |
+
id_col=id_col,
|
| 604 |
+
n_bins=12,
|
| 605 |
+
column_base_colors=column_colors,
|
| 606 |
+
metric_direction=metric_direction_for_colors,
|
| 607 |
+
darken_factor=0.65,
|
| 608 |
+
)
|
| 609 |
+
|
| 610 |
+
return columns, data, styles, fig_grid
|
| 611 |
+
|
| 612 |
+
|
| 613 |
+
if __name__ == "__main__":
|
| 614 |
+
app.run_server(debug=True)
|