Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions extensions/default/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
"test:unit:ci": "jest --ci --runInBand --collectCoverage --passWithNoTests"
},
"peerDependencies": {
"@cornerstonejs/metadata": "5.4.17",
"@ohif/core": "workspace:*",
"@ohif/i18n": "workspace:*",
"dcmjs": "0.52.0",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import type { InstanceGroup } from '@cornerstonejs/metadata';
import { ohifDefaultSplitRules } from '../displaySetSplitting/ohifDefaultSplitRules';
import { makeDisplaySetFromInstanceGroup } from '../displaySetSplitting/makeDisplaySetFromInstanceGroup';
import type { ImageSetFactoryContext } from '../displaySetSplitting/makeImageSetDisplaySet';

/**
* The `useMetadataDisplaySet` customization (default OFF).
*
* When enabled, DisplaySetService splits series instances into display sets
* with the `@cornerstonejs/metadata` split-rules engine instead of the stack
* SOP class handler. Instances not matched by any rule (video, whole-slide,
* ECG, SEG, SR, RT, PDF, ...) fall through to the registered SOP class
* handlers unchanged.
*
* Enable per mode:
* ```js
* customizationService.setCustomizations({
* useMetadataDisplaySet: { enabled: { $set: true } },
* });
* ```
* or globally via the named module entry
* `'@ohif/extension-default.customizationModule.metadataDisplaySet'`,
* or from the URL with `?customization=split/enableNewSplit`.
*
* Split rules may be overridden with immutability-helper specs. Rules may
* also be authored declaratively (e.g. in JSONC URL customizations) with
* `$function` expressions and object-form `series`/`customAttributes` maps —
* DisplaySetService normalizes those into engine shape when reading the
* customization.
*
* Note: image SOP class instances without `Rows` are unmatched by the default
* rules and become a separate legacy stack display set (the legacy handler
* merges them into the series' stackable display set instead).
*/
export default function getMetadataDisplaySetCustomization(context: ImageSetFactoryContext) {
return {
useMetadataDisplaySet: {
enabled: false,
splitRules: ohifDefaultSplitRules,
createDisplaySetFromGroup: (group: InstanceGroup, options: { splitNumber: number }) =>
makeDisplaySetFromInstanceGroup(group, options, context),
},
};
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
import type { InstanceGroup } from '@cornerstonejs/metadata';
import getDisplaySetMessages from '../getDisplaySetMessages';
import {
getDisplaySetInfo,
makeImageSetDisplaySet,
type ImageSetFactoryContext,
} from './makeImageSetDisplaySet';

/**
* Attributes the rule's `customAttributes` may never overwrite — they define
* the identity/content of the display set.
*/
const RESERVED_ATTRIBUTES = new Set([
'instances',
'images',
'uid',
'displaySetInstanceUID',
'splitKey',
]);

/**
* Converts a `@cornerstonejs/metadata` split-rule instance group into a full
* OHIF ImageSet display set. This is the default
* `createDisplaySetFromGroup` of the `useMetadataDisplaySet` customization.
*
* The display set is built by the same factory the legacy stack SOP class
* handler uses, so it carries the complete legacy attribute set; the split
* engine then contributes `splitKey` (reconciliation identity),
* `splitRuleId`, `viewportTypes` and the matched rule's custom attributes.
*/
export function makeDisplaySetFromInstanceGroup(
group: InstanceGroup,
{ splitNumber }: { splitNumber: number },
context: ImageSetFactoryContext
) {
const { instances, matchedRule, splitKey } = group;

const imageSet = makeImageSetDisplaySet([...instances], context);
const sopClassUids = [...new Set(instances.map(instance => instance.SOPClassUID))];
const viewportTypes = matchedRule.viewportTypes ? [...matchedRule.viewportTypes] : undefined;

imageSet.setAttributes({
sopClassUids,
splitKey,
splitRuleId: matchedRule.id,
viewportTypes,
});

const customAttributes = matchedRule.customAttributes?.(
{
instance: instances[0],
isMultiFrame: Number(instances[0]?.NumberOfFrames) > 1,
sopClassUids: sopClassUids as string[],
viewportTypes: matchedRule.viewportTypes,
},
{ instances: [...instances], splitNumber }
);
if (customAttributes) {
imageSet.setAttributes(
Object.fromEntries(
Object.entries(customAttributes).filter(([key]) => !RESERVED_ATTRIBUTES.has(key))
)
);
}

// Incremental-merge hook used by DisplaySetService when new instances of an
// existing split group arrive. Intentionally NOT named `addInstances` (the
// SOP-class-handler merge hook) so the legacy handler loop can never feed
// unmatched instances into split-rule display sets - they share the stack
// SOPClassHandlerId.
imageSet.setAttribute('updateInstances', newInstances => {
const knownSOPInstanceUIDs = new Set(
imageSet.instances.map(instance => (instance as { SOPInstanceUID?: string }).SOPInstanceUID)
);
const instancesToAdd = newInstances.filter(
instance => !knownSOPInstanceUIDs.has(instance.SOPInstanceUID)
);
if (!instancesToAdd.length) {
return undefined;
}

// `images` is a non-writable property, but the array contents are mutable.
imageSet.images.push(...instancesToAdd);
imageSet.sort(context.servicesManager.services.customizationService);

// Recompute reconstructability and validation messages exactly like the
// initial build.
const dataSource = context.extensionManager.getActiveDataSource()[0];
const imageIds = dataSource.getImageIdsForDisplaySet(imageSet);
const {
isDynamicVolume,
value: isReconstructable,
averageSpacingBetweenFrames,
dynamicVolumeInfo,
} = getDisplaySetInfo(imageSet.images, imageIds, context);
const messages = getDisplaySetMessages(imageSet.images, isReconstructable, isDynamicVolume);

imageSet.setAttributes({
numImageFrames: imageSet.images.length,
countIcon: isReconstructable ? 'icon-mpr' : undefined,
isReconstructable,
messages,
averageSpacingBetweenFrames: averageSpacingBetweenFrames || null,
isDynamicVolume,
dynamicVolumeInfo,
});

return imageSet;
});

return imageSet;
}
175 changes: 175 additions & 0 deletions extensions/default/src/displaySetSplitting/makeImageSetDisplaySet.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@
import { utils, classes } from '@ohif/core';
import i18n from '@ohif/i18n';
import { metaData } from '@cornerstonejs/core';
import { id } from '../id';
import getDisplaySetMessages from '../getDisplaySetMessages';

const { sortStudyInstances, isDisplaySetReconstructable } = utils;
const { ImageSet } = classes;

const DEFAULT_VOLUME_LOADER_SCHEME = 'cornerstoneStreamingImageVolume';
const DYNAMIC_VOLUME_LOADER_SCHEME = 'cornerstoneStreamingDynamicImageVolume';

export const STACK_SOP_CLASS_HANDLER_ID = `${id}.sopClassHandlerModule.stack`;

/**
* The application context required to build an ImageSet display set. This is
* the same shape as the `appContext` handed to `getSopClassHandlerModule`.
*/
export type ImageSetFactoryContext = {
servicesManager: AppTypes.ServicesManager;
extensionManager: AppTypes.ExtensionManager;
appConfig?: AppTypes.Config;
};

const isMultiFrame = instance => {
return instance.NumberOfFrames > 1;
};

function getDynamicVolumeInfo(imageIds, context: ImageSetFactoryContext) {
const { extensionManager } = context;

if (!extensionManager) {
throw new Error('extensionManager is not available');
}

const volumeLoaderUtility = extensionManager.getModuleEntry(
'@ohif/extension-cornerstone.utilityModule.volumeLoader'
);

if (!volumeLoaderUtility?.exports) {
throw new Error(
'The @ohif/extension-cornerstone volumeLoader utility module is not available'
);
}

const { getDynamicVolumeInfo: csGetDynamicVolumeInfo } = volumeLoaderUtility.exports;

return csGetDynamicVolumeInfo(imageIds);
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.

/**
* Computes reconstructability / dynamic-volume information for a set of
* instances. Exported so incremental updates (`updateInstances`) can re-run
* the exact computation used at creation time.
*/
export function getDisplaySetInfo(instances, imageIds, context: ImageSetFactoryContext) {
const dynamicVolumeInfo = getDynamicVolumeInfo(imageIds, context);
const { isDynamicVolume, timePoints } = dynamicVolumeInfo;
let displaySetInfo;

const { appConfig } = context;

if (isDynamicVolume) {
const timePoint = timePoints[0];
const instancesMap = new Map();

let firstTimePointInstances;

if (instances[0].NumberOfFrames > 1 && timePoints.length > 1) {
// Handle multiframe dynamic volumes. Local file frame imageIds do not
// always resolve to a frame-level instance object, so keep resolved
// entries and fall back to the source multiframe instance when needed.
firstTimePointInstances = timePoints[0]
.map(imageId => metaData.get('instance', imageId))
.filter(Boolean);

if (!firstTimePointInstances.length) {
firstTimePointInstances = [instances[0]];
}
} else {
// O(n) to convert it into a map and O(1) to find each instance
instances.forEach(instance => instancesMap.set(instance.imageId, instance));
firstTimePointInstances = timePoint.map(imageId => instancesMap.get(imageId)).filter(Boolean);
}
displaySetInfo = isDisplaySetReconstructable(firstTimePointInstances, appConfig);
} else {
displaySetInfo = isDisplaySetReconstructable(instances, appConfig);
}

return {
isDynamicVolume,
...displaySetInfo,
dynamicVolumeInfo,
};
}

/**
* Builds a stack/volume ImageSet display set carrying the full OHIF attribute
* set (`label`, `supportsWindowLevel`, `FrameOfReferenceUID`,
* `SOPClassHandlerId`, `isReconstructable`, `messages`, ...).
*
* This is the single shared factory used by both the legacy stack SOP class
* handler and the `useMetadataDisplaySet` split-rules path, so both paths
* produce identical display sets.
*/
export function makeImageSetDisplaySet(instances, context: ImageSetFactoryContext) {
// Need to sort the instances in order to get a consistent instance/thumbnail
sortStudyInstances(instances);
const instance = instances[0];
const imageSet = new ImageSet(instances);
const { extensionManager } = context;
const dataSource = extensionManager.getActiveDataSource()[0];
const imageIds = dataSource.getImageIdsForDisplaySet(imageSet);
const {
isDynamicVolume,
value: isReconstructable,
averageSpacingBetweenFrames,
dynamicVolumeInfo,
} = getDisplaySetInfo(instances, imageIds, context);

const volumeLoaderSchema = isDynamicVolume
? DYNAMIC_VOLUME_LOADER_SCHEME
: DEFAULT_VOLUME_LOADER_SCHEME;

// set appropriate attributes to image set...
const messages = getDisplaySetMessages(instances, isReconstructable, isDynamicVolume);

imageSet.setAttributes({
volumeLoaderSchema,
displaySetInstanceUID: imageSet.uid, // create a local alias for the imageSet UID
SeriesDate: instance.SeriesDate,
SeriesTime: instance.SeriesTime,
SeriesInstanceUID: instance.SeriesInstanceUID,
StudyInstanceUID: instance.StudyInstanceUID,
SeriesNumber: instance.SeriesNumber || 0,
FrameRate: instance.FrameTime,
SOPClassUID: instance.SOPClassUID,
SeriesDescription: instance.SeriesDescription || '',
Modality: instance.Modality,
isMultiFrame: isMultiFrame(instance),
countIcon: isReconstructable ? 'icon-mpr' : undefined,
numImageFrames: instances.length,
SOPClassHandlerId: STACK_SOP_CLASS_HANDLER_ID,
isReconstructable,
messages,
averageSpacingBetweenFrames: averageSpacingBetweenFrames || null,
isDynamicVolume,
dynamicVolumeInfo,
supportsWindowLevel: true,
label:
instance.SeriesDescription ||
`${i18n.t('Series')} ${instance.SeriesNumber} - ${i18n.t(instance.Modality)}`,
FrameOfReferenceUID: instance.FrameOfReferenceUID,
});

let imageId = imageIds[Math.floor(imageIds.length / 2)];
const thumbnailInstance = instances[Math.floor(instances.length / 2)];
if (isDynamicVolume) {
const timePoints = dynamicVolumeInfo.timePoints;
const middleIndex = Math.floor(timePoints.length / 2);
const middleTimePointImageIds = timePoints[middleIndex];
imageId = middleTimePointImageIds[Math.floor(middleTimePointImageIds.length / 2)];
}

imageSet.setAttributes({
getThumbnailSrc: dataSource.retrieve.getGetThumbnailSrc?.(thumbnailInstance, imageId),
});

const { servicesManager } = context;
const { customizationService } = servicesManager.services;

imageSet.sort(customizationService);

return imageSet;
}
Loading
Loading