chore: Tag everything currently unused as legacy.

This commit is contained in:
James A. Petts authored and Erik Ziegler committed 2021-02-11 17:29:07 +01:00
1 parent 8392c1f97e
commit 414ebc6850
161 files changed
+128 -14712

No files matched your search

@@ -1,76 +0,0 @@
import { studyMetadataManager } from '../utils';
import OHIFError from './OHIFError';
import { StudyMetadata } from './metadata/StudyMetadata';
import { StudyMetadataSource } from './StudyMetadataSource.js';
import { retrieveStudyMetadata } from '../studies/retrieveStudyMetadata.js';
export class OHIFStudyMetadataSource extends StudyMetadataSource {
/**
* Get study metadata for a study with given study InstanceUID
* @param server
* @param {String} studyInstanceUID Study InstanceUID
* @return {Promise} A Promise object
*/
getByInstanceUID(server, studyInstanceUID) {
return retrieveStudyMetadata(server, studyInstanceUID);
}
/**
* Load study info (OHIF.viewer.Studies) and study metadata (OHIF.viewer.StudyMetadataList) for a given study.
* @param {StudyMetadata} study StudyMetadata object.
*/
loadStudy(study) {
if (!(study instanceof StudyMetadata)) {
throw new OHIFError(
'OHIFStudyMetadataSource::loadStudy study is not an instance of StudyMetadata'
);
}
return new Promise((resolve, reject) => {
const studyInstanceUID = study.getStudyInstanceUID();
if (study instanceof StudyMetadata) {
const alreadyLoaded = OHIF.viewer.Studies.findBy({
StudyInstanceUID: studyInstanceUID,
});
if (!alreadyLoaded) {
OHIFStudyMetadataSource._updateStudyCollections(study);
}
resolve(study);
return;
}
this.getByInstanceUID(studyInstanceUID)
.then(studyInfo => {
// Create study metadata object
const studyMetadata = new StudyMetadata(
studyInfo,
studyInfo.StudyInstanceUID
);
// Get Study display sets
const displaySets = studyMetadata.createDisplaySets();
// Set studyMetadata display sets
studyMetadata.setDisplaySets(displaySets);
OHIFStudyMetadataSource._updateStudyCollections(studyMetadata);
resolve(studyMetadata);
})
.catch(reject);
});
}
// Static methods
static _updateStudyCollections(studyMetadata) {
const studyInfo = studyMetadata.getData();
// Set some studyInfo properties
studyInfo.selected = true;
studyInfo.displaySets = studyMetadata.getDisplaySets();
studyMetadataManager.add(studyMetadata);
}
}
@@ -1,471 +0,0 @@
import cornerstone from 'cornerstone-core';
import cornerstoneWADOImageLoader from 'cornerstone-wado-image-loader';
import {
clearStudyLoadingProgress,
setStudyLoadingProgress,
} from '../redux/actions';
import StackManager from '../utils/StackManager';
class BaseLoadingListener {
constructor(stack, options = {}) {
this.id = BaseLoadingListener.getNewId();
this.stack = stack;
this.startListening();
this.statsItemsLimit = options.statsItemsLimit || 2;
this.stats = {
items: [],
total: 0,
elapsedTime: 0,
speed: 0,
};
this._setProgressData = options._setProgressData;
this._clearProgressById = options._clearProgressById;
// Register the start point to make it possible to calculate
// bytes/s or frames/s when the first byte or frame is received
this._addStatsData(0);
// Update the progress before starting the download
// to make it possible to update the UI
this._updateProgress();
}
_addStatsData(value) {
const date = new Date();
const stats = this.stats;
const items = stats.items;
const newItem = {
value,
date,
};
items.push(newItem);
stats.total += newItem.value;
// Remove items until it gets below the limit
while (items.length > this.statsItemsLimit) {
const item = items.shift();
stats.total -= item.value;
}
// Update the elapsedTime (seconds) based on first and last
// elements and recalculate the speed (bytes/s or frames/s)
if (items.length > 1) {
const oldestItem = items[0];
stats.elapsedTime =
(newItem.date.getTime() - oldestItem.date.getTime()) / 1000;
stats.speed = (stats.total - oldestItem.value) / stats.elapsedTime;
}
}
_getProgressId() {
const displaySetInstanceUID = this.stack.displaySetInstanceUID;
return 'StackProgress:' + displaySetInstanceUID;
}
_clearProgress() {
const progressId = this._getProgressId();
this._clearProgressById(progressId);
}
startListening() {
throw new Error('`startListening` must be implemented by child classes');
}
stopListening() {
throw new Error('`stopListening` must be implemented by child classes');
}
destroy() {
this.stopListening();
this._clearProgress();
}
static getNewId() {
const timeSlice = new Date()
.getTime()
.toString()
.slice(-8);
const randomNumber = parseInt(Math.random() * 1000000000);
return timeSlice.toString() + randomNumber.toString();
}
}
class DICOMFileLoadingListener extends BaseLoadingListener {
constructor(stack, options) {
super(stack, options);
this._dataSetUrl = this._getDataSetUrl(stack);
this._lastLoaded = 0;
// Check how many instances has already been download (cached)
this._checkCachedData();
}
_checkCachedData() {
const dataSet = cornerstoneWADOImageLoader.wadouri.dataSetCacheManager.get(
this._dataSetUrl
);
if (dataSet) {
const dataSetLength = dataSet.byteArray.length;
this._updateProgress({
percentComplete: 100,
loaded: dataSetLength,
total: dataSetLength,
});
}
}
_getImageLoadProgressEventName() {
// TODO: Add this event as a constant in Cornerstone
return 'cornerstoneimageloadprogress.' + this.id;
}
startListening() {
const imageLoadProgressEventName = this._getImageLoadProgressEventName();
this.imageLoadProgressEventHandler = this._imageLoadProgressEventHandle.bind(
this
);
this.stopListening();
cornerstone.events.addEventListener(
imageLoadProgressEventName,
this.imageLoadProgressEventHandle
);
}
stopListening() {
const imageLoadProgressEventName = this._getImageLoadProgressEventName();
cornerstone.events.removeEventListener(
imageLoadProgressEventName,
this.imageLoadProgressEventHandle
);
}
_imageLoadProgressEventHandler = e => {
const eventData = e.detail;
const dataSetUrl = this._convertImageIdToDataSetUrl(eventData.imageId);
const bytesDiff = eventData.loaded - this._lastLoaded;
if (!this._dataSetUrl === dataSetUrl) {
return;
}
// Add the bytes downloaded to the stats
this._addStatsData(bytesDiff);
// Update the download progress
this._updateProgress(eventData);
// Cache the last eventData.loaded value
this._lastLoaded = eventData.loaded;
};
_updateProgress(eventData) {
const progressId = this._getProgressId();
eventData = eventData || {};
const progressData = {
multiFrame: false,
percentComplete: eventData.percentComplete,
bytesLoaded: eventData.loaded,
bytesTotal: eventData.total,
bytesPerSecond: this.stats.speed,
};
this._setProgressData(progressId, progressData);
}
_convertImageIdToDataSetUrl(imageId) {
// Remove the prefix ("dicomweb:" or "wadouri:"")
imageId = imageId.replace(/^(dicomweb:|wadouri:)/i, '');
// Remove "frame=999&" from the imageId
imageId = imageId.replace(/frame=\d+&?/i, '');
// Remove the last "&" like in "http://...?foo=1&bar=2&"
imageId = imageId.replace(/&$/, '');
return imageId;
}
_getDataSetUrl(stack) {
const imageId = stack.imageIds[0];
return this._convertImageIdToDataSetUrl(imageId);
}
}
class StackLoadingListener extends BaseLoadingListener {
constructor(stack, options = {}) {
options.statsItemsLimit = 20;
super(stack, options);
this.imageDataMap = this._convertImageIdsArrayToMap(stack.imageIds);
this.framesStatus = this._createArray(stack.imageIds.length, false);
this.loadedCount = 0;
// Check how many instances has already been download (cached)
this._checkCachedData();
}
_convertImageIdsArrayToMap(imageIds) {
const imageIdsMap = new Map();
for (let i = 0; i < imageIds.length; i++) {
imageIdsMap.set(imageIds[i], {
index: i,
loaded: false,
});
}
return imageIdsMap;
}
_createArray(length, defaultValue) {
// `new Array(length)` is an anti-pattern in javascript because its
// funny API. Otherwise I would go for `new Array(length).fill(false)`
const array = [];
for (let i = 0; i < length; i++) {
array[i] = defaultValue;
}
return array;
}
_checkCachedData() {
// const imageIds = this.stack.imageIds;
// TODO: No way to check status of Promise.
/*for(let i = 0; i < imageIds.length; i++) {
const imageId = imageIds[i];
const imagePromise = cornerstone.imageCache.getImageLoadObject(imageId).promise;
if (imagePromise && (imagePromise.state() === 'resolved')) {
this._updateFrameStatus(imageId, true);
}
}*/
}
_getImageLoadedEventName() {
return `${cornerstone.EVENTS.IMAGE_LOADED}.${this.id}`;
}
_getImageCachePromiseRemoveEventName() {
return `${cornerstone.EVENTS.IMAGE_CACHE_PROMISE_REMOVED}.${this.id}`;
}
_imageLoadedEventHandler(e) {
this._updateFrameStatus(e.detail.image.imageId, true);
}
_imageCachePromiseRemovedEventHandler(e) {
this._updateFrameStatus(e.detail.imageId, false);
}
startListening() {
const imageLoadedEventName = this._getImageLoadedEventName();
const imageCachePromiseRemovedEventName = this._getImageCachePromiseRemoveEventName();
this.imageLoadedEventHandler = this._imageLoadedEventHandler.bind(this);
this.imageCachePromiseRemovedEventHandler = this._imageCachePromiseRemovedEventHandler.bind(
this
);
this.stopListening();
cornerstone.events.addEventListener(
imageLoadedEventName,
this.imageLoadedEventHandler
);
cornerstone.events.addEventListener(
imageCachePromiseRemovedEventName,
this.imageCachePromiseRemovedEventHandler
);
}
stopListening() {
const imageLoadedEventName = this._getImageLoadedEventName();
const imageCachePromiseRemovedEventName = this._getImageCachePromiseRemoveEventName();
cornerstone.events.removeEventListener(
imageLoadedEventName,
this.imageLoadedEventHandler
);
cornerstone.events.removeEventListener(
imageCachePromiseRemovedEventName,
this.imageCachePromiseRemovedEventHandler
);
}
_updateFrameStatus(imageId, loaded) {
const imageData = this.imageDataMap.get(imageId);
if (!imageData || imageData.loaded === loaded) {
return;
}
// Add one more frame to the stats
if (loaded) {
this._addStatsData(1);
}
imageData.loaded = loaded;
this.framesStatus[imageData.index] = loaded;
this.loadedCount += loaded ? 1 : -1;
this._updateProgress();
}
_setProgressData(progressId, progressData) {
// TODO: This method (and _clearProgressById) need to access
// the Redux store and should therefore be provided from the
// application. I've added a workaround to pass this in through
// the 'options' variable on instantiation, but this is really ugly.
// We could consider making the StudyLoadingListener a higher-order
// component which would set this stuff itself.
throw new Error(
"The _setProgressData function must be provided in StudyLoadingListener's options"
);
}
_clearProgressById(progressId) {
throw new Error(
"The _clearProgressById function must be provided in StudyLoadingListener's options"
);
}
_updateProgress() {
const totalFramesCount = this.stack.imageIds.length;
const loadedFramesCount = this.loadedCount;
const loadingFramesCount = totalFramesCount - loadedFramesCount;
const percentComplete = Math.round(
(loadedFramesCount / totalFramesCount) * 100
);
const progressId = this._getProgressId();
const progressData = {
multiFrame: true,
totalFramesCount,
loadedFramesCount,
loadingFramesCount,
percentComplete,
framesPerSecond: this.stats.speed,
framesStatus: this.framesStatus,
};
this._setProgressData(progressId, progressData);
}
_logProgress() {
const totalFramesCount = this.stack.imageIds.length;
const displaySetInstanceUID = this.stack.displaySetInstanceUID;
let progressBar = '[';
for (let i = 0; i < totalFramesCount; i++) {
const ch = this.framesStatus[i] ? '|' : '.';
progressBar += `${ch}`;
}
progressBar += ']';
log.info(`${displaySetInstanceUID}: ${progressBar}`);
}
}
class StudyLoadingListener {
constructor(options) {
this.listeners = {};
this.options = options;
}
addStack(stack, stackMetaData) {
// TODO: Make this work for plugins
if (!stack) {
//console.log('Skipping adding stack to StudyLoadingListener');
return;
}
const displaySetInstanceUID = stack.displaySetInstanceUID;
if (!this.listeners[displaySetInstanceUID]) {
const listener = this._createListener(stack, stackMetaData);
if (listener) {
this.listeners[displaySetInstanceUID] = listener;
}
}
}
addStudy(study) {
study.displaySets.forEach(displaySet => {
const stack = StackManager.findOrCreateStack(study, displaySet);
// TODO: Make this work for plugins
if (!stack) {
console.warn('Skipping adding displaySet to StudyLoadingListener');
console.warn(displaySet);
return;
}
this.addStack(stack, {
isMultiFrame: displaySet.isMultiFrame,
});
});
}
addStudies(studies) {
if (!studies || !studies.length) {
return;
}
studies.forEach(study => this.addStudy(study));
}
clear() {
const displaySetInstanceUIDs = Object.keys(this.listeners);
const length = displaySetInstanceUIDs.length;
for (let i = 0; i < length; i++) {
const displaySetInstanceUID = displaySetInstanceUIDs[i];
const displaySet = this.listeners[displaySetInstanceUID];
displaySet.destroy();
}
this.listeners = {};
}
_createListener(stack, stackMetaData) {
const schema = this._getSchema(stack);
// A StackLoadingListener can be created if it's wadors or not a multiframe
// wadouri instance (single file) that means "N" files will have to be
// downloaded where "N" is the number of frames. DICOMFileLoadingListener
// is created only if it's a single DICOM file and there's no way to know
// how many frames has already been loaded (bytes/s instead of frames/s).
if (schema === 'wadors' || !stackMetaData.isMultiFrame) {
return new StackLoadingListener(stack, this.options);
} else {
return new DICOMFileLoadingListener(stack, this.options);
}
}
_getSchema(stack) {
const imageId = stack.imageIds[0];
const colonIndex = imageId.indexOf(':');
return imageId.substring(0, colonIndex);
}
// Singleton
static getInstance(options) {
if (!StudyLoadingListener._instance) {
StudyLoadingListener._instance = new StudyLoadingListener(options);
}
return StudyLoadingListener._instance;
}
}
export { StudyLoadingListener, StackLoadingListener, DICOMFileLoadingListener };
@@ -1,32 +0,0 @@
import OHIFError from './OHIFError';
/**
* Abstract class to fetch study metadata.
*/
export class StudyMetadataSource {
/**
* Get study metadata for a study with given study InstanceUID.
* @param {String} studyInstanceUID Study InstanceUID.
*/
getByInstanceUID(studyInstanceUID) {
/**
* Please override this method on a specialized class.
*/
throw new OHIFError(
'StudyMetadataSource::getByInstanceUID is not overriden. Please, override it in a specialized class. See OHIFStudyMetadataSource for example'
);
}
/**
* Load study info and study metadata for a given study into the viewer.
* @param {StudyMetadata} study StudyMetadata object.
*/
loadStudy(study) {
/**
* Please override this method on a specialized class.
*/
throw new OHIFError(
'StudyMetadataSource::loadStudy is not overriden. Please, override it in a specialized class. See OHIFStudyMetadataSource for example'
);
}
}
@@ -1,261 +0,0 @@
import log from '../log.js';
import OHIFError from './OHIFError';
import cornerstone from 'cornerstone-core';
import cornerstoneTools from 'cornerstone-tools';
import getImageId from '../utils/getImageId.js';
export class StudyPrefetcher {
constructor(studies) {
this.studies = studies || [];
this.prefetchDisplaySetsTimeout = 300;
this.lastActiveViewportElement = null;
cornerstone.events.addEventListener(
'cornerstoneimagecachefull.StudyPrefetcher',
this.cacheFullHandler
);
}
destroy() {
this.stopPrefetching();
cornerstone.events.removeEventListener(
'cornerstoneimagecachefull.StudyPrefetcher',
this.cacheFullHandler
);
}
static getInstance() {
if (!StudyPrefetcher.instance) {
StudyPrefetcher.instance = new StudyPrefetcher([]);
}
return StudyPrefetcher.instance;
}
setStudies(studies) {
this.stopPrefetching();
this.studies = studies;
}
prefetch() {
if (!this.studies || !this.studies.length) {
return;
}
this.stopPrefetching();
this.prefetchDisplaySets();
}
stopPrefetching() {
cornerstoneTools.requestPoolManager.clearRequestStack('prefetch');
}
prefetchDisplaySetsAsync(timeout) {
timeout = timeout || this.prefetchDisplaySetsTimeout;
clearTimeout(this.prefetchDisplaySetsHandler);
this.prefetchDisplaySetsHandler = setTimeout(() => {
this.prefetchDisplaySets();
}, timeout);
}
prefetchDisplaySets() {
// TODO: Allow passing in config
let config = {
order: 'closest',
displaySetCount: 1,
};
const displaySetsToPrefetch = this.getDisplaySetsToPrefetch(config);
const imageIds = this.getImageIdsFromDisplaySets(displaySetsToPrefetch);
this.prefetchImageIds(imageIds);
}
prefetchImageIds(imageIds) {
const nonCachedImageIds = this.filterCachedImageIds(imageIds);
const requestPoolManager = cornerstoneTools.requestPoolManager;
const requestType = 'prefetch';
const preventCache = false;
const noop = () => {};
nonCachedImageIds.forEach(imageId => {
requestPoolManager.addRequest(
{},
imageId,
requestType,
preventCache,
noop,
noop
);
});
requestPoolManager.startGrabbing();
}
getStudy(image) {
const StudyInstanceUID = cornerstone.metaData.get(
'StudyInstanceUID',
image.imageId
);
return OHIF.viewer.Studies.find(
study => study.StudyInstanceUID === StudyInstanceUID
);
}
getSeries(study, image) {
const SeriesInstanceUID = cornerstone.metaData.get(
'SeriesInstanceUID',
image.imageId
);
const studyMetadata = OHIF.viewerbase.getStudyMetadata(study);
return studyMetadata.getSeriesByUID(SeriesInstanceUID);
}
getInstance(series, image) {
const instanceMetadata = cornerstone.metaData.get(
'instance',
image.imageId
);
return series.getInstanceByUID(instanceMetadata.SOPInstanceUID);
}
getActiveDisplaySet(displaySets, instance) {
return displaySets.find(displaySet => {
return displaySet.images.some(displaySetImage => {
return displaySetImage.SOPInstanceUID === instance.SOPInstanceUID;
});
});
}
getDisplaySetsToPrefetch(config) {
const image = this.getActiveViewportImage();
if (!image || !config || !config.displaySetCount) {
return [];
}
/*const study = this.getStudy(image);
const series = this.getSeries(study, image);
const instance = this.getInstance(series, image);*/
const displaySets = study.displaySets;
const activeDisplaySet = null; //this.getActiveDisplaySet(displaySets, instance);
const prefetchMethodMap = {
topdown: 'getFirstDisplaySets',
downward: 'getNextDisplaySets',
closest: 'getClosestDisplaySets',
};
const prefetchOrder = config.order;
const methodName = prefetchMethodMap[prefetchOrder];
const getDisplaySets = this[methodName];
if (!getDisplaySets) {
if (prefetchOrder) {
log.warn(`Invalid prefetch order configuration (${prefetchOrder})`);
}
return [];
}
return getDisplaySets.call(
this,
displaySets,
activeDisplaySet,
config.displaySetCount
);
}
getFirstDisplaySets(displaySets, activeDisplaySet, displaySetCount) {
const length = displaySets.length;
const selectedDisplaySets = [];
for (let i = 0; i < length && displaySetCount; i++) {
const displaySet = displaySets[i];
if (displaySet !== activeDisplaySet) {
selectedDisplaySets.push(displaySet);
displaySetCount--;
}
}
return selectedDisplaySets;
}
getNextDisplaySets(displaySets, activeDisplaySet, displaySetCount) {
const activeDisplaySetIndex = displaySets.indexOf(activeDisplaySet);
const begin = activeDisplaySetIndex + 1;
const end = Math.min(begin + displaySetCount, displaySets.length);
return displaySets.slice(begin, end);
}
getClosestDisplaySets(displaySets, activeDisplaySet, displaySetCount) {
const activeDisplaySetIndex = displaySets.indexOf(activeDisplaySet);
const length = displaySets.length;
const selectedDisplaySets = [];
let left = activeDisplaySetIndex - 1;
let right = activeDisplaySetIndex + 1;
while ((left >= 0 || right < length) && displaySetCount) {
if (left >= 0) {
selectedDisplaySets.push(displaySets[left]);
displaySetCount--;
left--;
}
if (right < length && displaySetCount) {
selectedDisplaySets.push(displaySets[right]);
displaySetCount--;
right++;
}
}
return selectedDisplaySets;
}
getImageIdsFromDisplaySets(displaySets) {
let imageIds = [];
displaySets.forEach(displaySet => {
imageIds = imageIds.concat(this.getImageIdsFromDisplaySet(displaySet));
});
return imageIds;
}
getImageIdsFromDisplaySet(displaySet) {
const imageIds = [];
// TODO: This duplicates work done by the stack manager
displaySet.images.forEach(image => {
const numFrames = image.numFrames;
if (numFrames > 1) {
for (let i = 0; i < numFrames; i++) {
let imageId = getImageId(image, i);
imageIds.push(imageId);
}
} else {
let imageId = getImageId(image);
imageIds.push(imageId);
}
});
return imageIds;
}
filterCachedImageIds(imageIds) {
return imageIds.filter(imageId => !this.isImageCached(imageId));
}
isImageCached(imageId) {
const image = cornerstone.imageCache.imageCache[imageId];
return image && image.sizeInBytes;
}
cacheFullHandler = () => {
log.warn('Cache full');
this.stopPrefetching();
};
}
@@ -1,508 +0,0 @@
import guid from '../utils/guid';
/**
* Constants
*/
const PROPERTY_SEPARATOR = '.';
const ORDER_ASC = 'asc';
const ORDER_DESC = 'desc';
const MIN_COUNT = 0x00000000;
const MAX_COUNT = 0x7fffffff;
/**
* Class Definition
*/
export class TypeSafeCollection {
constructor() {
this._operationCount = MIN_COUNT;
this._elementList = [];
this._handlers = Object.create(null);
}
/**
* Private Methods
*/
_invalidate() {
let count = this._operationCount;
this._operationCount = count < MAX_COUNT ? count + 1 : MIN_COUNT;
}
_elements(silent) {
silent === true || this._operationCount;
return this._elementList;
}
_elementWithPayload(payload, silent) {
return this._elements(silent).find(item => item.payload === payload);
}
_elementWithId(id, silent) {
return this._elements(silent).find(item => item.id === id);
}
_trigger(event, data) {
let handlers = this._handlers;
if (event in handlers) {
handlers = handlers[event];
if (!(handlers instanceof Array)) {
return;
}
for (let i = 0, limit = handlers.length; i < limit; ++i) {
let handler = handlers[i];
if (_isFunction(handler)) {
handler.call(null, data);
}
}
}
}
/**
* Public Methods
*/
onInsert(callback) {
if (_isFunction(callback)) {
let handlers = this._handlers.insert;
if (!(handlers instanceof Array)) {
handlers = [];
this._handlers.insert = handlers;
}
handlers.push(callback);
}
}
/**
* Update the payload associated with the given ID to be the new supplied payload.
* @param {string} id The ID of the entry that will be updated.
* @param {any} payload The element that will replace the previous payload.
* @returns {boolean} Returns true if the given ID is present in the collection, false otherwise.
*/
updateById(id, payload) {
let result = false,
found = this._elementWithPayload(payload, true);
if (found) {
// nothing to do since the element is already in the collection...
if (found.id === id) {
// set result to true since the ids match...
result = true;
this._invalidate();
}
} else {
found = this._elementWithId(id, true);
if (found) {
found.payload = payload;
result = true;
this._invalidate();
}
}
return result;
}
/**
* Signal that the given element has been changed by notifying reactive data-source observers.
* This method is basically a means to invalidate the inernal reactive data-source.
* @param {any} payload The element that has been altered.
* @returns {boolean} Returns true if the element is present in the collection, false otherwise.
*/
update(payload) {
let result = false,
found = this._elementWithPayload(payload, true);
if (found) {
// nothing to do since the element is already in the collection...
result = true;
this._invalidate();
}
return result;
}
/**
* Insert an element in the collection. On success, the element ID (a unique string) is returned. On failure, returns null.
* A failure scenario only happens when the given payload is already present in the collection. Note that NO exceptions are thrown!
* @param {any} payload The element to be stored.
* @returns {string} The ID of the inserted element or null if the element already exists...
*/
insert(payload) {
let id = null,
found = this._elementWithPayload(payload, true);
if (!found) {
id = guid();
this._elements(true).push({ id, payload });
this._invalidate();
this._trigger('insert', { id, data: payload });
}
return id;
}
/**
* Remove all elements from the collection.
* @returns {void} No meaningful value is returned.
*/
removeAll() {
let all = this._elements(true),
length = all.length;
for (let i = length - 1; i >= 0; i--) {
let item = all[i];
delete item.id;
delete item.payload;
all[i] = null;
}
all.splice(0, length);
this._invalidate();
}
/**
* Remove elements from the collection that match the criteria given in the property map.
* @param {Object} propertyMap A property map that will be macthed against all collection elements.
* @returns {Array} A list with all removed elements.
*/
remove(propertyMap) {
let found = this.findAllEntriesBy(propertyMap),
foundCount = found.length,
removed = [];
if (foundCount > 0) {
const all = this._elements(true);
for (let i = foundCount - 1; i >= 0; i--) {
let item = found[i];
all.splice(item[2], 1);
removed.push(item[0]);
}
this._invalidate();
}
return removed;
}
/**
* Provides the ID of the given element inside the collection.
* @param {any} payload The element being searched for.
* @returns {string} The ID of the given element or undefined if the element is not present.
*/
getElementId(payload) {
let found = this._elementWithPayload(payload);
return found && found.id;
}
/**
* Provides the position of the given element in the internal list returning -1 if the element is not present.
* @param {any} payload The element being searched for.
* @returns {number} The position of the given element in the internal list. If the element is not present -1 is returned.
*/
findById(id) {
let found = this._elementWithId(id);
return found && found.payload;
}
/**
* Provides the position of the given element in the internal list returning -1 if the element is not present.
* @param {any} payload The element being searched for.
* @returns {number} The position of the given element in the internal list. If the element is not present -1 is returned.
*/
indexOfElement(payload) {
return this._elements().indexOf(this._elementWithPayload(payload, true));
}
/**
* Provides the position of the element associated with the given ID in the internal list returning -1 if the element is not present.
* @param {string} id The index of the element.
* @returns {number} The position of the element associated with the given ID in the internal list. If the element is not present -1 is returned.
*/
indexOfId(id) {
return this._elements().indexOf(this._elementWithId(id, true));
}
/**
* Provides a list-like approach to the collection returning an element by index.
* @param {number} index The index of the element.
* @returns {any} If out of bounds, undefined is returned. Otherwise the element in the given position is returned.
*/
getElementByIndex(index) {
let found = this._elements()[index >= 0 ? index : -1];
return found && found.payload;
}
/**
* Find an element by a criteria defined by the given callback function.
* Attention!!! The reactive source will not be notified if no valid callback is supplied...
* @param {function} callback A callback function which will define the search criteria. The callback
* function will be passed the collection element, its ID and its index in this very order. The callback
* shall return true when its criterea has been fulfilled.
* @returns {any} The matched element or undefined if not match was found.
*/
find(callback) {
let found;
if (_isFunction(callback)) {
found = this._elements().find((item, index) => {
return callback.call(this, item.payload, item.id, index);
});
}
return found && found.payload;
}
/**
* Find the first element that strictly matches the specified property map.
* @param {Object} propertyMap A property map that will be macthed against all collection elements.
* @param {Object} options A set of options. Currently only "options.sort" option is supported.
* @param {Object.SortingSpecifier} options.sort An optional sorting specifier. If a sorting specifier is supplied
* but is not valid, an exception will be thrown.
* @returns {Any} The matched element or undefined if not match was found.
*/
findBy(propertyMap, options) {
let found;
if (_isObject(options)) {
// if the "options" argument is provided and is a valid object,
// it must be applied to the dataset before search...
const all = this.all(options);
if (all.length > 0) {
if (_isObject(propertyMap)) {
found = all.find(item =>
_compareToPropertyMapStrict(propertyMap, item)
);
} else {
found = all[0]; // simply extract the first element...
}
}
} else if (_isObject(propertyMap)) {
found = this._elements().find(item =>
_compareToPropertyMapStrict(propertyMap, item.payload)
);
if (found) {
found = found.payload;
}
}
return found;
}
/**
* Find all elements that strictly match the specified property map.
* Attention!!! The reactive source will not be notified if no valid property map is supplied...
* @param {Object} propertyMap A property map that will be macthed against all collection elements.
* @returns {Array} An array of entries of all elements that match the given criteria. Each set in
* in the array has the following format: [ elementData, elementId, elementIndex ].
*/
findAllEntriesBy(propertyMap) {
const found = [];
if (_isObject(propertyMap)) {
this._elements().forEach((item, index) => {
if (_compareToPropertyMapStrict(propertyMap, item.payload)) {
// Match! Add it to the found list...
found.push([item.payload, item.id, index]);
}
});
}
return found;
}
/**
* Find all elements that match a specified property map.
* Attention!!! The reactive source will not be notified if no valid property map is supplied...
* @param {Object} propertyMap A property map that will be macthed against all collection elements.
* @param {Object} options A set of options. Currently only "options.sort" option is supported.
* @param {Object.SortingSpecifier} options.sort An optional sorting specifier. If a sorting specifier is supplied
* but is not valid, an exception will be thrown.
* @returns {Array} An array with all elements that match the given criteria and sorted in the specified sorting order.
*/
findAllBy(propertyMap, options) {
const found = this.findAllEntriesBy(propertyMap).map(item => item[0]); // Only payload is relevant...
if (_isObject(options)) {
if ('sort' in options) {
_sortListBy(found, options.sort);
}
}
return found;
}
/**
* Executes the supplied callback function for each element of the collection.
* Attention!!! The reactive source will not be notified if no valid property map is supplied...
* @param {function} callback The callback function to be executed. The callback is passed the element,
* its ID and its index in this very order.
* @returns {void} Nothing is returned.
*/
forEach(callback) {
if (_isFunction(callback)) {
this._elements().forEach((item, index) => {
callback.call(this, item.payload, item.id, index);
});
}
}
/**
* Count the number of elements currently in the collection.
* @returns {number} The current number of elements in the collection.
*/
count() {
return this._elements().length;
}
/**
* Returns a list with all elements of the collection optionally sorted by a sorting specifier criteria.
* @param {Object} options A set of options. Currently only "options.sort" option is supported.
* @param {Object.SortingSpecifier} options.sort An optional sorting specifier. If a sorting specifier is supplied
* but is not valid, an exception will be thrown.
* @returns {Array} An array with all elements stored in the collection.
*/
all(options) {
let list = this._elements().map(item => item.payload);
if (_isObject(options)) {
if ('sort' in options) {
_sortListBy(list, options.sort);
}
}
return list;
}
}
/**
* Utility Functions
*/
/**
* Test if supplied argument is a valid object for current class purposes.
* Atention! The underscore version of this function should not be used for performance reasons.
*/
function _isObject(subject) {
return (
subject instanceof Object ||
(typeof subject === 'object' && subject !== null)
);
}
/**
* Test if supplied argument is a valid string for current class purposes.
* Atention! The underscore version of this function should not be used for performance reasons.
*/
function _isString(subject) {
return typeof subject === 'string';
}
/**
* Test if supplied argument is a valid function for current class purposes.
* Atention! The underscore version of this function should not be used for performance reasons.
*/
function _isFunction(subject) {
return typeof subject === 'function';
}
/**
* Shortcut for Object's prototype "hasOwnProperty" method.
*/
const _hasOwnProperty = Object.prototype.hasOwnProperty;
/**
* Retrieve an object's property value by name. Composite property names (e.g., 'address.country.name') are accepted.
* @param {Object} targetObject The object we want read the property from...
* @param {String} propertyName The property to be read (e.g., 'address.street.name' or 'address.street.number'
* to read object.address.street.name or object.address.street.number, respectively);
* @returns {Any} Returns whatever the property holds or undefined if the property cannot be read or reached.
*/
function _getPropertyValue(targetObject, propertyName) {
let propertyValue; // undefined (the default return value)
if (_isObject(targetObject) && _isString(propertyName)) {
const fragments = propertyName.split(PROPERTY_SEPARATOR);
const fragmentCount = fragments.length;
if (fragmentCount > 0) {
const firstFragment = fragments[0];
const remainingFragments =
fragmentCount > 1 ? fragments.slice(1).join(PROPERTY_SEPARATOR) : null;
propertyValue = targetObject[firstFragment];
if (remainingFragments !== null) {
propertyValue = _getPropertyValue(propertyValue, remainingFragments);
}
}
}
return propertyValue;
}
/**
* Compare a property map with a target object using strict comparison.
* @param {Object} propertyMap The property map whose properties will be used for comparison. Composite
* property names (e.g., 'address.country.name') will be tested against the "resolved" properties from the target object.
* @param {Object} targetObject The target object whose properties will be tested.
* @returns {boolean} Returns true if the properties match, false otherwise.
*/
function _compareToPropertyMapStrict(propertyMap, targetObject) {
let result = false;
// "for in" loops do not thown exceptions for invalid data types...
for (let propertyName in propertyMap) {
if (_hasOwnProperty.call(propertyMap, propertyName)) {
if (
propertyMap[propertyName] !==
_getPropertyValue(targetObject, propertyName)
) {
result = false;
break;
} else if (result !== true) {
result = true;
}
}
}
return result;
}
/**
* Checks if a sorting specifier is valid.
* A valid sorting specifier consists of an array of arrays being each subarray a pair
* in the format ["property name", "sorting order"].
* The following exemple can be used to sort studies by "date"" and use "time" to break ties in descending order.
* [ [ 'study.date', 'desc' ], [ 'study.time', 'desc' ] ]
* @param {Array} specifiers The sorting specifier to be tested.
* @returns {boolean} Returns true if the specifiers are valid, false otherwise.
*/
function _isValidSortingSpecifier(specifiers) {
let result = true;
if (specifiers instanceof Array && specifiers.length > 0) {
for (let i = specifiers.length - 1; i >= 0; i--) {
const item = specifiers[i];
if (item instanceof Array) {
const property = item[0];
const order = item[1];
if (
_isString(property) &&
(order === ORDER_ASC || order === ORDER_DESC)
) {
continue;
}
}
result = false;
break;
}
}
return result;
}
/**
* Sorts an array based on sorting specifier options.
* @param {Array} list The that needs to be sorted.
* @param {Array} specifiers An array of specifiers. Please read isValidSortingSpecifier method definition for further details.
* @returns {void} No value is returned. The array is sorted in place.
*/
function _sortListBy(list, specifiers) {
if (list instanceof Array && _isValidSortingSpecifier(specifiers)) {
const specifierCount = specifiers.length;
list.sort(function _sortListByCallback(a, b) {
// callback name for stack traces...
let index = 0;
while (index < specifierCount) {
const specifier = specifiers[index];
const property = specifier[0];
const order = specifier[1] === ORDER_DESC ? -1 : 1;
const aValue = _getPropertyValue(a, property);
const bValue = _getPropertyValue(b, property);
// @TODO: should we check for the types being compared, like:
// ~~ if (typeof aValue !== typeof bValue) continue;
// Not sure because dates, for example, can be correctly compared to numbers...
if (aValue < bValue) {
return order * -1;
}
if (aValue > bValue) {
return order * 1;
}
if (++index >= specifierCount) {
return 0;
}
}
});
} else {
throw new Error('Invalid Arguments');
}
}
-29
View File
@@ -1,52 +1,23 @@
import { InstanceMetadata, SeriesMetadata, StudyMetadata } from './metadata';
import CommandsManager from './CommandsManager.js';
import { DICOMFileLoadingListener } from './StudyLoadingListener';
import HotkeysManager from './HotkeysManager.js';
import ImageSet from './ImageSet';
import MetadataProvider from './MetadataProvider';
import OHIFError from './OHIFError.js';
import { OHIFStudyMetadataSource } from './OHIFStudyMetadataSource';
import { StackLoadingListener } from './StudyLoadingListener';
import { StudyLoadingListener } from './StudyLoadingListener';
import { StudyMetadataSource } from './StudyMetadataSource';
import { StudyPrefetcher } from './StudyPrefetcher';
import { TypeSafeCollection } from './TypeSafeCollection';
export {
OHIFStudyMetadataSource,
MetadataProvider,
CommandsManager,
HotkeysManager,
ImageSet,
StudyPrefetcher,
StudyLoadingListener,
StackLoadingListener,
DICOMFileLoadingListener,
StudyMetadata,
SeriesMetadata,
InstanceMetadata,
TypeSafeCollection,
OHIFError,
StudyMetadataSource,
};
const classes = {
OHIFStudyMetadataSource,
MetadataProvider,
CommandsManager,
HotkeysManager,
ImageSet,
StudyPrefetcher,
StudyLoadingListener,
StackLoadingListener,
DICOMFileLoadingListener,
StudyMetadata,
SeriesMetadata,
InstanceMetadata,
TypeSafeCollection,
OHIFError,
StudyMetadataSource,
};
export default classes;
@@ -1,210 +0,0 @@
import { Metadata } from './Metadata';
import OHIFError from '../OHIFError.js';
/**
* ATTENTION! This class should never depend on StudyMetadata or SeriesMetadata classes as this could
* possibly cause circular dependency issues.
*/
const UNDEFINED = 'undefined';
const STRING = 'string';
export class InstanceMetadata extends Metadata {
constructor(data, uid) {
super(data, uid);
// Initialize Private Properties
Object.defineProperties(this, {
_imageId: {
configurable: true, // configurable so that it can be redefined in sub-classes...
enumerable: false,
writable: true,
value: null,
},
});
// Initialize Public Properties
this._definePublicProperties();
}
/**
* Private Methods
*/
/**
* Define Public Properties
* This method should only be called during initialization (inside the class constructor)
*/
_definePublicProperties() {
/**
* Property: this.SOPInstanceUID
* Same as this.getSOPInstanceUID()
* It's specially useful in contexts where a method call is not suitable like in search criteria. For example:
* sopInstanceCollection.findBy({
* SOPInstanceUID: '1.2.3.4.5.6.77777.8888888.99999999999.0'
* });
*/
Object.defineProperty(this, 'SOPInstanceUID', {
configurable: false,
enumerable: false,
get: function() {
return this.getSOPInstanceUID();
},
});
}
/**
* Public Methods
*/
/**
* Returns the StudyInstanceUID of the current instance. This method is basically a shorthand the full "getTagValue" method call.
*/
getStudyInstanceUID() {
return this.getTagValue('StudyInstanceUID', null);
}
/**
* Returns the SeriesInstanceUID of the current instance. This method is basically a shorthand the full "getTagValue" method call.
*/
getSeriesInstanceUID() {
return this.getTagValue('SeriesInstanceUID', null);
}
/**
* Returns the SOPInstanceUID of the current instance.
*/
getSOPInstanceUID() {
return this.getTagValue('SOPInstanceUID', null);
}
// @TODO: Improve this... (E.g.: blob data)
getStringValue(tagOrProperty, index, defaultValue) {
let value = this.getTagValue(tagOrProperty, defaultValue);
if (typeof value !== STRING && typeof value !== UNDEFINED) {
value = value.toString();
}
return InstanceMetadata.getIndexedValue(value, index, defaultValue);
}
// @TODO: Improve this... (E.g.: blob data)
getFloatValue(tagOrProperty, index, defaultValue) {
let value = this.getTagValue(tagOrProperty, defaultValue);
value = InstanceMetadata.getIndexedValue(value, index, defaultValue);
if (value instanceof Array) {
value.forEach((val, idx) => {
value[idx] = parseFloat(val);
});
return value;
}
return typeof value === STRING ? parseFloat(value) : value;
}
// @TODO: Improve this... (E.g.: blob data)
getIntValue(tagOrProperty, index, defaultValue) {
let value = this.getTagValue(tagOrProperty, defaultValue);
value = InstanceMetadata.getIndexedValue(value, index, defaultValue);
if (value instanceof Array) {
value.forEach((val, idx) => {
value[idx] = parseFloat(val);
});
return value;
}
return typeof value === STRING ? parseInt(value) : value;
}
/**
* This function should be overriden by specialized classes in order to allow client libraries or viewers to take advantage of the Study Metadata API.
*/
getTagValue(tagOrProperty, defaultValue) {
/**
* Please override this method on a specialized class.
*/
throw new OHIFError(
'InstanceMetadata::getTagValue is not overriden. Please, override it in a specialized class. See OHIFInstanceMetadata for example'
);
}
/**
* Compares the current instance with another one.
* @param {InstanceMetadata} instance An instance of the InstanceMetadata class.
* @returns {boolean} Returns true if both instances refer to the same instance.
*/
equals(instance) {
const self = this;
return (
instance === self ||
(instance instanceof InstanceMetadata &&
instance.getSOPInstanceUID() === self.getSOPInstanceUID())
);
}
/**
* Check if the tagOrProperty exists
* @param {String} tagOrProperty tag or property be checked
* @return {Boolean} True if the tag or property exists or false if doesn't
*/
tagExists(tagOrProperty) {
/**
* Please override this method
*/
throw new OHIFError(
'InstanceMetadata::tagExists is not overriden. Please, override it in a specialized class. See OHIFInstanceMetadata for example'
);
}
/**
* Get custom image id of a sop instance
* @return {Any} sop instance image id
*/
getImageId(frame) {
/**
* Please override this method
*/
throw new OHIFError(
'InstanceMetadata::getImageId is not overriden. Please, override it in a specialized class. See OHIFInstanceMetadata for example'
);
}
/**
* Static Methods
*/
/**
* Get an value based that can be index based. This function is called by all getters. See above functions.
* - If value is a String and has indexes:
* - If undefined index: returns an array of the split values.
* - If defined index:
* - If invalid: returns defaultValue
* - If valid: returns the indexed value
* - If value is not a String, returns default value.
*/
static getIndexedValue(value, index, defaultValue) {
let result = defaultValue;
if (typeof value === STRING) {
const hasIndexValues = value.indexOf('\\') !== -1;
result = value;
if (hasIndexValues) {
const splitValues = value.split('\\');
if (Metadata.isValidIndex(index)) {
const indexedValue = splitValues[index];
result = typeof indexedValue !== STRING ? defaultValue : indexedValue;
} else {
result = splitValues;
}
}
}
return result;
}
}
@@ -1,127 +0,0 @@
/**
* Constants
*/
const STRING = 'string';
const NUMBER = 'number';
const FUNCTION = 'function';
const OBJECT = 'object';
/**
* Class Definition
*/
export class Metadata {
/**
* Constructor and Instance Methods
*/
constructor(data, uid) {
// Define the main "_data" private property as an immutable property.
// IMPORTANT: This property can only be set during instance construction.
Object.defineProperty(this, '_data', {
configurable: false,
enumerable: false,
writable: false,
value: data,
});
// Define the main "_uid" private property as an immutable property.
// IMPORTANT: This property can only be set during instance construction.
Object.defineProperty(this, '_uid', {
configurable: false,
enumerable: false,
writable: false,
value: uid,
});
// Define "_custom" properties as an immutable property.
// IMPORTANT: This property can only be set during instance construction.
Object.defineProperty(this, '_custom', {
configurable: false,
enumerable: false,
writable: false,
value: Object.create(null),
});
}
getData() {
return this._data;
}
getDataProperty(propertyName) {
let propertyValue;
const _data = this._data;
if (
_data instanceof Object ||
(typeof _data === OBJECT && _data !== null)
) {
propertyValue = _data[propertyName];
}
return propertyValue;
}
/**
* Get unique object ID
*/
getObjectID() {
return this._uid;
}
/**
* Set custom attribute value
* @param {String} attribute Custom attribute name
* @param {Any} value Custom attribute value
*/
setCustomAttribute(attribute, value) {
this._custom[attribute] = value;
}
/**
* Get custom attribute value
* @param {String} attribute Custom attribute name
* @return {Any} Custom attribute value
*/
getCustomAttribute(attribute) {
return this._custom[attribute];
}
/**
* Check if a custom attribute exists
* @param {String} attribute Custom attribute name
* @return {Boolean} True if custom attribute exists or false if not
*/
customAttributeExists(attribute) {
return attribute in this._custom;
}
/**
* Set custom attributes in batch mode.
* @param {Object} attributeMap An object whose own properties will be used as custom attributes.
*/
setCustomAttributes(attributeMap) {
const _hasOwn = Object.prototype.hasOwnProperty;
const _custom = this._custom;
for (let attribute in attributeMap) {
if (_hasOwn.call(attributeMap, attribute)) {
_custom[attribute] = attributeMap[attribute];
}
}
}
/**
* Static Methods
*/
static isValidUID(uid) {
return typeof uid === STRING && uid.length > 0;
}
static isValidIndex(index) {
return typeof index === NUMBER && index >= 0 && (index | 0) === index;
}
static isValidCallback(callback) {
return typeof callback === FUNCTION;
}
}
@@ -1,97 +0,0 @@
import { InstanceMetadata } from './InstanceMetadata';
import getImageId from '../../utils/getImageId.js';
export class OHIFInstanceMetadata extends InstanceMetadata {
/**
* @param {Object} Instance object.
*/
constructor(data, series, study, uid) {
super(data, uid);
this.init(series, study);
}
init(series, study) {
const instance = this.getData();
// Initialize Private Properties
Object.defineProperties(this, {
_sopInstanceUID: {
configurable: false,
enumerable: false,
writable: false,
value: instance.SOPInstanceUID,
},
_study: {
configurable: false,
enumerable: false,
writable: false,
value: study,
},
_series: {
configurable: false,
enumerable: false,
writable: false,
value: series,
},
_instance: {
configurable: false,
enumerable: false,
writable: false,
value: instance,
},
_cache: {
configurable: false,
enumerable: false,
writable: false,
value: Object.create(null),
},
});
}
// Override
getTagValue(tagOrProperty, defaultValue, bypassCache) {
// check if this property has been cached...
if (tagOrProperty in this._cache && bypassCache !== true) {
return this._cache[tagOrProperty];
}
const instanceData = this._instance.metadata;
// Search property value in the whole study metadata chain...
let rawValue;
if (tagOrProperty in instanceData) {
rawValue = instanceData[tagOrProperty];
} else if (tagOrProperty in this._series) {
rawValue = this._series[tagOrProperty];
} else if (tagOrProperty in this._study) {
rawValue = this._study[tagOrProperty];
}
if (rawValue !== void 0) {
// if rawValue value is not undefined, cache result...
this._cache[tagOrProperty] = rawValue;
return rawValue;
}
return defaultValue;
}
// Override
tagExists(tagOrProperty) {
return (
tagOrProperty in this._instance.metadata ||
tagOrProperty in this._series ||
tagOrProperty in this._study
);
}
// Override
getImageId(frame, thumbnail) {
// If _imageID is not cached, create it
if (this._imageId === null) {
this._imageId = getImageId(this.getData(), frame, thumbnail);
}
return this._imageId;
}
}
@@ -1,29 +0,0 @@
import { SeriesMetadata } from './SeriesMetadata';
import { OHIFInstanceMetadata } from './OHIFInstanceMetadata';
export class OHIFSeriesMetadata extends SeriesMetadata {
/**
* @param {Object} Series object.
*/
constructor(data, study, uid) {
super(data, uid);
this.init(study);
}
init(study) {
const series = this.getData();
// define "_seriesInstanceUID" protected property...
Object.defineProperty(this, '_seriesInstanceUID', {
configurable: false,
enumerable: false,
writable: false,
value: series.SeriesInstanceUID,
});
// populate internal list of instances...
series.instances.forEach(instance => {
this.addInstance(new OHIFInstanceMetadata(instance, series, study));
});
}
}
@@ -1,29 +0,0 @@
import { StudyMetadata } from './StudyMetadata';
import { OHIFSeriesMetadata } from './OHIFSeriesMetadata';
export class OHIFStudyMetadata extends StudyMetadata {
/**
* @param {Object} Study object.
*/
constructor(data, uid) {
super(data, uid);
this.init();
}
init() {
const study = this.getData();
// define "_studyInstanceUID" protected property
Object.defineProperty(this, '_studyInstanceUID', {
configurable: false,
enumerable: false,
writable: false,
value: study.StudyInstanceUID,
});
// populate internal list of series
study.series.forEach(series => {
this.addSeries(new OHIFSeriesMetadata(series, study));
});
}
}
@@ -1,145 +0,0 @@
# Study Metadata Module
This module defines the API/Data-Model by which OHIF Viewerbase package and
possibly distinct viewer implementations can access studies metadata. This
module does not attempt to define any means of _loading_ study metadata from any
data end-point but only how the data that has been previously loaded into the
application context will be accessed by any of the routines or algorithm
implementations that need the data.
## Intro
For various reasons like sorting, grouping or simply rendering study
information, OHIF Viewerbase package and applications depending on it usually
have the need to access study metadata. Before the current initiative there was
no uniform way of achieving that since each implementation provides study
metadata on its own specific ways. The application and the package itself needed
to have a deep knowledge of the data structures provided by the data endpoint to
perform any of the operations mentioned above, meaning that any data access code
needed to be adapted or rewritten.
The intent of the current module is to provide a fairly consistent and flexible
API/Data-Model by which OHIF Viewerbase package (and different viewer
implementations that depend on it) can manipulate DICOM matadata retrieved from
distinct data end points (e.g., a proprietary back end servers) in uniform ways
with minor to no modifications needed.
## Implementation
The current API implementation defines three classes of objects:
`StudyMetadata`, `SeriesMetadata` and `InstanceMetadata`. Inside OHIF Viewerbase
package, every access to Study, Series or SOP Instance metadata is achieved by
the interface exposed by these three classes. By inheriting from them and
overriding or extending their methods, different applications with different
data models can adapt even the most peculiar data structures to the uniform
interface defined by those classes. Together these classes define a flexible and
extensible data manipulation layer leaving routines and algorithms that depend
on that data untouched.
## Design Decisions & "_Protected_" Members
In order to provide for good programming practices, attributes and methods meant
to be used exclusively by the classes themselves (for internal purposes only)
were written with an initial '\_' character, being thus treated as "_protected_"
members. The idea behind this practice was never to hide them from the
programmers (what makes debugging tasks painful) but only advise for something
that's not part of the official public API and thus should not be relied on.
Usage of "protected" members makes the code less readable and prone to
compatibility issues.
As an example, the initial implementation of the `StudyMetadata` class defined
the attribute `_studyInstanceUID` and the method `getStudyInstanceUID`. This
implies that whenever the _StudyInstanceUID_ of a given study needs to be
retrieved the `getStudyInstanceUID` method should be called instead of directly
accessing the attribute `_studyInstanceUID` (which might not even be populated
since `getStudyInstanceUID` can be possiblity overriden by a subclass to satisfy
specific implementation needs, leaving the attribute `_studyInstanceUID`
unused).
Ex:
```javascript
let studyUID = myStudy.getStudyInstanceUID(); // GOOD! :-)
[ ... ]
let otherStudyUID = anotherStudy._studyInstanceUID; // BAD... :-(
```
Another important topic is the preference of _methods_ over _attributes_ on the
public API. This design decision was made to ensure extensibility and
flexibility (methods are extensible while standalone attributes are not, and can
be adapted – through overrides, for example – to support even the most peculiar
data models) even though the overhead a few additional function calls may incur.
## Abstract Classes
Some classes defined in this module are "_abstract_" classes (even though
JavaScript does not _officially_ support such programming facility). They are
_abstract_ in the sense that a few methods (very important ones, by the way)
were left "_blank_" (unimplemented, or more precisely implemented as empty NOP
functions) in order to be implemented by specialized subclasses. Methods
believed to be more generic were implemented in an attempt to satify most
implementation needs but nothing prevents a subclass from overriding them as
well (again, flexibility and extensibility are design goals). Most implemented
methods rely on the implementation of an unimplemented method. For example, the
method `getStringValue` from `InstanceMetadata` class, which has indeed been
implemented and is meant to retrieve a metadata value as a string, internally
calls the `getTagValue` method which _was NOT implemented_ and is meant to query
the internal data structures for the requested metadata value and return it _as
is_. Used in that way, an application would not benefit much from the already
implemented methods. On the other hand, by simply overriding the `getTagValue`
method on a specialized class to deal with the intrinsics of its internal data
structures, this very application would now benefit from all already implemented
methods.
The following code snippet tries to illustrate the idea:
```javascript
// -- InstanceMetadata.js
class InstanceMetadata {
[ ... ]
getTagValue(tagOrProperty, defaultValue) {
// Please implement this method in a specialized subclass...
}
[ ... ]
getStringValue(tagOrProperty, index, defaultValue) {
let rawValue = this.getTagValue(tagOrProperty, '');
// parse the returned value into a string...
[ ... ]
return stringValue;
}
[ ... ]
}
// -- MyFancyAppInstanceMetadata.js
class MyFancyAppInstanceMetadata extends InstanceMetadata {
// Overriding this method will make all methods implemented in the super class
// that rely on it to be immediately available...
getTagValue(tagOrProperty, defaultValue) {
let tagValue;
// retrieve raw value from internal data structures...
[ ... ]
return tagValue;
}
}
// -- main.js
[ ... ]
let sopInstaceMetadata = new MyFancyAppInstanceMetadata(myInternalData);
if (sopInstaceMetadata instanceof MyFancyAppInstanceMetadata) { // true
// this code will be executed...
}
if (sopInstaceMetadata instanceof InstanceMetadata) { // also true
// this code will also be executed...
}
// The following will also work since the internal "getTagValue" call inside
// "getStringValue" method will now be satisfied... (thanks to the override)
let PatientName = sopInstaceMetadata.getStringValue('PatientName', '');
[ ... ]
```
_Copyright &copy; 2016 nucleushealth&trade;. All rights reserved_
@@ -1,192 +0,0 @@
import { Metadata } from './Metadata';
import { InstanceMetadata } from './InstanceMetadata';
export class SeriesMetadata extends Metadata {
constructor(data, uid) {
super(data, uid);
// Initialize Private Properties
Object.defineProperties(this, {
_seriesInstanceUID: {
configurable: true, // configurable so that it can be redefined in sub-classes...
enumerable: false,
writable: true,
value: null,
},
_instances: {
configurable: false,
enumerable: false,
writable: false,
value: [],
},
_firstInstance: {
configurable: false,
enumerable: false,
writable: true,
value: null,
},
});
// Initialize Public Properties
this._definePublicProperties();
}
/**
* Private Methods
*/
/**
* Define Public Properties
* This method should only be called during initialization (inside the class constructor)
*/
_definePublicProperties() {
/**
* Property: this.seriesInstanceUID
* Same as this.getSeriesInstanceUID()
* It's specially useful in contexts where a method call is not suitable like in search criteria. For example:
* seriesCollection.findBy({
* seriesInstanceUID: '1.2.3.4.5.6.77777.8888888.99999999999.0'
* });
*/
Object.defineProperty(this, 'seriesInstanceUID', {
configurable: false,
enumerable: false,
get: function() {
return this.getSeriesInstanceUID();
},
});
}
/**
* Public Methods
*/
/**
* Returns the SeriesInstanceUID of the current series.
*/
getSeriesInstanceUID() {
return this._seriesInstanceUID;
}
/**
* Append an instance to the current series.
* @param {InstanceMetadata} instance The instance to be added to the current series.
* @returns {boolean} Returns true on success, false otherwise.
*/
addInstance(instance) {
let result = false;
if (
instance instanceof InstanceMetadata &&
this.getInstanceByUID(instance.getSOPInstanceUID()) === void 0
) {
this._instances.push(instance);
result = true;
}
return result;
}
/**
* Get the first instance of the current series retaining a consistent result across multiple calls.
* @return {InstanceMetadata} An instance of the InstanceMetadata class or null if it does not exist.
*/
getFirstInstance() {
let instance = this._firstInstance;
if (!(instance instanceof InstanceMetadata)) {
instance = null;
const found = this.getInstanceByIndex(0);
if (found instanceof InstanceMetadata) {
this._firstInstance = found;
instance = found;
}
}
return instance;
}
/**
* Find an instance by index.
* @param {number} index An integer representing a list index.
* @returns {InstanceMetadata} Returns a InstanceMetadata instance when found or undefined otherwise.
*/
getInstanceByIndex(index) {
let found; // undefined by default...
if (Metadata.isValidIndex(index)) {
found = this._instances[index];
}
return found;
}
/**
* Find an instance by SOPInstanceUID.
* @param {string} uid An UID string.
* @returns {InstanceMetadata} Returns a InstanceMetadata instance when found or undefined otherwise.
*/
getInstanceByUID(uid) {
let found; // undefined by default...
if (Metadata.isValidUID(uid)) {
found = this._instances.find(instance => {
return instance.getSOPInstanceUID() === uid;
});
}
return found;
}
/**
* Retrieve the number of instances within the current series.
* @returns {number} The number of instances in the current series.
*/
getInstanceCount() {
return this._instances.length;
}
/**
* Invokes the supplied callback for each instance in the current series passing
* two arguments: instance (an InstanceMetadata instance) and index (the integer
* index of the instance within the current series)
* @param {function} callback The callback function which will be invoked for each instance in the series.
* @returns {undefined} Nothing is returned.
*/
forEachInstance(callback) {
if (Metadata.isValidCallback(callback)) {
this._instances.forEach((instance, index) => {
callback.call(null, instance, index);
});
}
}
/**
* Find the index of an instance inside the series.
* @param {InstanceMetadata} instance An instance of the SeriesMetadata class.
* @returns {number} The index of the instance inside the series or -1 if not found.
*/
indexOfInstance(instance) {
return this._instances.indexOf(instance);
}
/**
* Search the associated instances using the supplied callback as criteria. The callback is passed
* two arguments: instance (a InstanceMetadata instance) and index (the integer
* index of the instance within its series)
* @param {function} callback The callback function which will be invoked for each instance.
* @returns {InstanceMetadata|undefined} If an instance is found based on callback criteria it
* returns a InstanceMetadata. "undefined" is returned otherwise
*/
findInstance(callback) {
if (Metadata.isValidCallback(callback)) {
return this._instances.find((instance, index) => {
return callback.call(null, instance, index);
});
}
}
/**
* Compares the current series with another one.
* @param {SeriesMetadata} series An instance of the SeriesMetadata class.
* @returns {boolean} Returns true if both instances refer to the same series.
*/
equals(series) {
const self = this;
return (
series === self ||
(series instanceof SeriesMetadata &&
series.getSeriesInstanceUID() === self.getSeriesInstanceUID())
);
}
}
@@ -1,906 +0,0 @@
// - createStacks
import DICOMWeb from './../../DICOMWeb';
import ImageSet from './../ImageSet';
import { InstanceMetadata } from './InstanceMetadata';
import { Metadata } from './Metadata';
import OHIFError from '../OHIFError';
import { SeriesMetadata } from './SeriesMetadata';
// - createStacks
import { api } from 'dicomweb-client';
// - createStacks
import { isImage } from '../../utils/isImage';
import isDisplaySetReconstructable from '../../utils/isDisplaySetReconstructable';
import isLowPriorityModality from '../../utils/isLowPriorityModality';
import errorHandler from '../../errorHandler';
export class StudyMetadata extends Metadata {
constructor(data, uid) {
super(data, uid);
// Initialize Private Properties
Object.defineProperties(this, {
_studyInstanceUID: {
configurable: true, // configurable so that it can be redefined in sub-classes...
enumerable: false,
writable: true,
value: null,
},
_series: {
configurable: false,
enumerable: false,
writable: false,
value: [],
},
_displaySets: {
configurable: false,
enumerable: false,
writable: false,
value: [],
},
_derivedDisplaySets: {
configurable: false,
enumerable: false,
writable: false,
value: [],
},
_firstSeries: {
configurable: false,
enumerable: false,
writable: true,
value: null,
},
_firstInstance: {
configurable: false,
enumerable: false,
writable: true,
value: null,
},
});
// Initialize Public Properties
this._definePublicProperties();
}
/**
* Private Methods
*/
/**
* Define Public Properties
* This method should only be called during initialization (inside the class constructor)
*/
_definePublicProperties() {
/**
* Property: this.studyInstanceUID
* Same as this.getStudyInstanceUID()
* It's specially useful in contexts where a method call is not suitable like in search criteria. For example:
* studyCollection.findBy({
* studyInstanceUID: '1.2.3.4.5.6.77777.8888888.99999999999.0'
* });
*/
Object.defineProperty(this, 'studyInstanceUID', {
configurable: false,
enumerable: false,
get: function() {
return this.getStudyInstanceUID();
},
});
}
/**
* Public Methods
*/
/**
* Getter for displaySets
* @return {Array} Array of display set object
*/
getDisplaySets() {
return this._displaySets.slice();
}
/**
* Split a series metadata object into display sets
* @param {Array} sopClassHandlerModules List of SOP Class Modules
* @param {SeriesMetadata} series The series metadata object from which the display sets will be created
* @returns {Array} The list of display sets created for the given series object
*/
_createDisplaySetsForSeries(sopClassHandlerModules, series) {
const study = this;
const displaySets = [];
const anyInstances = series.getInstanceCount() > 0;
if (!anyInstances) {
const displaySet = new ImageSet([]);
const seriesData = series.getData();
displaySet.setAttributes({
displaySetInstanceUID: displaySet.uid,
SeriesInstanceUID: seriesData.SeriesInstanceUID,
SeriesDescription: seriesData.SeriesDescription,
SeriesNumber: seriesData.SeriesNumber,
Modality: seriesData.Modality,
});
displaySets.push(displaySet);
return displaySets;
}
const sopClassUIDs = getSopClassUIDs(series);
if (sopClassHandlerModules && sopClassHandlerModules.length > 0) {
const displaySet = _getDisplaySetFromSopClassModule(
sopClassHandlerModules,
series,
study,
sopClassUIDs
);
if (displaySet) {
displaySet.sopClassModule = true;
displaySet.isDerived
? this._addDerivedDisplaySet(displaySet)
: displaySets.push(displaySet);
return displaySets;
}
}
// WE NEED A BETTER WAY TO NOTE THAT THIS IS THE DEFAULT BEHAVIOR FOR LOADING
// A DISPLAY SET IF THERE IS NO MATCHING SOP CLASS PLUGIN
// Search through the instances (InstanceMetadata object) of this series
// Split Multi-frame instances and Single-image modalities
// into their own specific display sets. Place the rest of each
// series into another display set.
const stackableInstances = [];
series.forEachInstance(instance => {
// All imaging modalities must have a valid value for SOPClassUID (x00080016) or Rows (x00280010)
if (
!isImage(instance.getTagValue('SOPClassUID')) &&
!instance.getTagValue('Rows')
) {
return;
}
let displaySet;
if (isMultiFrame(instance)) {
displaySet = makeDisplaySet(series, [instance]);
displaySet.setAttributes({
sopClassUIDs,
isClip: true,
SeriesInstanceUID: series.getSeriesInstanceUID(),
StudyInstanceUID: study.getStudyInstanceUID(), // Include the study instance UID for drag/drop purposes
numImageFrames: instance.getTagValue('NumberOfFrames'), // Override the default value of instances.length
InstanceNumber: instance.getTagValue('InstanceNumber'), // Include the instance number
AcquisitionDatetime: instance.getTagValue('AcquisitionDateTime'), // Include the acquisition datetime
});
displaySets.push(displaySet);
} else if (isSingleImageModality(instance.Modality)) {
displaySet = makeDisplaySet(series, [instance]);
displaySet.setAttributes({
sopClassUIDs,
StudyInstanceUID: study.getStudyInstanceUID(), // Include the study instance UID
SeriesInstanceUID: series.getSeriesInstanceUID(),
InstanceNumber: instance.getTagValue('InstanceNumber'), // Include the instance number
AcquisitionDatetime: instance.getTagValue('AcquisitionDateTime'), // Include the acquisition datetime
});
displaySets.push(displaySet);
} else {
stackableInstances.push(instance);
}
});
if (stackableInstances.length) {
const displaySet = makeDisplaySet(series, stackableInstances);
displaySet.setAttribute('StudyInstanceUID', study.getStudyInstanceUID());
displaySet.setAttributes({
sopClassUIDs,
});
displaySets.push(displaySet);
}
return displaySets;
}
/**
* Adds the displaySets to the studies list of derived displaySets.
* @param {object} displaySet The displaySet to append to the derived displaysets list.
*/
_addDerivedDisplaySet(displaySet) {
this._derivedDisplaySets.push(displaySet);
// --> Perhaps that logic should exist in the extension sop class handler and this be a dumb list.
// TODO -> Get x Modality by referencedSeriesInstanceUid, FoR, etc.
}
/**
* Returns a list of derived datasets in the study, filtered by the given filter.
* @param {object} filter An object containing search filters
* @param {object} filter.Modality
* @param {object} filter.referencedSeriesInstanceUID
* @param {object} filter.referencedFrameOfReferenceUID
* @return {Array} filtered derived display sets
*/
getDerivedDatasets(filter) {
const {
Modality,
referencedSeriesInstanceUID,
referencedFrameOfReferenceUID,
} = filter;
let filteredDerivedDisplaySets = this._derivedDisplaySets;
if (Modality) {
filteredDerivedDisplaySets = filteredDerivedDisplaySets.filter(
displaySet => displaySet.Modality === Modality
);
}
if (referencedSeriesInstanceUID) {
filteredDerivedDisplaySets = filteredDerivedDisplaySets.filter(
displaySet => {
if (!displaySet.metadata.ReferencedSeriesSequence) {
return false;
}
const ReferencedSeriesSequence = Array.isArray(
displaySet.metadata.ReferencedSeriesSequence
)
? displaySet.metadata.ReferencedSeriesSequence
: [displaySet.metadata.ReferencedSeriesSequence];
return ReferencedSeriesSequence.some(
ReferencedSeries =>
ReferencedSeries.SeriesInstanceUID === referencedSeriesInstanceUID
);
}
);
}
if (referencedFrameOfReferenceUID) {
filteredDerivedDisplaySets = filteredDerivedDisplaySets.filter(
displaySet =>
displaySet.ReferencedFrameOfReferenceUID ===
ReferencedFrameOfReferenceUID
);
}
return filteredDerivedDisplaySets;
}
/**
* Creates a set of displaySets to be placed in the Study Metadata
* The displaySets that appear in the Study Metadata must represent
* imaging modalities. A series may be split into one or more displaySets.
*
* Furthermore, for drag/drop functionality,
* it is easiest if the stack objects also contain information about
* which study they are linked to.
*
* @param {StudyMetadata} study The study instance metadata to be used
* @returns {Array} An array of series to be placed in the Study Metadata
*/
createDisplaySets(sopClassHandlerModules) {
const displaySets = [];
const anyDisplaySets = this.getSeriesCount();
if (!anyDisplaySets) {
return displaySets;
}
// Loop through the series (SeriesMetadata)
this.forEachSeries(series => {
const displaySetsForSeries = this._createDisplaySetsForSeries(
sopClassHandlerModules,
series
);
displaySets.push(...displaySetsForSeries);
});
return sortDisplaySetList(displaySets);
}
sortDisplaySets() {
sortDisplaySetList(this._displaySets);
}
/**
* Method to append display sets from a given series to the internal list of display sets
* @param {Array} sopClassHandlerModules A list of SOP Class Handler Modules
* @param {SeriesMetadata} series The series metadata object from which the display sets will be created
* @returns {boolean} Returns true on success or false on failure (e.g., the series does not belong to this study)
*/
createAndAddDisplaySetsForSeries(sopClassHandlerModules, series) {
if (!this.containsSeries(series)) {
return false;
}
const displaySets = this._createDisplaySetsForSeries(
sopClassHandlerModules,
series
);
// Note: filtering in place because this._displaySets has writable: false
for (let i = this._displaySets.length - 1; i >= 0; i--) {
const displaySet = this._displaySets[i];
if (displaySet.SeriesInstanceUID === series.getSeriesInstanceUID()) {
this._displaySets.splice(i, 1);
}
}
displaySets.forEach(displaySet => {
this.addDisplaySet(displaySet);
});
this.sortDisplaySets();
return true;
}
/**
* Set display sets
* @param {Array} displaySets Array of display sets (ImageSet[])
*/
setDisplaySets(displaySets) {
if (Array.isArray(displaySets) && displaySets.length > 0) {
// TODO: This is weird, can we just switch it to writable: true?
this._displaySets.splice(0);
displaySets.forEach(displaySet => this.addDisplaySet(displaySet));
this.sortDisplaySets();
}
}
/**
* Add a single display set to the list
* @param {Object} displaySet Display set object
* @returns {boolean} True on success, false on failure.
*/
addDisplaySet(displaySet) {
if (displaySet instanceof ImageSet || displaySet.sopClassModule) {
this._displaySets.push(displaySet);
return true;
}
return false;
}
/**
* Invokes the supplied callback for each display set in the current study passing
* two arguments: display set (a ImageSet instance) and index (the integer
* index of the display set within the current study)
* @param {function} callback The callback function which will be invoked for each display set instance.
* @returns {undefined} Nothing is returned.
*/
forEachDisplaySet(callback) {
if (Metadata.isValidCallback(callback)) {
this._displaySets.forEach((displaySet, index) => {
callback.call(null, displaySet, index);
});
}
}
/**
* Search the associated display sets using the supplied callback as criteria. The callback is passed
* two arguments: display set (an ImageSet instance) and index (the integer
* index of the display set within the current study)
* @param {function} callback The callback function which will be invoked for each display set instance.
* @returns {undefined} Nothing is returned.
*/
findDisplaySet(callback) {
if (Metadata.isValidCallback(callback)) {
return this._displaySets.find((displaySet, index) => {
return callback.call(null, displaySet, index);
});
}
}
/**
* Retrieve the number of display sets within the current study.
* @returns {number} The number of display sets in the current study.
*/
getDisplaySetCount() {
return this._displaySets.length;
}
/**
* Returns the StudyInstanceUID of the current study.
*/
getStudyInstanceUID() {
return this._studyInstanceUID;
}
/**
* Getter for series
* @return {Array} Array of SeriesMetadata object
*/
getSeries() {
return this._series.slice();
}
/**
* Append a series to the current study.
* @param {SeriesMetadata} series The series to be added to the current study.
* @returns {boolean} Returns true on success, false otherwise.
*/
addSeries(series) {
let result = false;
if (
series instanceof SeriesMetadata &&
this.getSeriesByUID(series.getSeriesInstanceUID()) === void 0
) {
this._series.push(series);
result = true;
}
return result;
}
/**
* Update a series in the current study by SeriesInstanceUID.
* @param {String} SeriesInstanceUID The SeriesInstanceUID to be updated
* @param {SeriesMetadata} series The series to be added to the current study.
* @returns {boolean} Returns true on success, false otherwise.
*/
updateSeries(SeriesInstanceUID, series) {
const index = this._series.findIndex(series => {
return series.getSeriesInstanceUID() === SeriesInstanceUID;
});
if (index < 0) {
return false;
}
if (!(series instanceof SeriesMetadata)) {
throw new Error('Series must be an instance of SeriesMetadata');
}
this._series[index] = series;
return true;
}
/**
* Find a series by index.
* @param {number} index An integer representing a list index.
* @returns {SeriesMetadata} Returns a SeriesMetadata instance when found or undefined otherwise.
*/
getSeriesByIndex(index) {
let found; // undefined by default...
if (Metadata.isValidIndex(index)) {
found = this._series[index];
}
return found;
}
/**
* Find a series by SeriesInstanceUID.
* @param {string} uid An UID string.
* @returns {SeriesMetadata} Returns a SeriesMetadata instance when found or undefined otherwise.
*/
getSeriesByUID(uid) {
let found; // undefined by default...
if (Metadata.isValidUID(uid)) {
found = this._series.find(series => {
return series.getSeriesInstanceUID() === uid;
});
}
return found;
}
containsSeries(series) {
return (
series instanceof SeriesMetadata && this._series.indexOf(series) >= 0
);
}
/**
* Retrieve the number of series within the current study.
* @returns {number} The number of series in the current study.
*/
getSeriesCount() {
return this._series.length;
}
/**
* Retrieve the number of instances within the current study.
* @returns {number} The number of instances in the current study.
*/
getInstanceCount() {
return this._series.reduce((sum, series) => {
return sum + series.getInstanceCount();
}, 0);
}
/**
* Invokes the supplied callback for each series in the current study passing
* two arguments: series (a SeriesMetadata instance) and index (the integer
* index of the series within the current study)
* @param {function} callback The callback function which will be invoked for each series instance.
* @returns {undefined} Nothing is returned.
*/
forEachSeries(callback) {
if (Metadata.isValidCallback(callback)) {
this._series.forEach((series, index) => {
callback.call(null, series, index);
});
}
}
/**
* Find the index of a series inside the study.
* @param {SeriesMetadata} series An instance of the SeriesMetadata class.
* @returns {number} The index of the series inside the study or -1 if not found.
*/
indexOfSeries(series) {
return this._series.indexOf(series);
}
/**
* It sorts the series based on display sets order. Each series must be an instance
* of SeriesMetadata and each display sets must be an instance of ImageSet.
* Useful example of usage:
* Study data provided by backend does not sort series at all and client-side
* needs series sorted by the same criteria used for sorting display sets.
*/
sortSeriesByDisplaySets() {
// Object for mapping display sets' index by SeriesInstanceUID
const displaySetsMapping = {};
// Loop through each display set to create the mapping
this.forEachDisplaySet((displaySet, index) => {
if (!(displaySet instanceof ImageSet)) {
throw new OHIFError(
`StudyMetadata::sortSeriesByDisplaySets display set at index ${index} is not an instance of ImageSet`
);
}
// In case of multiframe studies, just get the first index occurence
if (displaySetsMapping[displaySet.SeriesInstanceUID] === void 0) {
displaySetsMapping[displaySet.SeriesInstanceUID] = index;
}
});
// Clone of actual series
const actualSeries = this.getSeries();
actualSeries.forEach((series, index) => {
if (!(series instanceof SeriesMetadata)) {
throw new OHIFError(
`StudyMetadata::sortSeriesByDisplaySets series at index ${index} is not an instance of SeriesMetadata`
);
}
// Get the new series index
const seriesIndex = displaySetsMapping[series.getSeriesInstanceUID()];
// Update the series object with the new series position
this._series[seriesIndex] = series;
});
}
/**
* Compares the current study instance with another one.
* @param {StudyMetadata} study An instance of the StudyMetadata class.
* @returns {boolean} Returns true if both instances refer to the same study.
*/
equals(study) {
const self = this;
return (
study === self ||
(study instanceof StudyMetadata &&
study.getStudyInstanceUID() === self.getStudyInstanceUID())
);
}
/**
* Get the first series of the current study retaining a consistent result across multiple calls.
* @return {SeriesMetadata} An instance of the SeriesMetadata class or null if it does not exist.
*/
getFirstSeries() {
let series = this._firstSeries;
if (!(series instanceof SeriesMetadata)) {
series = null;
const found = this.getSeriesByIndex(0);
if (found instanceof SeriesMetadata) {
this._firstSeries = found;
series = found;
}
}
return series;
}
/**
* Get the first image id given display instance uid.
* @return {string} The image id.
*/
getFirstImageId(displaySetInstanceUID) {
try {
const displaySet = this.findDisplaySet(
displaySet => displaySet.displaySetInstanceUID === displaySetInstanceUID
);
return displaySet.images[0].getImageId();
} catch (error) {
console.error('Failed to retrieve image metadata');
return null;
}
}
/**
* Get the first instance of the current study retaining a consistent result across multiple calls.
* @return {InstanceMetadata} An instance of the InstanceMetadata class or null if it does not exist.
*/
getFirstInstance() {
let instance = this._firstInstance;
if (!(instance instanceof InstanceMetadata)) {
instance = null;
const firstSeries = this.getFirstSeries();
if (firstSeries instanceof SeriesMetadata) {
const found = firstSeries.getFirstInstance();
if (found instanceof InstanceMetadata) {
this._firstInstance = found;
instance = found;
}
}
}
return instance;
}
/**
* Search the associated series to find an specific instance using the supplied callback as criteria.
* The callback is passed two arguments: instance (a InstanceMetadata instance) and index (the integer
* index of the instance within the current series)
* @param {function} callback The callback function which will be invoked for each instance instance.
* @returns {Object} Result object containing series (SeriesMetadata) and instance (InstanceMetadata)
* objects or an empty object if not found.
*/
findSeriesAndInstanceByInstance(callback) {
let result;
if (Metadata.isValidCallback(callback)) {
let instance;
const series = this._series.find(series => {
instance = series.findInstance(callback);
return instance instanceof InstanceMetadata;
});
// No series found
if (series instanceof SeriesMetadata) {
result = {
series,
instance,
};
}
}
return result || {};
}
/**
* Find series by instance using the supplied callback as criteria. The callback is passed
* two arguments: instance (a InstanceMetadata instance) and index (the integer index of
* the instance within its series)
* @param {function} callback The callback function which will be invoked for each instance.
* @returns {SeriesMetadata|undefined} If a series is found based on callback criteria it
* returns a SeriesMetadata. "undefined" is returned otherwise
*/
findSeriesByInstance(callback) {
const result = this.findSeriesAndInstanceByInstance(callback);
return result.series;
}
/**
* Find an instance using the supplied callback as criteria. The callback is passed
* two arguments: instance (a InstanceMetadata instance) and index (the integer index of
* the instance within its series)
* @param {function} callback The callback function which will be invoked for each instance.
* @returns {InstanceMetadata|undefined} If an instance is found based on callback criteria it
* returns a InstanceMetadata. "undefined" is returned otherwise
*/
findInstance(callback) {
const result = this.findSeriesAndInstanceByInstance(callback);
return result.instance;
}
}
/**
*
* @typedef StudyMetadata
* @property {function} getSeriesCount - returns the number of series in the study
* @property {function} forEachSeries - function that invokes callback with each series and index
* @property {function} getStudyInstanceUID - returns the study's instance UID
*
*/
/**
* @typedef SeriesMetadata
* @property {function} getSeriesInstanceUID - returns the series's instance UID
* @property {function} getData - ???
* @property {function} forEachInstance - ???
*/
const dwc = api.DICOMwebClient;
const isMultiFrame = instance => {
return instance.getTagValue('NumberOfFrames') > 1;
};
const makeDisplaySet = (series, instances) => {
const instance = instances[0];
const imageSet = new ImageSet(instances);
const seriesData = series.getData();
// set appropriate attributes to image set...
imageSet.setAttributes({
displaySetInstanceUID: imageSet.uid, // create a local alias for the imageSet UID
SeriesDate: seriesData.SeriesDate,
SeriesTime: seriesData.SeriesTime,
SeriesInstanceUID: series.getSeriesInstanceUID(),
SeriesNumber: instance.getTagValue('SeriesNumber'),
SeriesDescription: instance.getTagValue('SeriesDescription'),
numImageFrames: instances.length,
frameRate: instance.getTagValue('FrameTime'),
Modality: instance.getTagValue('Modality'),
isMultiFrame: isMultiFrame(instance),
});
// Sort the images in this series if needed
const shallSort = true; //!OHIF.utils.ObjectPath.get(Meteor, 'settings.public.ui.sortSeriesByIncomingOrder');
if (shallSort) {
imageSet.sortBy((a, b) => {
// Sort by InstanceNumber (0020,0013)
return (
(parseInt(a.getTagValue('InstanceNumber', 0)) || 0) -
(parseInt(b.getTagValue('InstanceNumber', 0)) || 0)
);
});
}
// Include the first image instance number (after sorted)
imageSet.setAttribute(
'InstanceNumber',
imageSet.getImage(0).getTagValue('InstanceNumber')
);
const isReconstructable = isDisplaySetReconstructable(instances);
imageSet.isReconstructable = isReconstructable.value;
if (shallSort && imageSet.isReconstructable) {
imageSet.sortByImagePositionPatient();
}
if (isReconstructable.missingFrames) {
// TODO -> This is currently unused, but may be used for reconstructing
// Volumes with gaps later on.
imageSet.missingFrames = isReconstructable.missingFrames;
}
return imageSet;
};
const isSingleImageModality = Modality => {
return Modality === 'CR' || Modality === 'MG' || Modality === 'DX';
};
function getSopClassUIDs(series) {
const uniqueSopClassUIDsInSeries = new Set();
series.forEachInstance(instance => {
const instanceSopClassUID = instance.getTagValue('SOPClassUID');
uniqueSopClassUIDsInSeries.add(instanceSopClassUID);
});
const sopClassUIDs = Array.from(uniqueSopClassUIDsInSeries);
return sopClassUIDs;
}
/**
* @private
* @param {SeriesMetadata} series
* @param {StudyMetadata} study
* @param {string[]} sopClassUIDs
*/
function _getDisplaySetFromSopClassModule(
sopClassHandlerExtensions, // TODO: Update Usage
series,
study,
sopClassUIDs
) {
// TODO: For now only use the plugins if all instances have the same SOPClassUID
if (sopClassUIDs.length !== 1) {
console.warn(
'getDisplaySetFromSopClassPlugin: More than one SOPClassUID in the same series is not yet supported.'
);
return;
}
const SOPClassUID = sopClassUIDs[0];
const sopClassHandlerModules = sopClassHandlerExtensions.map(extension => {
return extension.module;
});
const handlersForSopClassUID = sopClassHandlerModules.filter(module => {
return module.sopClassUIDs.includes(SOPClassUID);
});
// TODO: Sort by something, so we can determine which plugin to use
if (!handlersForSopClassUID || !handlersForSopClassUID.length) {
return;
}
const plugin = handlersForSopClassUID[0];
const headers = DICOMWeb.getAuthorizationHeader();
const errorInterceptor = errorHandler.getHTTPErrorHandler();
const dicomWebClient = new dwc({
url: study.getData().wadoRoot,
headers,
errorInterceptor,
});
let displaySet = plugin.getDisplaySetFromSeries(
series,
study,
dicomWebClient,
headers
);
if (displaySet && !displaySet.Modality) {
const instance = series.getFirstInstance();
displaySet.Modality = instance.getTagValue('Modality');
}
return displaySet;
}
/**
* Sort series primarily by Modality (i.e., series with references to other
* series like SEG, KO or PR are grouped in the end of the list) and then by
* series number:
*
* --------
* | CT #3 |
* | CT #4 |
* | CT #5 |
* --------
* | SEG #1 |
* | SEG #2 |
* --------
*
* @param {*} a - DisplaySet
* @param {*} b - DisplaySet
*/
function seriesSortingCriteria(a, b) {
const isLowPriorityA = isLowPriorityModality(a.Modality);
const isLowPriorityB = isLowPriorityModality(b.Modality);
if (!isLowPriorityA && isLowPriorityB) {
return -1;
}
if (isLowPriorityA && !isLowPriorityB) {
return 1;
}
return sortBySeriesNumber(a, b);
}
/**
* Sort series by series number. Series with low
* @param {*} a - DisplaySet
* @param {*} b - DisplaySet
*/
function sortBySeriesNumber(a, b) {
const seriesNumberAIsGreaterOrUndefined =
a.SeriesNumber > b.SeriesNumber || (!a.SeriesNumber && b.SeriesNumber);
return seriesNumberAIsGreaterOrUndefined ? 1 : -1;
}
/**
* Sorts a list of display set objects
* @param {Array} list A list of display sets to be sorted
*/
function sortDisplaySetList(list) {
return list.sort(seriesSortingCriteria);
}
@@ -1,29 +0,0 @@
import { InstanceMetadata } from './InstanceMetadata';
import { Metadata } from './Metadata';
import { OHIFInstanceMetadata } from './OHIFInstanceMetadata';
import { OHIFSeriesMetadata } from './OHIFSeriesMetadata';
import { OHIFStudyMetadata } from './OHIFStudyMetadata';
import { SeriesMetadata } from './SeriesMetadata';
import { StudyMetadata } from './StudyMetadata';
const metadata = {
Metadata,
StudyMetadata,
SeriesMetadata,
InstanceMetadata,
OHIFStudyMetadata,
OHIFSeriesMetadata,
OHIFInstanceMetadata,
};
export {
Metadata,
StudyMetadata,
SeriesMetadata,
InstanceMetadata,
OHIFStudyMetadata,
OHIFSeriesMetadata,
OHIFInstanceMetadata,
};
export default metadata;