Spaces:
Paused

File size: 13,639 Bytes
d0d8df8
 
c933dc4
d0d8df8
 
 
 
 
c933dc4
d0d8df8
 
 
 
 
5bd1213
c933dc4
d0d8df8
 
 
 
 
 
 
 
 
 
 
 
 
be160fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d0d8df8
 
 
 
 
c933dc4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d0d8df8
 
 
 
5bd1213
c933dc4
d0d8df8
 
 
 
 
 
 
 
c933dc4
 
 
 
d0d8df8
 
c933dc4
d0d8df8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5bd1213
d0d8df8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c933dc4
d0d8df8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c933dc4
d0d8df8
be160fd
 
 
 
 
 
 
 
d0d8df8
 
 
 
 
 
 
 
 
 
 
c933dc4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
be160fd
c933dc4
 
 
 
 
 
 
d0d8df8
 
 
 
 
 
5bd1213
c933dc4
 
 
 
 
 
41179e2
d0d8df8
 
 
 
 
17e1ada
d0d8df8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
be160fd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
'use client'

import { useMemo, useState } from 'react'
import { SCORE_CATEGORIES, SCORE_REGISTRY, getScoresByCategory, ScoreDefinition } from '@/lib/score-registry'
import { SimulatedScoreResult } from '@/lib/score-simulator'
import { computeScoreTopLinks } from '@/lib/score-links'
import { ConnectomeLink } from '@/lib/types'
import { getROIInfo } from '@/lib/shen268-labels'
import { LazyImportanceBrain } from '@/components/LazyImportanceBrain'

interface BrainVisualizationPanelProps {
  predictedValues: Record<string, SimulatedScoreResult>
  correlationMatrix: number[][]
  connectomeHtml?: string | null
  importanceBrainUrl?: string | null
  importanceStaticBrainUrl?: string | null
  selectedScoreId: string | null
  onSelectScore: (scoreId: string) => void
}

const TOP_K_OPTIONS = [3, 5, 10, 20, 50]

function formatValue(value: number, scoreDef: ScoreDefinition): string {
  const range = scoreDef.scoreRange[1] - scoreDef.scoreRange[0]
  if (range <= 1) return value.toFixed(2)
  if (range <= 30) return value.toFixed(1)
  return Math.round(value).toString()
}

function formatPredictionValue(value: number, scoreDef: ScoreDefinition, valueScale?: string): string {
  if (valueScale === 'normalized') return value.toFixed(3)
  return formatValue(value, scoreDef)
}

function formatPredictionUnit(scoreDef: ScoreDefinition, valueScale?: string): string {
  if (valueScale === 'normalized') return 'normalized'
  return scoreDef.unit
}

function sourceBadgeClass(source?: string): string {
  return source === 'model'
    ? 'bg-emerald-100 text-emerald-800 border-emerald-300/80'
    : 'bg-amber-100 text-amber-800 border-amber-300/80'
}

const linkBadgeClass = (link: ConnectomeLink) =>
  link.sign === 'positive'
    ? 'bg-rose-100 text-rose-800 border-rose-300/70'
    : 'bg-blue-100 text-blue-800 border-blue-300/70'

function ScoreInfoTooltip({ score }: { score: ScoreDefinition }) {
  return (
    <span className='group relative inline-flex'>
      <span
        className='inline-flex h-6 w-6 items-center justify-center rounded-full border border-brand-400/25 bg-white text-[11px] font-bold text-ink-700 shadow-sm transition hover:border-brand-500/50 hover:text-ink-950'
        aria-label={`Information about ${score.name}`}
        tabIndex={0}
      >
        i
      </span>
      <span className='pointer-events-none absolute left-1/2 top-full z-30 mt-2 hidden w-[min(22rem,80vw)] -translate-x-1/2 rounded-2xl border border-slate-200 bg-white p-4 text-left text-xs leading-relaxed text-slate-700 shadow-xl group-hover:inline-block group-focus-within:inline-block'>
        <span className='block text-sm font-semibold text-slate-950'>{score.name}</span>
        {score.domain ? (
          <span className='mt-2 block'>
            <span className='font-semibold text-slate-950'>Area: </span>
            {score.domain}
          </span>
        ) : null}
        {score.construct ? (
          <span className='mt-1.5 block'>
            <span className='font-semibold text-slate-950'>Measures: </span>
            {score.construct}
          </span>
        ) : null}
        {score.measureName ? (
          <span className='mt-1.5 block'>
            <span className='font-semibold text-slate-950'>Full measure: </span>
            {score.measureName}
          </span>
        ) : null}
        {score.detail ? <span className='mt-2 block text-slate-600'>{score.detail}</span> : null}
        {score.interpretation ? (
          <span className='mt-3 block rounded-xl bg-slate-50 p-3'>
            <span className='font-semibold text-slate-950'>How to read it: </span>
            {score.interpretation}
          </span>
        ) : null}
      </span>
    </span>
  )
}

export default function BrainVisualizationPanel({
  predictedValues,
  correlationMatrix,
  connectomeHtml,
  importanceBrainUrl,
  importanceStaticBrainUrl,
  selectedScoreId,
  onSelectScore,
}: BrainVisualizationPanelProps) {
  const [topK, setTopK] = useState(10)
  const [minR, setMinR] = useState(0)
  const [showDetails, setShowDetails] = useState(false)

  const selectedScore = useMemo(
    () =>
      SCORE_REGISTRY.find((s) => s.id === selectedScoreId) ??
      SCORE_REGISTRY.find((s) => s.id === 'listsort_ageadj') ??
      null,
    [selectedScoreId]
  )
  const effectiveSelectedScoreId = selectedScore?.id ?? null

  const topLinks = useMemo(() => {
    if (!selectedScore) return []
    return computeScoreTopLinks(correlationMatrix, selectedScore, topK, minR)
  }, [correlationMatrix, selectedScore, topK, minR])

  const relevantLobes = useMemo(() => {
    if (!selectedScore) return []
    const lobes = new Set<string>()
    for (const roi of selectedScore.relevantROIs) {
      const info = getROIInfo(roi)
      if (info) lobes.add(`${info.hemisphere} ${info.lobe}`)
    }
    return Array.from(lobes).sort()
  }, [selectedScore])

  const result = selectedScore ? predictedValues[selectedScore.id] : null
  const showImportanceBrain = Boolean(importanceBrainUrl)

  return (
    <div className='surface-card space-y-3'>
      {/* Score selector tabs */}
      <div className='space-y-2'>
        {SCORE_CATEGORIES.map((category) => {
          const scores = getScoresByCategory(category.id)
          if (scores.length === 0) return null
          return (
            <div key={category.id} className='flex flex-wrap items-center gap-1.5'>
              <span className='text-[10px] uppercase tracking-wider text-ink-600 font-semibold w-16 shrink-0'>
                {category.label}
              </span>
              {scores.map((scoreDef) => {
                const sv = predictedValues[scoreDef.id]
                const isActive = effectiveSelectedScoreId === scoreDef.id
                return (
                  <button
                    key={scoreDef.id}
                    type='button'
                    onClick={() => onSelectScore(scoreDef.id)}
                    className={`flex items-center gap-1.5 rounded-lg px-2.5 py-1.5 text-xs font-medium transition border ${
                      isActive
                        ? 'bg-white border-brand-500/40 shadow-sm text-ink-950'
                        : 'bg-white/50 border-brand-400/20 text-ink-700 hover:bg-white/80'
                    }`}
                  >
                    <span
                      className='w-2 h-2 rounded-full shrink-0'
                      style={{ background: scoreDef.accentColor }}
                    />
                    <span>{scoreDef.shortName}</span>
                    <ScoreInfoTooltip score={scoreDef} />
                    {sv && (
                      <>
                        <span className='font-semibold' style={{ color: scoreDef.accentColor }}>
                          {formatPredictionValue(sv.value, scoreDef, sv.valueScale)}
                        </span>
                        <span className={`rounded-full border px-1.5 py-0.5 text-[9px] font-semibold uppercase tracking-wide ${sourceBadgeClass(sv.source)}`}>
                          {sv.source === 'model' ? 'Model' : 'Sim'}
                        </span>
                      </>
                    )}
                  </button>
                )
              })}
            </div>
          )
        })}
      </div>

      {/* Selected score summary */}
      {selectedScore && result && (
        <div className='border-t border-brand-400/10 pt-2'>
          <div className='flex items-baseline justify-between gap-3'>
            <div>
              <div className='group flex items-center gap-2'>
                <p className='text-sm font-semibold text-ink-950'>{selectedScore.name}</p>
                <ScoreInfoTooltip score={selectedScore} />
              </div>
              <p className='text-[11px] text-ink-600'>{selectedScore.description}</p>
              <p className='mt-1 flex flex-wrap items-center gap-1.5 text-[10px] text-ink-600'>
                <span className={`rounded-full border px-2 py-0.5 font-semibold uppercase tracking-wide ${sourceBadgeClass(result.source)}`}>
                  {result.source === 'model' ? 'Model prediction' : 'Simulated fallback'}
                </span>
                {result.modelFile && <span>File: {result.modelFile}</span>}
                {result.modelArchitecture && <span>Architecture: {result.modelArchitecture}</span>}
                {result.nGraphWindows && <span>Windows: {result.nGraphWindows}</span>}
                {result.normalizedValue !== undefined && result.valueScale === 'original' && (
                  <span>Normalized: {result.normalizedValue.toFixed(3)}</span>
                )}
              </p>
            </div>
            <div className='text-right shrink-0'>
              <span className='text-xl font-semibold' style={{ color: selectedScore.accentColor }}>
                {formatPredictionValue(result.value, selectedScore, result.valueScale)}
              </span>
              <span className='text-xs text-ink-600 ml-1'>
                {formatPredictionUnit(selectedScore, result.valueScale)}
              </span>
              <p className='text-[10px] text-ink-600'>
                95% CI: {formatPredictionValue(result.ci95Lower, selectedScore, result.valueScale)} - {formatPredictionValue(result.ci95Upper, selectedScore, result.valueScale)}
              </p>
            </div>
          </div>
        </div>
      )}

      {/* 3D Connectome */}
      <div className='rounded-xl border border-brand-400/20 bg-white/82 overflow-hidden'>
        {showImportanceBrain && importanceBrainUrl ? (
          <LazyImportanceBrain
            interactiveUrl={importanceBrainUrl}
            staticUrl={importanceStaticBrainUrl}
            title={`Global ${selectedScore?.shortName ?? 'score'} model importance brain`}
            className='h-[500px]'
          />
        ) : connectomeHtml ? (
          <iframe
            title={`Connectome for ${selectedScore?.shortName ?? 'brain'}`}
            srcDoc={connectomeHtml}
            className='w-full border-0'
            style={{ height: '400px' }}
            loading='lazy'
            sandbox='allow-scripts allow-same-origin'
          />
        ) : (
          <div className='flex items-center justify-center h-48 text-sm text-ink-700'>
            Connectome not available
          </div>
        )}
      </div>

      {/* Collapsible details */}
      {selectedScore && (
        <div>
          <button
            type='button'
            onClick={() => setShowDetails(!showDetails)}
            className='text-xs text-ink-600 hover:text-ink-900 transition'
          >
            {showDetails ? 'Hide' : 'Show'} connection details ({topLinks.length} links)
          </button>

          {showDetails && (
            <div className='mt-2 space-y-3'>
              <div className='flex flex-wrap items-center gap-2'>
                <label className='text-xs text-ink-700'>
                  Top&#8209;k:
                  <select
                    value={topK}
                    onChange={(e) => setTopK(Number(e.target.value))}
                    className='ml-1 rounded-lg border border-brand-400/25 bg-white/80 px-2 py-1 text-xs text-ink-800'
                  >
                    {TOP_K_OPTIONS.map((k) => (
                      <option key={k} value={k}>{k}</option>
                    ))}
                  </select>
                </label>
                <label className='text-xs text-ink-700'>
                  Min |r|:
                  <input
                    type='number'
                    min={0}
                    max={1}
                    step={0.05}
                    value={minR}
                    onChange={(e) => setMinR(Math.max(0, Math.min(1, Number(e.target.value))))}
                    className='ml-1 w-16 rounded-lg border border-brand-400/25 bg-white/80 px-2 py-1 text-xs text-ink-800'
                  />
                </label>
              </div>

              {topLinks.length > 0 ? (
                <div className='rounded-xl border border-brand-400/20 bg-white/85 p-3'>
                  <p className='font-semibold text-ink-900 mb-2 text-sm'>
                    Top {topLinks.length} links for {selectedScore.shortName}
                  </p>
                  <div className='space-y-1.5'>
                    {topLinks.map((link, index) => (
                      <div key={`${link.source_roi}-${link.target_roi}-${index}`} className='flex flex-wrap items-center gap-1.5 text-xs'>
                        <span className='inline-flex rounded-full px-2 py-0.5 border text-[10px] font-semibold bg-white border-brand-400/25 text-ink-800'>
                          #{index + 1}
                        </span>
                        <span className='text-ink-900 font-medium'>
                          {link.source_label} &lt;-&gt; {link.target_label}
                        </span>
                        <span className={`inline-flex rounded-full border px-2 py-0.5 text-[10px] font-semibold ${linkBadgeClass(link)}`}>
                          {link.sign}
                        </span>
                        <span className='text-ink-700'>r = {link.weight.toFixed(4)}</span>
                      </div>
                    ))}
                  </div>
                </div>
              ) : (
                <p className='text-xs text-ink-600'>No connections above threshold.</p>
              )}

              <p className='text-[10px] text-ink-600'>
                Regions: {relevantLobes.join(', ')} ({selectedScore.relevantROIs.length} ROIs)
              </p>
            </div>
          )}
        </div>
      )}
    </div>
  )
}