Spaces:
Paused

rruiqii commited on
Commit
e643e60
·
1 Parent(s): eb4cbe8

fixed histogram layout and updated top 3 brain regions

Browse files
backend/app/services/database.py CHANGED
@@ -4,6 +4,7 @@ import math
4
  import threading
5
  import traceback
6
  from datetime import datetime
 
7
  from typing import Any, Dict, List, Optional
8
 
9
  from supabase import Client, create_client
@@ -21,6 +22,8 @@ class SupabaseDbService:
21
  raise RuntimeError("Supabase credentials are not configured for backend DB access.")
22
  self.client: Client = create_client(settings.supabase_url, key)
23
  self._client_lock = threading.RLock()
 
 
24
 
25
  async def _run(self, fn):
26
  def locked_call():
@@ -63,6 +66,186 @@ class SupabaseDbService:
63
  return {}
64
  return {}
65
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
  def _build_prediction_summary_rows(
67
  self,
68
  *,
@@ -97,22 +280,9 @@ class SupabaseDbService:
97
  continue
98
 
99
  explanation = explained_by_score.get(score_id, {})
100
- roi_items = explanation.get("roi_importance") or []
101
- if not isinstance(roi_items, list):
102
- roi_items = []
103
-
104
- top_regions = []
105
- for roi in roi_items[:10]:
106
- if not isinstance(roi, dict):
107
- continue
108
- label = str(roi.get("label") or roi.get("roi_index") or "").strip()
109
- importance = self._safe_float(roi.get("importance"))
110
- if not label or importance is None:
111
- continue
112
- top_regions.append({
113
- "name": label,
114
- "importance": importance,
115
- })
116
 
117
  summary_rows.append(
118
  {
@@ -477,11 +647,11 @@ async def get_dashboard_stats(user_id: str) -> Dict[str, Any]:
477
  "range": [0.0, 24.0],
478
  "defaultInsight": "Fluid reasoning aligns with executive-control and parietal integration patterns.",
479
  },
480
- "sustained_attention": {
481
- "label": "Sustained Attention",
482
- "shortLabel": "Attention",
483
- "range": [0.0, 1.0],
484
- "defaultInsight": "Attention performance tracks dorsal attention synchronization stability.",
485
  },
486
  "emotion_recognition": {
487
  "label": "Emotion Recognition",
@@ -496,6 +666,10 @@ async def get_dashboard_stats(user_id: str) -> Dict[str, Any]:
496
  "defaultInsight": "Sleep-quality variation clusters around salience, limbic, and thalamic circuitry.",
497
  },
498
  }
 
 
 
 
499
 
500
  uploads_resp = (
501
  service.client.table("file_uploads")
@@ -508,7 +682,7 @@ async def get_dashboard_stats(user_id: str) -> Dict[str, Any]:
508
 
509
  exec_resp = (
510
  service.client.table("model_executions")
511
- .select("execution_id,status,created_at,completed_at")
512
  .eq("user_id", user_id)
513
  .execute()
514
  )
@@ -516,6 +690,16 @@ async def get_dashboard_stats(user_id: str) -> Dict[str, Any]:
516
 
517
  completed = [e for e in executions if e.get("status") == "completed"]
518
  pending = [e for e in executions if e.get("status") in ("queued", "processing")]
 
 
 
 
 
 
 
 
 
 
519
 
520
  durations = []
521
  for e in completed:
@@ -536,14 +720,54 @@ async def get_dashboard_stats(user_id: str) -> Dict[str, Any]:
536
 
537
  dashboard_metrics = []
538
  try:
539
- summary_resp = (
540
- service.client.table("prediction_summaries")
541
- .select("score_id,predicted_value,completed_at,top_regions")
542
- .eq("user_id", user_id)
543
- .order("completed_at", desc=False)
544
- .execute()
545
- )
546
- summary_rows = summary_resp.data or []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
547
 
548
  metric_values: Dict[str, List[float]] = {metric_id: [] for metric_id in metric_configs}
549
  metric_timeline: Dict[str, List[tuple[str, float]]] = {metric_id: [] for metric_id in metric_configs}
@@ -552,24 +776,38 @@ async def get_dashboard_stats(user_id: str) -> Dict[str, Any]:
552
  for row in summary_rows:
553
  if not isinstance(row, dict):
554
  continue
555
- metric_id = str(row.get("score_id") or "").strip().lower()
 
556
  if metric_id not in metric_configs:
557
  continue
558
- value = self._safe_float(row.get("predicted_value"))
559
  if value is None:
560
  continue
561
  timeline_key = str(row.get("completed_at") or "")
562
  metric_values[metric_id].append(value)
563
  metric_timeline[metric_id].append((timeline_key, value))
564
 
565
- top_regions = row.get("top_regions") or []
566
- if not isinstance(top_regions, list):
567
- top_regions = []
568
- for region in top_regions[:10]:
569
- if not isinstance(region, dict):
570
- continue
 
 
 
 
 
 
 
 
 
 
 
 
 
571
  label = str(region.get("name") or "").strip()
572
- importance = self._safe_float(region.get("importance"))
573
  if not label or importance is None:
574
  continue
575
  metric_region_scores[metric_id][label] = metric_region_scores[metric_id].get(label, 0.0) + importance
 
4
  import threading
5
  import traceback
6
  from datetime import datetime
7
+ from pathlib import Path
8
  from typing import Any, Dict, List, Optional
9
 
10
  from supabase import Client, create_client
 
22
  raise RuntimeError("Supabase credentials are not configured for backend DB access.")
23
  self.client: Client = create_client(settings.supabase_url, key)
24
  self._client_lock = threading.RLock()
25
+ self._roi_network_map = self._load_roi_network_map()
26
+ self._score_region_cache: Dict[str, List[Dict[str, Any]]] = {}
27
 
28
  async def _run(self, fn):
29
  def locked_call():
 
66
  return {}
67
  return {}
68
 
69
+ @staticmethod
70
+ def _normalize_network_name(value: str) -> str:
71
+ compact = "".join(ch.lower() for ch in value if ch.isalnum())
72
+ aliases = {
73
+ "frontoparietal": "Frontoparietal",
74
+ "defaultmode": "Default Mode",
75
+ "medialfrontal": "Medial Frontal",
76
+ "motor": "Motor",
77
+ "visuali": "Visual I",
78
+ "visualii": "Visual II",
79
+ "visualassoc": "Visual Association",
80
+ "visualassociation": "Visual Association",
81
+ "subcorticalcerebellum": "Subcortical/Cerebellum",
82
+ }
83
+ return aliases.get(compact, value)
84
+
85
+ @staticmethod
86
+ def _is_dashboard_network_name(value: str) -> bool:
87
+ return value in {
88
+ "Frontoparietal",
89
+ "Default Mode",
90
+ "Medial Frontal",
91
+ "Motor",
92
+ "Visual I",
93
+ "Visual II",
94
+ "Visual Association",
95
+ "Subcortical/Cerebellum",
96
+ }
97
+
98
+ def _load_roi_network_map(self) -> Dict[int, str]:
99
+ nodes_path = Path(__file__).resolve().parents[1] / "data" / "brain_importance" / "shen268_nodes.json"
100
+ try:
101
+ payload = json.loads(nodes_path.read_text(encoding="utf-8"))
102
+ except Exception:
103
+ return {}
104
+
105
+ nodes = payload.get("nodes") if isinstance(payload, dict) else None
106
+ if not isinstance(nodes, list):
107
+ return {}
108
+
109
+ mapping: Dict[int, str] = {}
110
+ for node in nodes:
111
+ if not isinstance(node, dict):
112
+ continue
113
+ node_no = node.get("node_no")
114
+ network = node.get("network")
115
+ if isinstance(node_no, int) and isinstance(network, str) and network.strip():
116
+ mapping[node_no] = self._normalize_network_name(network.strip())
117
+ return mapping
118
+
119
+ def _get_dashboard_network_label(self, roi_index: Any = None, raw_label: Any = None) -> str:
120
+ if isinstance(roi_index, int):
121
+ mapped = self._roi_network_map.get(roi_index)
122
+ if mapped and self._is_dashboard_network_name(mapped):
123
+ return mapped
124
+
125
+ label = self._normalize_network_name(str(raw_label or "").strip())
126
+ return label if self._is_dashboard_network_name(label) else ""
127
+
128
+ def _build_dashboard_top_regions(self, explanation: Dict[str, Any]) -> List[Dict[str, Any]]:
129
+ top_edges = explanation.get("top_edges") or []
130
+ if not isinstance(top_edges, list):
131
+ top_edges = []
132
+
133
+ region_scores: Dict[str, float] = {}
134
+ for edge in top_edges[:10]:
135
+ if not isinstance(edge, dict):
136
+ continue
137
+ importance = self._safe_float(edge.get("importance"))
138
+ if importance is None:
139
+ continue
140
+
141
+ source_label = self._get_dashboard_network_label(
142
+ roi_index=edge.get("source_roi"),
143
+ raw_label=edge.get("source_label"),
144
+ )
145
+ target_label = self._get_dashboard_network_label(
146
+ roi_index=edge.get("target_roi"),
147
+ raw_label=edge.get("target_label"),
148
+ )
149
+
150
+ if source_label:
151
+ region_scores[source_label] = region_scores.get(source_label, 0.0) + importance
152
+ if target_label:
153
+ region_scores[target_label] = region_scores.get(target_label, 0.0) + importance
154
+
155
+ if region_scores:
156
+ return [
157
+ {"name": name, "importance": score}
158
+ for name, score in sorted(region_scores.items(), key=lambda item: item[1], reverse=True)[:8]
159
+ ]
160
+
161
+ roi_items = explanation.get("roi_importance") or []
162
+ if not isinstance(roi_items, list):
163
+ roi_items = []
164
+
165
+ fallback_scores: Dict[str, float] = {}
166
+ for roi in roi_items[:10]:
167
+ if not isinstance(roi, dict):
168
+ continue
169
+ importance = self._safe_float(roi.get("importance"))
170
+ if importance is None:
171
+ continue
172
+ label = self._get_dashboard_network_label(
173
+ roi_index=roi.get("roi_index"),
174
+ raw_label=roi.get("label"),
175
+ )
176
+ if label:
177
+ fallback_scores[label] = fallback_scores.get(label, 0.0) + importance
178
+
179
+ return [
180
+ {"name": name, "importance": score}
181
+ for name, score in sorted(fallback_scores.items(), key=lambda item: item[1], reverse=True)[:8]
182
+ ]
183
+
184
+ def _get_score_fallback_top_regions(self, score_id: str) -> List[Dict[str, Any]]:
185
+ normalized_score_id = str(score_id or "").strip().lower()
186
+ if not normalized_score_id:
187
+ return []
188
+
189
+ cached = self._score_region_cache.get(normalized_score_id)
190
+ if cached is not None:
191
+ return [dict(item) for item in cached]
192
+
193
+ score_files = {
194
+ "listsort_ageadj": "listsort_fbnetgen_importance_top100.json",
195
+ "pmat": "pmat_braingnn_importance_top100.json",
196
+ "picseq": "picseq_fbnetgen_importance_top100.json",
197
+ "emotion_recognition": "emotsupp_reggnn_importance_top100.json",
198
+ "emotsupp_unadj": "emotsupp_reggnn_importance_top100.json",
199
+ "psqi": "psqi_reggnn_importance_top100.json",
200
+ }
201
+ file_name = score_files.get(normalized_score_id)
202
+ if not file_name:
203
+ self._score_region_cache[normalized_score_id] = []
204
+ return []
205
+
206
+ payload_path = Path(__file__).resolve().parents[1] / "data" / "brain_importance" / file_name
207
+ try:
208
+ payload = json.loads(payload_path.read_text(encoding="utf-8"))
209
+ except Exception:
210
+ self._score_region_cache[normalized_score_id] = []
211
+ return []
212
+
213
+ edges = payload.get("edges") if isinstance(payload, dict) else None
214
+ plot_edges = payload.get("plot_edges") if isinstance(payload, dict) else None
215
+ edge_candidates = plot_edges if isinstance(plot_edges, list) and plot_edges else edges
216
+ if not isinstance(edge_candidates, list):
217
+ self._score_region_cache[normalized_score_id] = []
218
+ return []
219
+
220
+ top_k_edges = 15 if normalized_score_id == "pmat" else 30
221
+ region_scores: Dict[str, float] = {}
222
+ for edge in edge_candidates[:top_k_edges]:
223
+ if not isinstance(edge, dict):
224
+ continue
225
+ importance = self._safe_float(edge.get("weight"))
226
+ if importance is None:
227
+ continue
228
+ source_label = self._get_dashboard_network_label(
229
+ roi_index=edge.get("source_node_no"),
230
+ raw_label=edge.get("start_network"),
231
+ )
232
+ target_label = self._get_dashboard_network_label(
233
+ roi_index=edge.get("target_node_no"),
234
+ raw_label=edge.get("end_network"),
235
+ )
236
+
237
+ if source_label:
238
+ region_scores[source_label] = region_scores.get(source_label, 0.0) + abs(importance)
239
+ if target_label:
240
+ region_scores[target_label] = region_scores.get(target_label, 0.0) + abs(importance)
241
+
242
+ fallback = [
243
+ {"name": name, "importance": score}
244
+ for name, score in sorted(region_scores.items(), key=lambda item: item[1], reverse=True)[:8]
245
+ ]
246
+ self._score_region_cache[normalized_score_id] = fallback
247
+ return [dict(item) for item in fallback]
248
+
249
  def _build_prediction_summary_rows(
250
  self,
251
  *,
 
280
  continue
281
 
282
  explanation = explained_by_score.get(score_id, {})
283
+ top_regions = self._build_dashboard_top_regions(explanation)
284
+ if not top_regions:
285
+ top_regions = self._get_score_fallback_top_regions(score_id)
 
 
 
 
 
 
 
 
 
 
 
 
 
286
 
287
  summary_rows.append(
288
  {
 
647
  "range": [0.0, 24.0],
648
  "defaultInsight": "Fluid reasoning aligns with executive-control and parietal integration patterns.",
649
  },
650
+ "picseq": {
651
+ "label": "PicSeq (Picture Sequence Memory)",
652
+ "shortLabel": "PicSeq",
653
+ "range": [50.0, 150.0],
654
+ "defaultInsight": "Picture-sequence memory patterns reflect distributed episodic-memory and associative network coordination.",
655
  },
656
  "emotion_recognition": {
657
  "label": "Emotion Recognition",
 
666
  "defaultInsight": "Sleep-quality variation clusters around salience, limbic, and thalamic circuitry.",
667
  },
668
  }
669
+ metric_aliases = {
670
+ "sustained_attention": "picseq",
671
+ "emotsupp_unadj": "emotion_recognition",
672
+ }
673
 
674
  uploads_resp = (
675
  service.client.table("file_uploads")
 
682
 
683
  exec_resp = (
684
  service.client.table("model_executions")
685
+ .select("execution_id,upload_id,status,created_at,completed_at,results")
686
  .eq("user_id", user_id)
687
  .execute()
688
  )
 
690
 
691
  completed = [e for e in executions if e.get("status") == "completed"]
692
  pending = [e for e in executions if e.get("status") in ("queued", "processing")]
693
+ completed_by_execution_id = {
694
+ str(e.get("execution_id")): e
695
+ for e in completed
696
+ if e.get("execution_id")
697
+ }
698
+ completed_execution_ids = [
699
+ str(e.get("execution_id"))
700
+ for e in completed
701
+ if e.get("execution_id")
702
+ ]
703
 
704
  durations = []
705
  for e in completed:
 
720
 
721
  dashboard_metrics = []
722
  try:
723
+ summary_rows = []
724
+ if completed_execution_ids:
725
+ summary_resp = (
726
+ service.client.table("prediction_summaries")
727
+ .select("execution_id,score_id,predicted_value,completed_at,top_regions")
728
+ .eq("user_id", user_id)
729
+ .in_("execution_id", completed_execution_ids)
730
+ .order("completed_at", desc=False)
731
+ .execute()
732
+ )
733
+ summary_rows = summary_resp.data or []
734
+
735
+ if not summary_rows and completed:
736
+ for execution in completed:
737
+ execution_id = str(execution.get("execution_id") or "")
738
+ upload_id = str(execution.get("upload_id") or "")
739
+ completed_at = str(execution.get("completed_at") or datetime.utcnow().isoformat())
740
+ results = service._normalize_json_dict(execution.get("results"))
741
+ if not execution_id or not upload_id:
742
+ continue
743
+ summary_rows.extend(
744
+ service._build_prediction_summary_rows(
745
+ execution_id=execution_id,
746
+ upload_id=upload_id,
747
+ user_id=user_id,
748
+ results=results,
749
+ completed_at_iso=completed_at,
750
+ )
751
+ )
752
+
753
+ execution_region_cache: Dict[str, Dict[str, List[Dict[str, Any]]]] = {}
754
+ for execution_id, execution in completed_by_execution_id.items():
755
+ results = service._normalize_json_dict(execution.get("results"))
756
+ explained_scores = results.get("explained_scores") or []
757
+ if not isinstance(explained_scores, list):
758
+ continue
759
+
760
+ per_score_regions: Dict[str, List[Dict[str, Any]]] = {}
761
+ for explanation in explained_scores:
762
+ if not isinstance(explanation, dict):
763
+ continue
764
+ score_id = str(explanation.get("score_id") or "").strip().lower()
765
+ if not score_id:
766
+ continue
767
+ per_score_regions[score_id] = service._build_dashboard_top_regions(explanation)
768
+
769
+ if per_score_regions:
770
+ execution_region_cache[execution_id] = per_score_regions
771
 
772
  metric_values: Dict[str, List[float]] = {metric_id: [] for metric_id in metric_configs}
773
  metric_timeline: Dict[str, List[tuple[str, float]]] = {metric_id: [] for metric_id in metric_configs}
 
776
  for row in summary_rows:
777
  if not isinstance(row, dict):
778
  continue
779
+ raw_metric_id = str(row.get("score_id") or "").strip().lower()
780
+ metric_id = metric_aliases.get(raw_metric_id, raw_metric_id)
781
  if metric_id not in metric_configs:
782
  continue
783
+ value = service._safe_float(row.get("predicted_value"))
784
  if value is None:
785
  continue
786
  timeline_key = str(row.get("completed_at") or "")
787
  metric_values[metric_id].append(value)
788
  metric_timeline[metric_id].append((timeline_key, value))
789
 
790
+ execution_id = str(row.get("execution_id") or "")
791
+ resolved_regions = execution_region_cache.get(execution_id, {}).get(raw_metric_id, [])
792
+ if not resolved_regions:
793
+ top_regions = row.get("top_regions") or []
794
+ if not isinstance(top_regions, list):
795
+ top_regions = []
796
+ for region in top_regions[:10]:
797
+ if not isinstance(region, dict):
798
+ continue
799
+ label = service._get_dashboard_network_label(raw_label=region.get("name"))
800
+ importance = service._safe_float(region.get("importance"))
801
+ if not label or importance is None:
802
+ continue
803
+ resolved_regions.append({"name": label, "importance": importance})
804
+ if not resolved_regions:
805
+ fallback_metric_id = raw_metric_id if raw_metric_id in {"listsort_ageadj", "pmat", "picseq", "emotsupp_unadj", "psqi"} else metric_id
806
+ resolved_regions = service._get_score_fallback_top_regions(fallback_metric_id)
807
+
808
+ for region in resolved_regions:
809
  label = str(region.get("name") or "").strip()
810
+ importance = service._safe_float(region.get("importance"))
811
  if not label or importance is None:
812
  continue
813
  metric_region_scores[metric_id][label] = metric_region_scores[metric_id].get(label, 0.0) + importance
backend/app/services/model_service.py CHANGED
@@ -1239,6 +1239,7 @@ def _run_model_predictions(
1239
  graphs_flat,
1240
  target_scaler_json_path=target_scaler_json,
1241
  )
 
1242
  predicted_scores.append(
1243
  {
1244
  "score_id": score_id,
@@ -1254,6 +1255,14 @@ def _run_model_predictions(
1254
  "source": "model",
1255
  }
1256
  )
 
 
 
 
 
 
 
 
1257
  print(
1258
  f"[model] Prediction succeeded for {score_id}: "
1259
  f"value={prediction['value']:.4f}, windows={prediction['n_graph_windows']}"
 
1239
  graphs_flat,
1240
  target_scaler_json_path=target_scaler_json,
1241
  )
1242
+ explanation = _explain_single_score_model(model, graphs_flat)
1243
  predicted_scores.append(
1244
  {
1245
  "score_id": score_id,
 
1255
  "source": "model",
1256
  }
1257
  )
1258
+ explained_scores.append(
1259
+ {
1260
+ "score_id": score_id,
1261
+ "model_file": model_meta.get("filename"),
1262
+ "source": "model",
1263
+ **explanation,
1264
+ }
1265
+ )
1266
  print(
1267
  f"[model] Prediction succeeded for {score_id}: "
1268
  f"value={prediction['value']:.4f}, windows={prediction['n_graph_windows']}"
frontend/app/(dashboard)/dashboard/page.tsx CHANGED
@@ -2,7 +2,7 @@
2
 
3
  import Link from 'next/link'
4
  import { useEffect, useMemo, useState } from 'react'
5
- import { useQuery } from '@tanstack/react-query'
6
  import {
7
  Bar,
8
  BarChart,
@@ -94,25 +94,25 @@ const DASHBOARD_METRICS: DashboardMetric[] = [
94
  ],
95
  },
96
  {
97
- id: 'sustained_attention',
98
- label: 'Sustained Attention',
99
- shortLabel: 'Attention',
100
- range: [0, 1],
101
- average: 0.53,
102
  trend: 1.9,
103
  accent: '#EC4899',
104
  accentSoft: '#FCE7F3',
105
- distribution: [0.08, 0.13, 0.19, 0.24, 0.29, 0.35, 0.41, 0.47, 0.53, 0.58, 0.64, 0.71, 0.77, 0.84, 0.91],
106
- cohortSplit: [0.47, 0.59],
107
  confidence: 0.9,
108
  reliability: 'Stable across sessions',
109
- insight: 'Attention performance tracks dorsal attention synchronization with stronger stability in mid-range sustained-control profiles.',
110
  topRegions: [
111
- { name: 'Superior Parietal Cortex', contribution: 95 },
112
- { name: 'Frontal Eye Fields', contribution: 86 },
113
  { name: 'Precuneus', contribution: 80 },
114
- { name: 'Middle Frontal Gyrus', contribution: 76 },
115
- { name: 'Visual Association Cortex', contribution: 69 },
116
  ],
117
  },
118
  {
@@ -164,7 +164,7 @@ const DASHBOARD_METRICS: DashboardMetric[] = [
164
  const METRIC_VISUALS: Record<string, Pick<DashboardMetric, 'accent' | 'accentSoft'>> = {
165
  listsort_ageadj: { accent: '#3B82F6', accentSoft: '#DBEAFE' },
166
  pmat: { accent: '#8B5CF6', accentSoft: '#EDE9FE' },
167
- sustained_attention: { accent: '#EC4899', accentSoft: '#FCE7F3' },
168
  emotion_recognition: { accent: '#EF4444', accentSoft: '#FEE2E2' },
169
  psqi: { accent: '#F97316', accentSoft: '#FFEDD5' },
170
  }
@@ -271,32 +271,37 @@ function BrainCard({ metric }: { metric: DashboardMetric }) {
271
  </div>
272
 
273
  <div className='mt-4 space-y-2'>
274
- {topRegions.map((region, index) => (
275
- <div key={region.name} className='rounded-[0.95rem] border border-slate-200/80 bg-white/80 px-3 py-2 shadow-sm'>
276
- <div className='mb-1.5 flex items-center justify-between gap-3'>
277
- <div className='flex items-center gap-3'>
278
- <span
279
- className='inline-flex h-6 w-6 items-center justify-center rounded-full text-[11px] font-semibold text-white shadow-sm'
280
- style={{ background: metric.accent }}
281
- >
282
- {index + 1}
283
- </span>
284
- <span className='text-[12px] font-medium text-slate-900'>{region.name}</span>
 
 
 
 
 
 
 
 
 
 
 
 
285
  </div>
286
- <span className='text-[12px] font-semibold text-slate-950'>{region.contribution}%</span>
287
- </div>
288
- <div className='h-2 rounded-full bg-slate-100'>
289
- <div
290
- className='h-full rounded-full transition-all duration-500'
291
- style={{
292
- width: `${region.contribution}%`,
293
- background: `linear-gradient(90deg, ${metric.accent}, ${metric.accent}bb)`,
294
- boxShadow: `0 0 18px ${metric.accent}55`,
295
- }}
296
- />
297
  </div>
 
 
 
 
298
  </div>
299
- ))}
300
  </div>
301
  </div>
302
  )
@@ -368,6 +373,8 @@ function BoxplotStrip({ metric }: { metric: DashboardMetric }) {
368
 
369
  export default function DashboardPage() {
370
  const [selectedMetricId, setSelectedMetricId] = useState<string>(DASHBOARD_METRICS[0].id)
 
 
371
 
372
  const { data: stats, isLoading, error } = useQuery<DashboardStats>({
373
  queryKey: ['dashboardStats'],
@@ -376,7 +383,7 @@ export default function DashboardPage() {
376
 
377
  const dashboardMetrics = useMemo<DashboardMetric[]>(() => {
378
  const actualMetrics = stats?.dashboard_metrics ?? []
379
- if (actualMetrics.length === 0) return DASHBOARD_METRICS
380
 
381
  return actualMetrics.map((metric) => {
382
  const visual = METRIC_VISUALS[metric.id]
@@ -385,6 +392,8 @@ export default function DashboardPage() {
385
  ...metric,
386
  accent: visual?.accent ?? fallback?.accent ?? '#3B82F6',
387
  accentSoft: visual?.accentSoft ?? fallback?.accentSoft ?? '#DBEAFE',
 
 
388
  }
389
  })
390
  }, [stats?.dashboard_metrics])
@@ -400,10 +409,26 @@ export default function DashboardPage() {
400
  }
401
  }, [dashboardMetrics, selectedMetricId])
402
 
403
- const histogramData = useMemo(() => buildHistogram(selectedMetric), [selectedMetric])
404
- const histogramTicks = useMemo(() => buildHistogramTicks(selectedMetric), [selectedMetric])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
405
  const histogramColors = useMemo(
406
- () => histogramBarColors(selectedMetric, histogramData.length),
407
  [histogramData.length, selectedMetric]
408
  )
409
 
@@ -417,9 +442,8 @@ export default function DashboardPage() {
417
 
418
  const cohortSize = Math.max(
419
  safeStats.completed,
420
- selectedMetric.distribution.length,
421
- safeStats.recentUploads.length,
422
- 18
423
  )
424
 
425
  const successRate =
 
2
 
3
  import Link from 'next/link'
4
  import { useEffect, useMemo, useState } from 'react'
5
+ import { useQuery, useQueryClient } from '@tanstack/react-query'
6
  import {
7
  Bar,
8
  BarChart,
 
94
  ],
95
  },
96
  {
97
+ id: 'picseq',
98
+ label: 'PicSeq (Picture Sequence Memory)',
99
+ shortLabel: 'PicSeq',
100
+ range: [50, 150],
101
+ average: 102,
102
  trend: 1.9,
103
  accent: '#EC4899',
104
  accentSoft: '#FCE7F3',
105
+ distribution: [66, 72, 77, 83, 88, 92, 96, 102, 107, 111, 116, 121, 126, 132, 138],
106
+ cohortSplit: [96, 108],
107
  confidence: 0.9,
108
  reliability: 'Stable across sessions',
109
+ insight: 'Picture-sequence memory patterns reflect distributed episodic-memory and associative network coordination.',
110
  topRegions: [
111
+ { name: 'Hippocampus', contribution: 95 },
112
+ { name: 'Parahippocampal Cortex', contribution: 86 },
113
  { name: 'Precuneus', contribution: 80 },
114
+ { name: 'Posterior Cingulate', contribution: 76 },
115
+ { name: 'Temporal Association Cortex', contribution: 69 },
116
  ],
117
  },
118
  {
 
164
  const METRIC_VISUALS: Record<string, Pick<DashboardMetric, 'accent' | 'accentSoft'>> = {
165
  listsort_ageadj: { accent: '#3B82F6', accentSoft: '#DBEAFE' },
166
  pmat: { accent: '#8B5CF6', accentSoft: '#EDE9FE' },
167
+ picseq: { accent: '#EC4899', accentSoft: '#FCE7F3' },
168
  emotion_recognition: { accent: '#EF4444', accentSoft: '#FEE2E2' },
169
  psqi: { accent: '#F97316', accentSoft: '#FFEDD5' },
170
  }
 
271
  </div>
272
 
273
  <div className='mt-4 space-y-2'>
274
+ {topRegions.length > 0 ? (
275
+ topRegions.map((region, index) => (
276
+ <div key={region.name} className='rounded-[0.95rem] border border-slate-200/80 bg-white/80 px-3 py-2 shadow-sm'>
277
+ <div className='mb-1.5 flex items-center justify-between gap-3'>
278
+ <div className='flex items-center gap-3'>
279
+ <span
280
+ className='inline-flex h-6 w-6 items-center justify-center rounded-full text-[11px] font-semibold text-white shadow-sm'
281
+ style={{ background: metric.accent }}
282
+ >
283
+ {index + 1}
284
+ </span>
285
+ <span className='text-[12px] font-medium text-slate-900'>{region.name}</span>
286
+ </div>
287
+ </div>
288
+ <div className='h-2 rounded-full bg-slate-100'>
289
+ <div
290
+ className='h-full rounded-full transition-all duration-500'
291
+ style={{
292
+ width: `${region.contribution}%`,
293
+ background: `linear-gradient(90deg, ${metric.accent}, ${metric.accent}bb)`,
294
+ boxShadow: `0 0 18px ${metric.accent}55`,
295
+ }}
296
+ />
297
  </div>
 
 
 
 
 
 
 
 
 
 
 
298
  </div>
299
+ ))
300
+ ) : (
301
+ <div className='rounded-[0.95rem] border border-dashed border-slate-200 bg-white/70 px-4 py-6 text-center text-[12px] text-slate-500'>
302
+ No participant-level brain-region explanation is available for this metric yet.
303
  </div>
304
+ )}
305
  </div>
306
  </div>
307
  )
 
373
 
374
  export default function DashboardPage() {
375
  const [selectedMetricId, setSelectedMetricId] = useState<string>(DASHBOARD_METRICS[0].id)
376
+ const [hasRequestedBackfill, setHasRequestedBackfill] = useState(false)
377
+ const queryClient = useQueryClient()
378
 
379
  const { data: stats, isLoading, error } = useQuery<DashboardStats>({
380
  queryKey: ['dashboardStats'],
 
383
 
384
  const dashboardMetrics = useMemo<DashboardMetric[]>(() => {
385
  const actualMetrics = stats?.dashboard_metrics ?? []
386
+ if (actualMetrics.length === 0) return []
387
 
388
  return actualMetrics.map((metric) => {
389
  const visual = METRIC_VISUALS[metric.id]
 
392
  ...metric,
393
  accent: visual?.accent ?? fallback?.accent ?? '#3B82F6',
394
  accentSoft: visual?.accentSoft ?? fallback?.accentSoft ?? '#DBEAFE',
395
+ insight: metric.insight || fallback?.insight || '',
396
+ topRegions: metric.topRegions ?? [],
397
  }
398
  })
399
  }, [stats?.dashboard_metrics])
 
409
  }
410
  }, [dashboardMetrics, selectedMetricId])
411
 
412
+ useEffect(() => {
413
+ if (hasRequestedBackfill || !stats) return
414
+ const hasCompletedHistory = (stats.completed_analyses ?? 0) > 0
415
+ const hasDashboardMetrics = (stats.dashboard_metrics?.length ?? 0) > 0
416
+ const hasMissingTopRegions = (stats.dashboard_metrics ?? []).some(
417
+ (metric) => !metric.topRegions || metric.topRegions.length === 0
418
+ )
419
+ if (!hasCompletedHistory) return
420
+ if (hasDashboardMetrics && !hasMissingTopRegions) return
421
+
422
+ setHasRequestedBackfill(true)
423
+ void analysisService.backfillDashboardSummaries()
424
+ .then(() => queryClient.invalidateQueries({ queryKey: ['dashboardStats'] }))
425
+ .catch(() => undefined)
426
+ }, [hasRequestedBackfill, queryClient, stats])
427
+
428
+ const histogramData = useMemo(() => (selectedMetric ? buildHistogram(selectedMetric) : []), [selectedMetric])
429
+ const histogramTicks = useMemo(() => (selectedMetric ? buildHistogramTicks(selectedMetric) : []), [selectedMetric])
430
  const histogramColors = useMemo(
431
+ () => (selectedMetric ? histogramBarColors(selectedMetric, histogramData.length) : []),
432
  [histogramData.length, selectedMetric]
433
  )
434
 
 
442
 
443
  const cohortSize = Math.max(
444
  safeStats.completed,
445
+ safeStats.totalUploads,
446
+ safeStats.recentUploads.length
 
447
  )
448
 
449
  const successRate =
frontend/lib/api.ts CHANGED
@@ -71,6 +71,7 @@ export const api = {
71
  getUploadContent: (uploadId: string, params?: { max_lines?: number; max_chars?: number }) =>
72
  apiClient.get(`/api/upload/${uploadId}/content`, { params }),
73
  getDashboardStats: () => apiClient.get('/api/dashboard'),
 
74
  getModelPerformance: () => apiClient.get('/api/model-performance'),
75
  retryAnalysis: (executionId: string) =>
76
  apiClient.post(`/api/retry/${executionId}`),
 
71
  getUploadContent: (uploadId: string, params?: { max_lines?: number; max_chars?: number }) =>
72
  apiClient.get(`/api/upload/${uploadId}/content`, { params }),
73
  getDashboardStats: () => apiClient.get('/api/dashboard'),
74
+ backfillDashboardSummaries: () => apiClient.post('/api/dashboard/backfill'),
75
  getModelPerformance: () => apiClient.get('/api/model-performance'),
76
  retryAnalysis: (executionId: string) =>
77
  apiClient.post(`/api/retry/${executionId}`),
frontend/lib/services/analysisService.ts CHANGED
@@ -125,6 +125,15 @@ export const analysisService = {
125
  }
126
  },
127
 
 
 
 
 
 
 
 
 
 
128
  async retryAnalysis(executionId: string): Promise<AnalysisResponse> {
129
  try {
130
  const response = await api.retryAnalysis(executionId)
 
125
  }
126
  },
127
 
128
+ async backfillDashboardSummaries(): Promise<{ processed_executions: number; inserted_summary_rows: number }> {
129
+ try {
130
+ const response = await api.backfillDashboardSummaries()
131
+ return response.data as { processed_executions: number; inserted_summary_rows: number }
132
+ } catch (error) {
133
+ return handleServiceError(error)
134
+ }
135
+ },
136
+
137
  async retryAnalysis(executionId: string): Promise<AnalysisResponse> {
138
  try {
139
  const response = await api.retryAnalysis(executionId)