Spaces:
Running

BHA / app.js
LidongYang's picture
NSD: a random sample of 100 test images with their cortical maps
f578741 verified
Raw History Blame Contribute Delete
22.3 kB
// BHA demo: static viewer of precomputed retrieval rankings and reconstructions.
// Data layout: data/<dataset>/{meta.json, images/, recon/<subject>/, q/<subject>.json, sig/<subject>.bin}
// A dataset with large recordings stores them in files of meta.sig_chunk test images: sig/<subject>/KK.bin
// A dataset that is shown by a sample of its test images lists them in meta.queries: only those can be
// picked and only their pictures are shipped; other candidates appear as a tile without a picture.
// Such a dataset shows its recording as a picture too: map/<subject>/NNNN.webp, listed in meta.map.
'use strict';
const DATASET_TITLES = {
'things-eeg2': 'EEG · THINGS-EEG2',
'things-meg': 'MEG · THINGS-MEG',
nsd: 'fMRI · NSD',
tvsd: 'MUA · TVSD',
};
const READOUT_TITLES = {
gated: 'BHA (composed)',
shared: 'Shared readout',
openclip: 'OpenCLIP expert',
dinov2l: 'DINOv2 expert',
mae: 'MAE expert',
dfn: 'DFN expert',
stage1: 'Stage 1 backbone',
};
const RECORDING_NOUN = { 'things-eeg2': 'EEG', 'things-meg': 'MEG', nsd: 'fMRI', tvsd: 'multi-unit' };
const SUBJECT_NOUN = { tvsd: 'Animal' };
const PAGE_SIZE = 48;
const cache = new Map();
const state = { ds: null, sub: null, idx: 0, page: [], token: 0 };
const $ = (id) => document.getElementById(id);
const pad4 = (i) => String(i).padStart(4, '0');
function once(key, make) {
if (!cache.has(key)) cache.set(key, make());
return cache.get(key);
}
const getJSON = (url) => once(url, () => fetch(url).then((r) => { if (!r.ok) throw new Error(url + ' ' + r.status); return r.json(); }));
const getBin = (url) => once(url, () => fetch(url).then((r) => { if (!r.ok) throw new Error(url + ' ' + r.status); return r.arrayBuffer(); }).then((b) => new Int8Array(b)));
const imageUrl = (ds, i) => `data/${ds}/images/${pad4(i)}.jpg`;
const reconUrl = (ds, sub, i, k) => `data/${ds}/recon/${sub}/${pad4(i)}_${k}.jpg`;
function labelOf(meta, i) {
if (meta.labels && meta.labels[i]) return meta.labels[i].replace(/_/g, ' ');
return `image ${i + 1}`;
}
function el(tag, props = {}, children = []) {
const node = document.createElement(tag);
for (const [k, v] of Object.entries(props)) {
if (k === 'class') node.className = v;
else if (k === 'text') node.textContent = v;
else node.setAttribute(k, v);
}
for (const child of children) node.append(child);
return node;
}
const hasImage = (meta, i) => !meta.queries || meta.queries.includes(i);
function card(src, caption, hit, alt) {
const fig = el('figure', { class: 'card' + (hit ? ' hit' : '') });
if (src) fig.append(el('img', { src, alt: alt || caption, loading: 'lazy' }));
else fig.append(el('div', { class: 'blank', role: 'img', 'aria-label': alt || caption, text: 'another test image' }));
const cap = el('figcaption', { text: caption });
if (hit) cap.append(' ', el('span', { class: 'hitmark', text: '✓', 'aria-label': 'the shown image' }));
fig.append(cap);
return fig;
}
function samplePage(n, keep) {
let picks;
if (n <= PAGE_SIZE) picks = Array.from({ length: n }, (_, i) => i);
else {
const set = new Set([keep]);
while (set.size < PAGE_SIZE) set.add(Math.floor(Math.random() * n));
picks = [...set];
}
return picks.sort((a, b) => a - b);
}
// Time courses of one test image, one line per channel (EEG), sensor (MEG) or recording site (MUA).
// `time` = {sfreq, tmin} of the stored samples in seconds; the dashed line is image onset.
const PALETTES = {
blue: { light: [198, 219, 239], dark: [8, 69, 148], bold: ['#6baed6', '#2171b5', '#08306b'] },
green: { light: [199, 233, 192], dark: [0, 109, 44], bold: ['#74c476', '#238b45', '#00441b'] },
violet: { light: [218, 218, 235], dark: [84, 39, 143], bold: ['#9e9ac8', '#6a51a3', '#3f007d'] },
};
function niceStep(span) {
for (const step of [10, 20, 25, 50, 100, 200, 250, 500]) if (span / step <= 6) return step;
return 1000;
}
function drawTraces(bin, shape, index, time, palette, extra = {}) {
const means = extra.means || []; // last rows: mean of an area, drawn bold
const steps = shape[1], channels = shape[0] - means.length;
const S = 2, W = 480 * S, H = 300 * S;
const canvas = $('signal');
canvas.width = W;
canvas.height = H;
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, W, H);
const darkMode = matchMedia('(prefers-color-scheme: dark)').matches;
const ink = darkMode ? '#ececec' : '#1c1d1f', muted = darkMode ? '#a3a7ad' : '#5d6066';
const left = 12 * S, right = W - 12 * S, top = 12 * S, bottom = H - 40 * S;
const first = time.tmin * 1000, dt = 1000 / time.sfreq, last = first + (steps - 1) * dt;
const from = Math.min(first, time.from === undefined ? first : time.from * 1000);
const x = (t) => left + ((t - from) / (last - from)) * (right - left);
const offset = index * shape[0] * steps;
let lo = Infinity, hi = -Infinity;
for (let p = 0; p < channels * steps; p++) {
const v = bin[offset + p];
if (v < lo) lo = v;
if (v > hi) hi = v;
}
if (hi === lo) hi = lo + 1;
const y = (v) => bottom - ((v - lo) / (hi - lo)) * (bottom - top);
const { light, dark, bold } = PALETTES[palette];
if (extra.window) { // samples the model reads
ctx.fillStyle = darkMode ? 'rgba(255, 255, 255, .07)' : 'rgba(0, 0, 0, .05)';
ctx.fillRect(x(extra.window[0] * 1000), top, x(extra.window[1] * 1000) - x(extra.window[0] * 1000), bottom - top);
}
ctx.lineJoin = 'round';
ctx.lineWidth = (channels > 100 ? 0.9 : 1.1) * S;
ctx.globalAlpha = Math.max(0.15, Math.min(0.75, 48 / channels));
for (let c = 0; c < channels; c++) {
const f = channels > 1 ? c / (channels - 1) : 1;
ctx.strokeStyle = `rgb(${light.map((l, k) => Math.round(l + f * (dark[k] - l))).join(',')})`;
ctx.beginPath();
for (let t = 0; t < steps; t++) {
const px = x(first + t * dt), py = y(bin[offset + c * steps + t]);
if (t) ctx.lineTo(px, py); else ctx.moveTo(px, py);
}
ctx.stroke();
}
ctx.globalAlpha = 1;
means.forEach((name, m) => {
const row = offset + (channels + m) * steps;
ctx.lineWidth = 5 * S;
ctx.strokeStyle = darkMode ? 'rgba(19, 20, 22, .85)' : 'rgba(255, 255, 255, .85)';
for (const pass of [0, 1]) {
ctx.beginPath();
for (let t = 0; t < steps; t++) {
const px = x(first + t * dt), py = y(bin[row + t]);
if (t) ctx.lineTo(px, py); else ctx.moveTo(px, py);
}
ctx.stroke();
ctx.lineWidth = 2.6 * S;
ctx.strokeStyle = bold[m % bold.length];
}
});
// key of the bold lines, in the corner before onset
ctx.font = `600 ${12 * S}px system-ui, -apple-system, "Segoe UI", Roboto, sans-serif`;
ctx.textAlign = 'left';
ctx.textBaseline = 'middle';
means.forEach((name, m) => {
const ky = top + (8 + m * 17) * S;
ctx.strokeStyle = bold[m % bold.length];
ctx.lineWidth = 3 * S;
ctx.beginPath();
ctx.moveTo(left + 2 * S, ky);
ctx.lineTo(left + 20 * S, ky);
ctx.stroke();
ctx.fillStyle = ink;
ctx.fillText(name, left + 25 * S, ky);
});
if (from <= 0 && last >= 0) {
ctx.strokeStyle = ink;
ctx.lineWidth = 1.6 * S;
ctx.setLineDash([6 * S, 5 * S]);
ctx.beginPath();
ctx.moveTo(x(0), top - 4 * S);
ctx.lineTo(x(0), bottom);
ctx.stroke();
ctx.setLineDash([]);
}
ctx.strokeStyle = muted;
ctx.fillStyle = muted;
ctx.lineWidth = S;
ctx.beginPath();
ctx.moveTo(left, bottom + 2 * S);
ctx.lineTo(right, bottom + 2 * S);
ctx.stroke();
ctx.font = `${12 * S}px system-ui, -apple-system, "Segoe UI", Roboto, sans-serif`;
ctx.textBaseline = 'top';
const step = niceStep(last - from);
for (let t = Math.ceil(from / step) * step; t <= last + 1e-6; t += step) {
ctx.beginPath();
ctx.moveTo(x(t), bottom + 2 * S);
ctx.lineTo(x(t), bottom + 7 * S);
ctx.stroke();
ctx.textAlign = x(t) - left < 14 * S ? 'left' : right - x(t) < 14 * S ? 'right' : 'center';
ctx.fillText(String(t), x(t), bottom + 10 * S);
}
ctx.textAlign = 'right';
ctx.fillText('ms from image onset', right, bottom + 25 * S);
}
const getImage = (url) => once(url, () => new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => resolve(img);
img.onerror = () => reject(new Error(url));
img.src = url;
}));
// Cortical flat map (fMRI): every pixel is a weighted mean of up to eight voxels around
// its position at mid-depth of the cortex. map.bin = pixel index, voxel indices, weights.
async function loadFlat(ds, sub) {
const base = `data/${ds}/flat/${sub}`;
const [info, labels, raw, under, roi] = await Promise.all([
getJSON(`${base}/map.json`),
getJSON(`${base}/labels.json`).catch(() => []),
once(`${base}/map.bin`, () => fetch(`${base}/map.bin`).then((r) => r.arrayBuffer())),
getImage(`${base}/under.png`),
getImage(`${base}/roi.png`),
]);
const n = info.N;
return {
info, labels, base,
under: regrey(under, info), roi: whiten(roi, info),
pix: new Uint32Array(raw, 0, n),
idx: new Uint16Array(raw, 4 * n, 8 * n),
wts: new Uint8Array(raw, 20 * n, 8 * n),
};
}
// Voxel responses are stored in files of `chunk` images, so showing one image
// fetches a few hundred kilobytes and not the whole test set.
const voxChunkUrl = (flat, index) => `${flat.base}/vox/${String(Math.floor(index / flat.info.chunk)).padStart(2, '0')}.bin`;
async function loadVox(flat, index) {
const part = await getBin(voxChunkUrl(flat, index));
return { part, offset: (index % flat.info.chunk) * flat.info.V };
}
// The curvature underlay in two mid greys and the area outlines in white.
function regrey(image, info) {
const canvas = document.createElement('canvas');
canvas.width = info.W;
canvas.height = info.H;
const ctx = canvas.getContext('2d', { willReadFrequently: true });
ctx.drawImage(image, 0, 0);
const frame = ctx.getImageData(0, 0, info.W, info.H);
for (let q = 0; q < frame.data.length; q += 4) {
const grey = frame.data[q] > 150 ? 172 : 136; // gyri, sulci
frame.data[q] = frame.data[q + 1] = frame.data[q + 2] = grey;
}
ctx.putImageData(frame, 0, 0);
return canvas;
}
function whiten(image, info) {
const canvas = document.createElement('canvas');
canvas.width = info.W;
canvas.height = info.H;
const ctx = canvas.getContext('2d');
ctx.drawImage(image, 0, 0);
ctx.globalCompositeOperation = 'source-in';
ctx.fillStyle = '#fff';
ctx.fillRect(0, 0, info.W, info.H);
return canvas;
}
const VIRIDIS = (() => {
const stops = ['440154', '482878', '3e4a89', '31688e', '26828e', '1f9e89', '35b779', '6ece58', 'b5de2b', 'fde725']
.map((h) => [0, 2, 4].map((k) => parseInt(h.slice(k, k + 2), 16)));
const at = [0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875, 0.9375, 1];
const table = new Uint8Array(256 * 3);
for (let i = 0, k = 0; i < 256; i++) {
const t = i / 255;
while (t > at[k + 1]) k++;
const f = (t - at[k]) / (at[k + 1] - at[k]);
for (let c = 0; c < 3; c++) table[i * 3 + c] = Math.round(stops[k][c] + f * (stops[k + 1][c] - stops[k][c]));
}
return table;
})();
function drawFlat(flat, vox) {
const { info, labels, under, roi, pix, idx, wts } = flat;
const { part, offset } = vox;
// the map is computed at its own resolution, then shown at twice that so the area names stay sharp
const buffer = flat.buffer || (flat.buffer = document.createElement('canvas'));
buffer.width = info.W;
buffer.height = info.H;
const ctx = buffer.getContext('2d', { willReadFrequently: true });
ctx.clearRect(0, 0, info.W, info.H);
ctx.drawImage(under, 0, 0);
const frame = ctx.getImageData(0, 0, info.W, info.H);
const data = frame.data;
for (let p = 0; p < info.N; p++) {
let sum = 0, total = 0;
for (let k = 0; k < 8; k++) {
const w = wts[p * 8 + k];
if (w) { sum += w * part[offset + idx[p * 8 + k]]; total += w; }
}
// response from weakest (dark violet) to strongest (yellow)
const v = total ? sum / total / 127 : 0;
const k = Math.round(Math.max(0, Math.min(1, (v + 1) / 2)) * 255) * 3;
const q = pix[p] * 4;
data[q] = VIRIDIS[k];
data[q + 1] = VIRIDIS[k + 1];
data[q + 2] = VIRIDIS[k + 2];
data[q + 3] = 255;
}
ctx.putImageData(frame, 0, 0);
ctx.drawImage(roi, 0, 0);
const canvas = $('signal');
canvas.width = info.W * FLAT_SCALE;
canvas.height = info.H * FLAT_SCALE;
const shown = canvas.getContext('2d');
shown.imageSmoothingQuality = 'high';
shown.drawImage(buffer, 0, 0, canvas.width, canvas.height);
drawAreaNames(shown, labels, canvas.width);
}
// Name of every outlined area at the point deepest inside it. Larger areas are placed
// first; a name that would cover another is moved up or down, or left out.
const FLAT_SCALE = 2;
function drawAreaNames(ctx, labels, width) {
const S = FLAT_SCALE, size = 15 * S;
ctx.font = `700 ${size}px system-ui, -apple-system, "Segoe UI", Roboto, sans-serif`;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.lineJoin = 'round';
const placed = [];
for (const label of labels.filter((l) => l.r >= 5).sort((a, b) => b.r - a.r)) {
const w = ctx.measureText(label.n).width + 3 * S, h = size * 0.95;
const x = Math.min(Math.max(label.x * S, w / 2), width - w / 2);
for (const shift of [0, -0.8, 0.8, -1.5, 1.5]) {
const y = label.y * S + shift * h;
const box = [x - w / 2, y - h / 2, x + w / 2, y + h / 2];
if (placed.some((b) => box[0] < b[2] && b[0] < box[2] && box[1] < b[3] && b[1] < box[3])) continue;
placed.push(box);
ctx.lineWidth = 3.5 * S;
ctx.strokeStyle = 'rgba(255, 255, 255, .92)';
ctx.strokeText(label.n, x, y);
ctx.fillStyle = '#111';
ctx.fillText(label.n, x, y);
break;
}
}
}
// The test images that can be picked: a random page of them, or the listed examples.
function pageOf(meta, keep) {
if (!meta.queries) return samplePage(meta.n, keep);
if (meta.queries.length <= PAGE_SIZE) return meta.queries.slice();
const set = new Set([keep]);
while (set.size < PAGE_SIZE) set.add(meta.queries[Math.floor(Math.random() * meta.queries.length)]);
return [...set].sort((x, y) => x - y);
}
function randomIndex(meta) {
return meta.queries ? meta.queries[Math.floor(Math.random() * meta.queries.length)] : Math.floor(Math.random() * meta.n);
}
function renderPicker(meta) {
const box = $('picker');
box.replaceChildren();
for (const i of state.page) {
const name = labelOf(meta, i);
const btn = el('button', { class: 'thumb', type: 'button', role: 'option', 'aria-selected': String(i === state.idx), title: name });
btn.append(el('img', { src: imageUrl(state.ds, i), alt: name, loading: 'lazy' }));
if (meta.labels) btn.append(el('span', { text: name }));
btn.addEventListener('click', () => select(i));
box.append(btn);
}
}
async function render() {
const token = ++state.token;
const { ds, sub, idx } = state;
const meta = await getJSON(`data/${ds}/meta.json`);
const q = await getJSON(`data/${ds}/q/${sub}.json`);
if (token !== state.token) return;
const name = labelOf(meta, idx);
$('seen').src = imageUrl(ds, idx);
$('seen').alt = `Test image: ${name}`;
$('title').textContent = meta.labels ? name.charAt(0).toUpperCase() + name.slice(1) : `Test image ${idx + 1}`;
const rank = q.rank[idx];
const noun = (SUBJECT_NOUN[ds] || 'Participant').toLowerCase();
const place = rank === 1 ? 'the first candidate' : `candidate ${rank}`;
const summary = $('summary');
summary.replaceChildren(
`From this ${noun}'s ${RECORDING_NOUN[ds] || 'brain'} recording alone, BHA ranked the image that was shown as `,
el('strong', { text: `${place} of ${meta.n}` }), '.');
const top5 = $('top5');
top5.replaceChildren();
q.top5[idx].forEach((j, k) => {
const caption = meta.labels ? `#${k + 1} ${labelOf(meta, j)}` : `#${k + 1}`;
top5.append(card(hasImage(meta, j) ? imageUrl(ds, j) : null, caption, j === idx, labelOf(meta, j)));
});
const count = (meta.recon && meta.recon[sub]) || 0;
const recon = $('recon');
recon.replaceChildren();
for (let k = 0; k < count; k++) recon.append(card(reconUrl(ds, sub, idx, k), `sample ${k + 1}`, false, `Reconstruction ${k + 1} of ${name}`));
$('recon-panel').hidden = count === 0;
if (count === 0) summary.append(' No reconstruction was generated for this recording.');
$('note').textContent = meta.note || '';
$('note').hidden = !meta.note;
const votes = $('votes');
const table = $('table');
votes.replaceChildren();
table.replaceChildren();
for (const key of meta.readouts) {
const vote = q.votes[key];
if (!vote) continue;
const best = vote.best[idx];
const hit = best === idx;
const title = READOUT_TITLES[key] || key;
votes.append(card(hasImage(meta, best) ? imageUrl(ds, best) : null, title.replace(' expert', ''), hit, `${title}: ${labelOf(meta, best)}`));
const guess = meta.labels ? labelOf(meta, best) : (hit ? 'the shown image' : 'another image');
const top1 = meta.top1 && meta.top1[sub] ? meta.top1[sub][key] : null;
const row = el('tr');
row.append(el('td', { text: title }), el('td', { text: `${vote.rank[idx]} of ${meta.n}` }));
const cell = el('td', { text: guess });
if (hit) cell.append(' ', el('span', { class: 'hitmark', text: '✓' }));
row.append(cell, el('td', { text: top1 == null ? '' : `${top1.toFixed(1)}%` }));
table.append(row);
}
const shape = meta.signal_view && meta.sig && meta.sig[sub];
const hasPicture = Boolean(meta.map && meta.map[sub]); // flat map drawn beforehand
const hasFlat = !hasPicture && Boolean(meta.flat && meta.flat[sub]); // flat map drawn here from the voxel responses
const hasMap = hasFlat || hasPicture;
$('signal-figure').hidden = !shape && !hasMap;
$('signal-figure').parentElement.classList.toggle('wide-signal', hasMap);
if (!hasMap) $('signal').classList.remove('zoomed');
$('signal').title = hasMap ? 'Click to enlarge' : '';
const MAP_CAPTION = 'The recording (cortical flat map, left and right hemisphere)';
const MAP_LEGEND = 'weaker <span class="ramp"></span> stronger response (z-scored, mean of 3 repetitions). '
+ 'Areas: early visual V1–hV4; faces OFA, FFA; bodies EBA, FBA; places OPA, PPA. Click the map to enlarge it.';
if (shape) {
const view = meta.signal_view;
$('signal-caption').textContent = view.caption;
$('signal-legend').textContent = view.legend;
$('signal').setAttribute('aria-label', view.caption);
// one file per participant, or files of sig_chunk images so that one image costs about a megabyte
const chunk = meta.sig_chunk;
const bin = await getBin(chunk ? `data/${ds}/sig/${sub}/${String(Math.floor(idx / chunk)).padStart(2, '0')}.bin` : `data/${ds}/sig/${sub}.bin`);
if (token === state.token) {
drawTraces(bin, shape, chunk ? idx % chunk : idx, view.time, view.palette, { means: view.means && view.means[sub], window: view.window });
}
} else if (hasPicture) {
$('signal-caption').textContent = MAP_CAPTION;
$('signal').setAttribute('aria-label', 'Voxel responses on the flattened visual cortex of this participant');
const picture = await getImage(`data/${ds}/map/${sub}/${pad4(idx)}.webp`);
if (token !== state.token) return;
const canvas = $('signal');
canvas.width = picture.naturalWidth;
canvas.height = picture.naturalHeight;
canvas.getContext('2d').drawImage(picture, 0, 0);
$('signal-legend').innerHTML = MAP_LEGEND;
} else if (hasFlat) {
$('signal-caption').textContent = MAP_CAPTION;
$('signal').setAttribute('aria-label', 'Voxel responses on the flattened visual cortex of this participant');
if (!cache.has(`data/${ds}/flat/${sub}/map.bin`)) $('signal-legend').textContent = 'Loading the cortical map…';
const flat = await loadFlat(ds, sub);
const vox = await loadVox(flat, idx);
if (token !== state.token) return;
$('signal-legend').innerHTML = MAP_LEGEND;
drawFlat(flat, vox);
}
}
function select(i) {
state.idx = i;
for (const btn of $('picker').children) btn.setAttribute('aria-selected', 'false');
const pos = state.page.indexOf(i);
if (pos >= 0) $('picker').children[pos].setAttribute('aria-selected', 'true');
render();
}
async function reshuffle() {
const meta = await getJSON(`data/${state.ds}/meta.json`);
state.idx = randomIndex(meta);
state.page = pageOf(meta, state.idx);
renderPicker(meta);
render();
}
async function setDataset(ds) {
state.ds = ds;
for (const btn of $('datasets').children) btn.setAttribute('aria-checked', String(btn.dataset.ds === ds));
const meta = await getJSON(`data/${ds}/meta.json`);
const select = $('subject');
select.replaceChildren(...meta.subjects.map((s) => el('option', { value: s, text: s })));
state.sub = meta.subjects[0];
$('subject-label').textContent = SUBJECT_NOUN[ds] || 'Participant';
$('shuffle').hidden = (meta.queries ? meta.queries.length : meta.n) <= PAGE_SIZE;
await reshuffle();
}
async function init() {
const datasets = await getJSON('data/index.json');
const box = $('datasets');
for (const ds of datasets) {
const btn = el('button', { type: 'button', role: 'radio', 'aria-checked': 'false', text: DATASET_TITLES[ds] || ds });
btn.dataset.ds = ds;
btn.addEventListener('click', () => setDataset(ds));
box.append(btn);
}
$('subject').addEventListener('change', (e) => { state.sub = e.target.value; render(); });
$('random').addEventListener('click', reshuffle);
$('shuffle').addEventListener('click', async () => {
const meta = await getJSON(`data/${state.ds}/meta.json`);
state.page = pageOf(meta, state.idx);
renderPicker(meta);
});
await setDataset(datasets[0]);
}
init().catch((err) => {
$('summary').textContent = 'The demo data could not be loaded: ' + err.message;
});
// The flat map opens large on a click, so the area names can be read.
$('signal').addEventListener('click', () => {
const canvas = $('signal');
if (canvas.closest('.pair').classList.contains('wide-signal')) canvas.classList.toggle('zoomed');
});
document.addEventListener('keydown', (event) => {
if (event.key === 'Escape') $('signal').classList.remove('zoomed');
});