diff --git a/src/config.ts b/src/config.ts index 0730fcfc3..27072f915 100644 --- a/src/config.ts +++ b/src/config.ts @@ -190,7 +190,7 @@ export const STROKE_WIDTH_ANNOTATION_TOOL_DEFAULT = 1; export const DEFAULT_PRESET_BY_MODALITY: Record = { CT: 'CT-AAA', - MR: 'CT-Coronary-Arteries-2', + MR: 'MR-Default', US: 'US-Fetal', }; diff --git a/src/store/view-configs/volume-coloring.ts b/src/store/view-configs/volume-coloring.ts index 4c2e0e4df..a9d5fdaf9 100644 --- a/src/store/view-configs/volume-coloring.ts +++ b/src/store/view-configs/volume-coloring.ts @@ -16,7 +16,7 @@ import { } from '@/src/utils/doubleKeyRecord'; import { DeepPartial, Maybe } from '@/src/types'; import { identity } from '@/src/utils'; -import { isDicomImage } from '@/src/utils/dataSelection'; +import { getDeclaredModality } from '@/src/utils/declaredModality'; import { useImageCacheStore } from '@/src/store/image-cache'; import { createViewConfigSerializer } from './common'; import { ViewConfig } from '../../io/state-file/schema'; @@ -30,15 +30,11 @@ export const DEFAULT_EDGE_GRADIENT = 0.2; export const DEFAULT_SAMPLING_DISTANCE = 0.2; function getPresetFromImageModality(imageID: string) { - const dicomStore = useDICOMStore(); - if (isDicomImage(imageID)) { - const volKey = imageID; - const { Modality } = dicomStore.volumeInfo[volKey]; - if (Modality in DEFAULT_PRESET_BY_MODALITY) { - return DEFAULT_PRESET_BY_MODALITY[Modality]; - } - } - return DEFAULT_PRESET; + const modality = getDeclaredModality( + useDICOMStore().volumeInfo[imageID]?.Modality, + useImageCacheStore().imageById[imageID]?.headerMetadata + ); + return DEFAULT_PRESET_BY_MODALITY[modality] ?? DEFAULT_PRESET; } /** diff --git a/src/utils/__tests__/declaredModality.spec.ts b/src/utils/__tests__/declaredModality.spec.ts new file mode 100644 index 000000000..7289038b5 --- /dev/null +++ b/src/utils/__tests__/declaredModality.spec.ts @@ -0,0 +1,58 @@ +import { describe, expect, it } from 'vitest'; +import { getDeclaredModality } from '@/src/utils/declaredModality'; + +describe('getDeclaredModality', () => { + it('prefers the DICOM modality over header fields', () => { + expect(getDeclaredModality(' mr ', [['modality', 'CT']])).toBe('MR'); + }); + + it('reads the modality tag before a plain modality field', () => { + expect( + getDeclaredModality(undefined, [ + ['Modality', 'us'], + ['0008|0060', 'MR'], + ]) + ).toBe('MR'); + expect(getDeclaredModality('', [[' Modality ', ' us ']])).toBe('US'); + }); + + it('reads MetaImage modality names', () => { + expect(getDeclaredModality(undefined, [['Modality', 'MET_MOD_MR']])).toBe( + 'MR' + ); + }); + + it('treats Hounsfield scalar units as CT', () => { + expect(getDeclaredModality(undefined, [['0028|1054', 'HU']])).toBe('CT'); + expect(getDeclaredModality(undefined, [['RescaleType', 'hu']])).toBe('CT'); + expect( + getDeclaredModality(undefined, [['IntensityUnits', 'Hounsfield Units']]) + ).toBe('CT'); + }); + + it('reads Hounsfield units from a MetaImage without a modality', () => { + expect( + getDeclaredModality(undefined, [ + ['IntensityUnits', 'HU'], + ['Modality', 'MET_MOD_UNKNOWN'], + ]) + ).toBe('CT'); + expect( + getDeclaredModality(undefined, [['Modality', 'MET_MOD_UNKNOWN']]) + ).toBe(''); + }); + + it('keeps an explicit modality even when units are Hounsfield', () => { + expect( + getDeclaredModality(undefined, [ + ['modality', 'OT'], + ['IntensityUnits', 'HU'], + ]) + ).toBe('OT'); + }); + + it('declares nothing for other units or no metadata', () => { + expect(getDeclaredModality(undefined, [['IntensityUnits', 'mm']])).toBe(''); + expect(getDeclaredModality(undefined)).toBe(''); + }); +}); diff --git a/src/utils/declaredModality.ts b/src/utils/declaredModality.ts new file mode 100644 index 000000000..f9b195f12 --- /dev/null +++ b/src/utils/declaredModality.ts @@ -0,0 +1,31 @@ +const HOUNSFIELD_UNITS = ['HU', 'HOUNSFIELD UNIT', 'HOUNSFIELD UNITS']; + +const firstField = (fields: Map, keys: string[]) => + keys.map((key) => fields.get(key)).find(Boolean); + +export function getDeclaredModality( + dicomModality: string | undefined, + headerMetadata: Iterable = [] +) { + const fields = new Map( + Array.from(headerMetadata, ([key, value]) => [ + key.trim().toLowerCase(), + value.trim().toUpperCase(), + ]) + ); + // MetaImage headers spell modalities as MET_MOD_CT, MET_MOD_MR, ... + const modality = ( + dicomModality?.trim().toUpperCase() || + firstField(fields, ['0008|0060', 'modality']) + )?.replace(/^MET_MOD_/, ''); + // ITK reports MET_MOD_UNKNOWN for every MetaImage without a modality. + if (modality && modality !== 'UNKNOWN') return modality; + + // Only scalar units identify CT; spatial units and value ranges do not. + const units = firstField(fields, [ + '0028|1054', + 'rescaletype', + 'intensityunits', + ]); + return units && HOUNSFIELD_UNITS.includes(units) ? 'CT' : ''; +} diff --git a/tests/specs/volume-modality-presets.e2e.ts b/tests/specs/volume-modality-presets.e2e.ts new file mode 100644 index 000000000..6f10c0444 --- /dev/null +++ b/tests/specs/volume-modality-presets.e2e.ts @@ -0,0 +1,127 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { volViewPage } from '../pageobjects/volview.page'; +import { buildSyntheticDicom, newUid } from './syntheticDicom'; +import { + makeTempDir, + waitForModuleTransitions, + writeManifestToFile, +} from './utils'; + +const LAYOUT = { + layouts: { + default: { + direction: 'row', + items: [{ type: '3D', viewDirection: 'Superior', viewUp: 'Anterior' }], + }, + }, +}; + +const VOXELS = Buffer.from( + Array.from({ length: 512 }, (_, index) => index % 256) +); + +const nrrd = (fields: string[]) => + [ + 'NRRD0005', + 'type: uchar', + 'dimension: 3', + 'sizes: 8 8 8', + 'space: left-posterior-superior', + 'space directions: (1,0,0) (0,1,0) (0,0,1)', + 'space origin: (0,0,0)', + 'encoding: raw', + ...fields, + '', + '', + ].join('\n'); + +const mha = (fields: string[]) => + [ + 'ObjectType = Image', + 'NDims = 3', + 'DimSize = 8 8 8', + ...fields, + 'ElementType = MET_UCHAR', + 'ElementDataFile = LOCAL', + '', + ].join('\n'); + +function writeDicomSeries(directory: string, modality: string) { + const studyUid = newUid(); + const seriesUid = newUid(); + return Array.from({ length: 4 }, (_, index) => { + const name = `slice-${index}.dcm`; + fs.writeFileSync( + path.join(directory, name), + buildSyntheticDicom({ + studyUid, + seriesUid, + sopUid: newUid(), + modality, + instanceNumber: index + 1, + rows: 8, + cols: 8, + imageOrientationPatient: [1, 0, 0, 0, 1, 0], + imagePositionPatient: [0, 0, index], + pixelValue: 100 * (index + 1), + }) + ); + return { url: `tmp/${path.basename(directory)}/${name}`, name }; + }); +} + +async function openWith3DLayout(dataUrl: string, name: string) { + const config = `${name}-layout.json`; + await writeManifestToFile(LAYOUT, config); + await volViewPage.open(`?urls=[tmp/${config},${dataUrl}]`); + await volViewPage.waitForViewCounts(0, true); +} + +async function expectSelectedPreset(label: string) { + await volViewPage.renderingModuleTab.waitForClickable(); + await volViewPage.renderingModuleTab.click(); + await waitForModuleTransitions(); + const title = $('.v-expansion-panel-title*=Color Presets'); + await title.scrollIntoView({ block: 'center', behavior: 'instant' }); + if ((await title.getAttribute('aria-expanded')) !== 'true') { + await title.click(); + } + await expect($('.thumbnail-container.bg-blue')).toHaveText(label); +} + +describe('volume preset from declared modality', () => { + for (const { file, header, label } of [ + { file: 'mr.nrrd', header: nrrd(['modality:=MR']), label: 'MR Default' }, + { file: 'us.nrrd', header: nrrd(['0008|0060:=US']), label: 'US Fetal' }, + { file: 'undeclared.nrrd', header: nrrd([]), label: 'CT AAA' }, + { + file: 'mr.mha', + header: mha(['Modality = MET_MOD_MR']), + label: 'MR Default', + }, + ]) { + it(`selects ${label} for ${file}`, async () => { + const name = `modality-preset-${file.replace('.', '-')}`; + const directory = makeTempDir(name); + fs.writeFileSync( + path.join(directory, file), + Buffer.concat([Buffer.from(header), VOXELS]) + ); + await openWith3DLayout(`tmp/${name}/${file}`, name); + await expectSelectedPreset(label); + }); + } + + it('selects MR Default for an MR DICOM series', async () => { + const name = 'dicom-mr-preset'; + const directory = makeTempDir(name); + const manifest = `${name}.json`; + await writeManifestToFile( + { resources: writeDicomSeries(directory, 'MR') }, + manifest + ); + await openWith3DLayout(`tmp/${manifest}`, name); + await expectSelectedPreset('MR Default'); + }); +});