|
29 | 29 | } |
30 | 30 | const iType = col('type'), iMat = col('material'); |
31 | 31 |
|
| 32 | + // Optional BIDS columns we preserve if present: `coordinate_system` and |
| 33 | + // `group` drive multi-frame EMG panelling; `hemisphere` helps iEEG. |
| 34 | + const iCoordSys = headers.indexOf('coordinate_system'); |
| 35 | + const iGroup = headers.indexOf('group'); |
| 36 | + const iHemi = headers.indexOf('hemisphere'); |
| 37 | + |
32 | 38 | const rows = []; |
33 | 39 | for (let i = 1; i < lines.length; i++) { |
34 | 40 | const c = lines[i].split('\t'); |
|
38 | 44 | const z = parseFloat(c[iZ]); |
39 | 45 | // BIDS uses "n/a" for missing; parseFloat → NaN → skip. |
40 | 46 | if (!name || !isFinite(x) || !isFinite(y) || !isFinite(z)) continue; |
41 | | - rows.push({ |
| 47 | + const row = { |
42 | 48 | name, x, y, z, |
43 | 49 | type: iType >= 0 ? (c[iType] || '').trim() : '', |
44 | 50 | material: iMat >= 0 ? (c[iMat] || '').trim() : '', |
45 | | - }); |
| 51 | + }; |
| 52 | + if (iCoordSys >= 0 && c[iCoordSys] && c[iCoordSys].trim() && c[iCoordSys].trim().toLowerCase() !== 'n/a') { |
| 53 | + row.coordinate_system = c[iCoordSys].trim(); |
| 54 | + } |
| 55 | + if (iGroup >= 0 && c[iGroup] && c[iGroup].trim() && c[iGroup].trim().toLowerCase() !== 'n/a') { |
| 56 | + row.group = c[iGroup].trim(); |
| 57 | + } |
| 58 | + if (iHemi >= 0 && c[iHemi] && c[iHemi].trim() && c[iHemi].trim().toLowerCase() !== 'n/a') { |
| 59 | + row.hemisphere = c[iHemi].trim(); |
| 60 | + } |
| 61 | + rows.push(row); |
46 | 62 | } |
47 | 63 | if (rows.length < 4) throw new Error('Need at least 4 electrodes with finite x,y,z'); |
48 | 64 | return rows; |
|
51 | 67 | // ---- coordsystem.json --------------------------------------- |
52 | 68 | api.parseCoordsystem = function (jsonOrText) { |
53 | 69 | const obj = typeof jsonOrText === 'string' ? JSON.parse(jsonOrText) : jsonOrText; |
54 | | - const prefix = ['EEG', 'iEEG', 'MEG'].find(p => obj[p + 'CoordinateSystem']) || 'EEG'; |
| 70 | + // BIDS prefixes coordinate keys by datatype: EEGCoordinateSystem, |
| 71 | + // iEEGCoordinateSystem, MEGCoordinateSystem, EMGCoordinateSystem (BEP-030), |
| 72 | + // NIRSCoordinateSystem. Pick whichever prefix has a match. |
| 73 | + const prefixes = ['EEG', 'iEEG', 'MEG', 'EMG', 'NIRS']; |
| 74 | + const prefix = prefixes.find( |
| 75 | + p => obj[p + 'CoordinateSystem'] || obj[p + 'CoordinateUnits'] |
| 76 | + ) || 'EEG'; |
55 | 77 | return { |
56 | 78 | space: obj[prefix + 'CoordinateSystem'] || 'Other', |
57 | 79 | units: (obj[prefix + 'CoordinateUnits'] || 'm').toLowerCase(), |
|
236 | 258 | return matches / electrodes.length >= 0.7 ? 'label' : 'position'; |
237 | 259 | } |
238 | 260 |
|
| 261 | + // Modalities the EEG-style sphere pipeline applies to. Other modalities |
| 262 | + // (iEEG in brain space, EMG on body landmarks, fNIRS when the coordsystem |
| 263 | + // isn't obviously a scalp frame) bypass sphere-fit + unit-inference and |
| 264 | + // go through a "flat" pipeline that just normalises the bounding box. |
| 265 | + const SPHERE_MODALITIES = new Set(['eeg', 'meg']); |
| 266 | + |
| 267 | + // ---- Flat pipeline (iEEG / EMG / fNIRS / anything non-spherical) ---- |
| 268 | + // Normalises raw (x, y, z) to a [-1, 1] cube around the centroid. Skips |
| 269 | + // axis rotation, unit inference, and sphere-fit. The viewer renders these |
| 270 | + // as a plain scatter — no head outline, no 10-10 rings, just coordinate |
| 271 | + // axes and a bounding box. |
| 272 | + // |
| 273 | + // For EMG datasets with multiple anatomical frames in one file (HySER's |
| 274 | + // ed/ep/fd/fp), we spread the groups across a 2×2 grid so they don't |
| 275 | + // stack at the same normalised coords. Detection: the raw parser |
| 276 | + // preserves the `coordinate_system` column when present. |
| 277 | + function buildFlatMontage({ raw, meta, label, modality }) { |
| 278 | + const electrodes = raw.slice(); |
| 279 | + |
| 280 | + // Group-based offsets for EMG multi-frame files. Each group gets its |
| 281 | + // own sub-panel in a grid. Groups are laid out 2-across. |
| 282 | + const groupKey = (e) => e.coordinate_system || e.group || ''; |
| 283 | + const groups = [...new Set(electrodes.map(groupKey).filter(k => k !== ''))]; |
| 284 | + const hasGroups = groups.length > 1; |
| 285 | + const perGroupPanel = {}; // groupName -> {ox, oy} offset in normalised space |
| 286 | + if (hasGroups) { |
| 287 | + const cols = Math.ceil(Math.sqrt(groups.length)); |
| 288 | + groups.forEach((g, i) => { |
| 289 | + const row = Math.floor(i / cols); |
| 290 | + const col = i % cols; |
| 291 | + // Each sub-panel fits in roughly [-0.45, 0.45]; offset centres |
| 292 | + // them on a (cols × rows) grid centered on (0, 0). |
| 293 | + const span = 1 / cols; |
| 294 | + const ox = (col - (cols - 1) / 2) * span * 2; |
| 295 | + const oy = ((cols - 1) / 2 - row) * span * 2; // row 0 on top |
| 296 | + perGroupPanel[g] = { ox, oy, span }; |
| 297 | + }); |
| 298 | + } |
| 299 | + |
| 300 | + // Normalise each group (or the whole cloud) to [-0.45, 0.45]. |
| 301 | + const normalise = (pts) => { |
| 302 | + const xs = pts.map(p => p.x), ys = pts.map(p => p.y), zs = pts.map(p => p.z); |
| 303 | + const xmin = Math.min(...xs), xmax = Math.max(...xs); |
| 304 | + const ymin = Math.min(...ys), ymax = Math.max(...ys); |
| 305 | + const zmin = Math.min(...zs), zmax = Math.max(...zs); |
| 306 | + const cx = (xmin + xmax) / 2, cy = (ymin + ymax) / 2, cz = (zmin + zmax) / 2; |
| 307 | + const span = Math.max(xmax - xmin, ymax - ymin, 1e-9); |
| 308 | + return { cx, cy, cz, span }; |
| 309 | + }; |
| 310 | + |
| 311 | + const out = []; |
| 312 | + if (hasGroups) { |
| 313 | + for (const g of groups) { |
| 314 | + const members = electrodes.filter(e => groupKey(e) === g); |
| 315 | + const { cx, cy, cz, span } = normalise(members); |
| 316 | + const { ox, oy, span: panelSpan } = perGroupPanel[g]; |
| 317 | + const scale = panelSpan * 0.9; // leave 10% margin per panel |
| 318 | + for (const e of members) { |
| 319 | + const nx = (e.x - cx) / span * scale + ox; |
| 320 | + const ny = (e.y - cy) / span * scale + oy; |
| 321 | + // In flat mode ux/uy are the final 2D coords; uz stays raw for |
| 322 | + // completeness but the renderer uses only ux/uy. |
| 323 | + out.push({ |
| 324 | + name: e.name, |
| 325 | + x: +(e.x).toFixed(5), y: +(e.y).toFixed(5), z: +(e.z).toFixed(5), |
| 326 | + ux: nx, uy: ny, uz: 0, |
| 327 | + region: 'other', |
| 328 | + type: e.type || modality.toUpperCase(), |
| 329 | + material: e.material || '', |
| 330 | + group: e.group, coordinate_system: e.coordinate_system, |
| 331 | + }); |
| 332 | + } |
| 333 | + } |
| 334 | + } else { |
| 335 | + const { cx, cy, cz, span } = normalise(electrodes); |
| 336 | + for (const e of electrodes) { |
| 337 | + out.push({ |
| 338 | + name: e.name, |
| 339 | + x: +(e.x).toFixed(5), y: +(e.y).toFixed(5), z: +(e.z).toFixed(5), |
| 340 | + ux: (e.x - cx) / span * 0.9, |
| 341 | + uy: (e.y - cy) / span * 0.9, |
| 342 | + uz: (e.z - cz) / span * 0.9, |
| 343 | + region: 'other', |
| 344 | + type: e.type || modality.toUpperCase(), |
| 345 | + material: e.material || '', |
| 346 | + }); |
| 347 | + } |
| 348 | + } |
| 349 | + |
| 350 | + return { |
| 351 | + label: label || `Loaded · ${out.length}ch`, |
| 352 | + count: out.length, |
| 353 | + electrodes: out, |
| 354 | + space: meta.space, |
| 355 | + units: meta.units, |
| 356 | + // Flat layouts have no sphere geometry. Consumers that read `.sphere` |
| 357 | + // must handle null explicitly (rail stats, caption, etc.). |
| 358 | + sphere: null, |
| 359 | + inferredUnits: meta.units, |
| 360 | + declaredUnits: meta.units, |
| 361 | + unitsMismatch: false, |
| 362 | + axisTransform: null, |
| 363 | + regionStrategy: 'none', |
| 364 | + layoutStyle: 'flat', |
| 365 | + modality, |
| 366 | + groups: hasGroups ? groups : null, |
| 367 | + }; |
| 368 | + } |
| 369 | + |
| 370 | + // Best-effort modality inference when the caller doesn't supply it. |
| 371 | + // Inspects the coordsystem.json keys — BIDS prefixes the system/units |
| 372 | + // keys with the datatype (EEGCoordinateSystem, iEEGCoordinateSystem, etc.). |
| 373 | + function inferModalityFromMeta(meta, coordsystemJson) { |
| 374 | + if (coordsystemJson) { |
| 375 | + const obj = typeof coordsystemJson === 'string' |
| 376 | + ? (() => { try { return JSON.parse(coordsystemJson); } catch { return {}; } })() |
| 377 | + : coordsystemJson; |
| 378 | + for (const prefix of ['iEEG', 'EEG', 'MEG', 'EMG', 'NIRS']) { |
| 379 | + if (obj[prefix + 'CoordinateSystem'] || obj[prefix + 'CoordinateUnits']) { |
| 380 | + return prefix.toLowerCase(); |
| 381 | + } |
| 382 | + } |
| 383 | + } |
| 384 | + return null; |
| 385 | + } |
| 386 | + |
239 | 387 | // ---- Main entry --------------------------------------------- |
240 | | - // Returns { label, count, electrodes, space, units, sphere } |
241 | | - // matching the shape of MONTAGES[key]. |
242 | | - api.buildMontageFromBIDS = function ({ tsvText, coordsystemJson, label }) { |
| 388 | + // Returns { label, count, electrodes, space, units, sphere, layoutStyle, |
| 389 | + // modality } matching the shape of MONTAGES[key]. The `modality` field |
| 390 | + // drives the viewer's rendering path ('sphere' vs 'flat'). |
| 391 | + api.buildMontageFromBIDS = function ({ tsvText, coordsystemJson, label, modality }) { |
243 | 392 | const parsed = api.parseElectrodesTSV(tsvText); |
244 | 393 | const meta = coordsystemJson |
245 | 394 | ? api.parseCoordsystem(coordsystemJson) |
246 | 395 | : { space: 'Other', units: null, landmarks: null }; |
247 | 396 |
|
248 | | - // Step 0: axis convention. Rotate into RAS+ if the declared space uses |
249 | | - // ALS (EEGLAB/CTF/4D/KIT). The transform is a pure permutation + sign |
250 | | - // flip, so it's safe to apply before sphere fitting. |
| 397 | + // Resolve modality: explicit > inferred from coordsystem.json keys > "eeg". |
| 398 | + const resolved = ( |
| 399 | + (modality || '').toLowerCase() || |
| 400 | + inferModalityFromMeta(meta, coordsystemJson) || |
| 401 | + 'eeg' |
| 402 | + ); |
| 403 | + |
| 404 | + // Flat pipeline for non-spherical modalities. No sphere-fit, no unit |
| 405 | + // inference, no axis rotation. The viewer renders a simple scatter. |
| 406 | + if (!SPHERE_MODALITIES.has(resolved)) { |
| 407 | + return buildFlatMontage({ raw: parsed, meta, label, modality: resolved }); |
| 408 | + } |
| 409 | + |
| 410 | + // Rotate into RAS+ if the declared space uses ALS (EEGLAB/CTF/4D/KIT). |
| 411 | + // Pure permutation + sign flip, safe to apply before sphere fitting. |
251 | 412 | const axisXform = axisTransformForSpace(meta.space); |
252 | 413 | const raw = axisXform ? parsed.map(axisXform.apply) : parsed; |
253 | 414 |
|
254 | | - // Step 1: fit a sphere in whatever units the TSV actually uses. |
255 | 415 | const rawSphere = api.fitSphere(raw); |
256 | 416 | if (!rawSphere) { |
257 | 417 | throw new Error( |
|
260 | 420 | ); |
261 | 421 | } |
262 | 422 |
|
263 | | - // Step 2: infer the scale from the fitted radius, not the metadata. |
264 | | - // The data is the ground truth; coordsystem.json frequently lies about |
265 | | - // units. If the raw radius is a plausible head radius in m/mm/cm we pick |
266 | | - // the matching scale; otherwise we bail with a clear error. |
| 423 | + // Infer scale from the fitted radius, not the metadata. coordsystem.json |
| 424 | + // frequently lies about units (see ds002578 mm-vs-m). |
267 | 425 | const inferred = inferMetersScaleFromRadius(rawSphere[3]); |
268 | 426 | if (!inferred) { |
269 | 427 | throw new Error( |
|
273 | 431 | ); |
274 | 432 | } |
275 | 433 |
|
276 | | - // Step 3: apply the inferred scale. Everything below is meters. |
277 | 434 | const s = inferred.scale; |
278 | 435 | const scaled = raw.map(e => ({ ...e, x: e.x * s, y: e.y * s, z: e.z * s })); |
279 | 436 | const [cx, cy, cz, R] = rawSphere.map(v => v * s); |
280 | 437 |
|
281 | | - // Flag a disagreement between declared and inferred units — useful for the |
282 | | - // UI and for diagnosing datasets with bad coordsystem.json files. |
283 | 438 | const declaredUnits = meta.units || null; |
284 | 439 | const unitsMismatch = declaredUnits && declaredUnits !== inferred.unit; |
285 | 440 |
|
|
316 | 471 | unitsMismatch, |
317 | 472 | axisTransform: axisXform ? axisXform.name : null, |
318 | 473 | regionStrategy, |
| 474 | + layoutStyle: 'sphere', |
| 475 | + modality: resolved, |
319 | 476 | }; |
320 | 477 | }; |
321 | 478 |
|
|
0 commit comments