Chore/kill yalc with fire (#629)
* init * more shifting * Move @babel dependencies up to workspace root * Begin updating dependent libraries to use sync'd webpack builds w/ watches * Commit changes before a long weekend * Split packages into platform and extensions * Consolidate how/where we specify file/module type entrypoints * Make it possible to pass in extensions as App props * Resolve viewer's modules * Target for UMD bundle * Add Webpack Stylus loader * Provide WebPack build options for microscopy, vtk, and ui * Better entrypoint for extensions * Push changes up to switch PCs * Fix ESM symlink build for Viewers * Shift docs to root * Specify additional lerna config props * Begin providing basic readme info * Rename example extension folder * Shift links to bottom of doc * First attempt at a netlify deploy preview * Attempt to fix deploy preview build * push workspace enabled to initial command; remove second yarn install; use npx to call gitbook cli commands * Try to use global gitbook-cli * Export node_modules path * More agressive with modifying PATH * Follow deploy log output advice * try again to set bin path * Try swapping bash with a new shell * Try bash -l instead of exec bash * Annd let's try again * and again * We may have figured it out johnny, boy * We need to pull cornerstone-wado-image-loader files from hoisted node_modules * Attempt to fix ticks/escapes * Change copy syntax; try running tests on viewers from root for circleci * Lower version to match circleci image * Try alternative jest-canvas-mock location and version file syntax * Run version command instead of calling node directly * Try alternative jest transform * Set path and enable workspaces * Add codecov flags * Use cpx so our copying finishes? * Get all platform unit tests to run * Run and report individually and in parallel * Try once relying on codecov yaml to split w/ flags * Add projects to split by flags * Generate separate reports * Trigger codecov after everything has finished running; these may not support flags * Use recommended flags from issue comments for codecov * Fix typo * Remove clear flag * Shift back to calling codecov from root * Generate example for codecov issue * Try fixing paths * Simplify * Try using codecov orb * Bump circleci version * Upload core and viewer * Use full string paths * Remove individual codecov calls * Fix dir * Combine files before upload * Escape anchors * tryfix syntax * Escape string literal * Combine lines to reduce path * long paths * Use home alias * Fix filename * Try to see the contents of our cat'd file * Also upload `core` * Try running with aliased folder * Fix path; split PR and Merge unit tests into separate jobs * Set default threshold * Fix typo * Changing to scoped package names * Adding note * Catch more updates * chore(release): publish %s [skip ci] - @ohif/extension-cornerstone@0.0.39-alpha.0 - @ohif/extension-dicom-html@0.0.4-alpha.0 - @ohif/extension-dicom-microscopy@0.0.9-alpha.0 - @ohif/extension-dicom-pdf@0.0.8-alpha.0 - @ohif/extension-vtk@0.1.4-alpha.0 - @ohif/core@0.11.1-alpha.0 - @ohif/i18n@0.2.3-alpha.0 - @ohif/ui@0.2.18-alpha.0 - @ohif/viewer@0.0.22-alpha.0 * Clean up primary readme * Support for dev and dev:* commands * Shift build command; satisfy default PWA build * Remove old scripts * Clean up UI to set webpack scripts * Tidy up project links * Clean duplicate code in UI project * Update UI project's docs * Clean up ui and i18n config * Reduce duplicate code in `@ohif/core` * Fix @ohif/ui versions * bump @ohif/core versions * Redux testkit dep * Remove unused/duplicate config files for projects/packages * ohif-core --> @ohif/core * Safer publish command * chore(release): publish %s [skip ci] - @ohif/extension-cornerstone@0.0.39-alpha.1 - @ohif/extension-dicom-html@0.0.4-alpha.1 - @ohif/extension-dicom-microscopy@0.0.9-alpha.1 - @ohif/extension-dicom-pdf@0.0.8-alpha.1 - @ohif/extension-vtk@0.1.4-alpha.1 - @ohif/core@0.11.1-alpha.1 - @ohif/i18n@0.2.3-alpha.1 - @ohif/ui@0.2.18-alpha.1 - @ohif/viewer@0.0.22-alpha.1 * test version bump * Add global prettier config * chore(release): publish %s [skip ci] - @ohif/viewer@0.0.22-alpha.2 * test lerna publish * Update package.jsons * Fix build scripts * catch changes * chore(release): publish %s [skip ci] - @ohif/extension-cornerstone@0.0.39-alpha.2 - @ohif/extension-dicom-html@0.0.4-alpha.2 - @ohif/extension-dicom-microscopy@0.0.9-alpha.2 - @ohif/extension-dicom-pdf@0.0.8-alpha.2 - @ohif/extension-vtk@0.1.4-alpha.2 - @ohif/core@0.11.1-alpha.2 - @ohif/i18n@0.2.3-alpha.2 - @ohif/ui@0.2.18-alpha.2 - @ohif/viewer@0.0.22-alpha.3 * fix eslint issues caused by eslint 6 and our react-app config * Publish with canary tag * chore(release): publish %s [skip ci] - @ohif/extension-cornerstone@0.0.39-alpha.3 - @ohif/extension-dicom-html@0.0.4-alpha.3 - @ohif/extension-dicom-microscopy@0.0.9-alpha.3 - @ohif/extension-dicom-pdf@0.0.8-alpha.3 - @ohif/extension-vtk@0.1.4-alpha.3 - @ohif/core@0.11.1-alpha.3 - @ohif/i18n@0.2.3-alpha.3 - @ohif/ui@0.2.18-alpha.3 - @ohif/viewer@0.0.22-alpha.4 * chore(release): publish %s [skip ci] - @ohif/extension-cornerstone@0.0.39-alpha.4 - @ohif/extension-dicom-html@0.0.4-alpha.4 - @ohif/extension-dicom-microscopy@0.0.9-alpha.4 - @ohif/extension-dicom-pdf@0.0.8-alpha.4 - @ohif/extension-vtk@0.1.4-alpha.4 - @ohif/core@0.11.1-alpha.4 - @ohif/i18n@0.2.3-alpha.4 - @ohif/ui@0.2.18-alpha.4 - @ohif/viewer@0.0.22-alpha.5 * Simplify build * chore(release): publish %s [skip ci] - @ohif/extension-cornerstone@0.0.39-alpha.5 - @ohif/extension-dicom-html@0.0.4-alpha.5 - @ohif/extension-dicom-microscopy@0.0.9-alpha.5 - @ohif/extension-dicom-pdf@0.0.8-alpha.5 - @ohif/extension-vtk@0.1.4-alpha.5 - @ohif/core@0.11.1-alpha.5 - @ohif/i18n@0.2.3-alpha.5 - @ohif/ui@0.2.18-alpha.5 - @ohif/viewer@0.0.22-alpha.6 * chore(release): publish %s [skip ci] - @ohif/extension-cornerstone@0.0.39-alpha.6 - @ohif/extension-dicom-html@0.0.4-alpha.6 - @ohif/extension-dicom-microscopy@0.0.9-alpha.6 - @ohif/extension-dicom-pdf@0.0.8-alpha.6 - @ohif/extension-vtk@0.1.4-alpha.6 - @ohif/core@0.11.1-alpha.6 - @ohif/i18n@0.2.3-alpha.6 - @ohif/ui@0.2.18-alpha.6 - @ohif/viewer@0.0.22-alpha.7 * Split version and publish * chore(release): publish %s [skip ci] - @ohif/extension-cornerstone@0.0.39-alpha.7 - @ohif/extension-dicom-html@0.0.4-alpha.7 - @ohif/extension-dicom-microscopy@0.0.9-alpha.7 - @ohif/extension-dicom-pdf@0.0.8-alpha.7 - @ohif/extension-vtk@0.1.4-alpha.7 - @ohif/core@0.11.1-alpha.7 - @ohif/i18n@0.2.3-alpha.7 - @ohif/ui@0.2.18-alpha.7 - @ohif/viewer@0.0.22-alpha.8 * Try simplify netlify build * react-viewerbase --> @ohif/ui * add test for stylus loader * Try new way to specify publish path * Use an output folder that won't be ignored * Try move command * fiddle with paths * Dig for some information * Make sure we're in root for our commands * Remove discovery * Setup script-tag example * Fix typo * Move config folder * Update cornerstone extension to use shared/root webpack configs * capture changes * Update extension webpack configs * Don't check in docz output * Fix babel runtime resolution issue * Simplify ui build steps * Push in progress * Shift directories * Get viewer dev path to work * Fix viewer commonjs build * Fix build pwa config for viewers * Make sure our package specific command can be called from root * Update notes * Fix imports and misc. merge notes * Bump wado-image-loader version * Switch up commands to remove webworkers copy * Fix CI config * Fix more broken package references * Add react-dropzone * Persist so e2e test can use * Fix lockfile * Use cypress orb to simplify CI * Fix config * Try again * Install yarn latest for orb * Install yarn a different way * Wait on correct port * Run tests in viewer project * Fix cypress config * Make Cypress happier - use default location * Simplify e2e testing * Capture UI changes since fork * Catch core up * Grab latest deps after merge * Fix broken import * Make sure cornerstone-wado-image-loader resolves to 3+ * Note regarding orbs * Fix refresh on 404 routes * Fix odd error for cornerstone-wado-image-loader * Different target for UMD * Simplify dev script * Try to get fancy with netlify output * Let's do it again * Try to fix measurementTools issue * See if we can get our lerna magic to work on merge to monorepo branch
This commit is contained in:
1 parent
cac911f08e
commit
08ff214ea6
919 files changed
+45652
-52097
No files matched your search
@@ -0,0 +1,1000 @@
|
||||
import cornerstoneTools from 'cornerstone-tools';
|
||||
import log from '../../log';
|
||||
import getLabel from '../lib/getLabel';
|
||||
import getDescription from '../lib/getDescription';
|
||||
import getImageIdForImagePath from '../lib/getImageIdForImagePath';
|
||||
import guid from '../../utils/guid';
|
||||
import studyMetadataManager from '../../utils/studyMetadataManager';
|
||||
|
||||
const configuration = {
|
||||
measurementTools: [],
|
||||
};
|
||||
|
||||
export default class MeasurementApi {
|
||||
static Instance;
|
||||
|
||||
static setConfiguration(config) {
|
||||
Object.assign(configuration, config);
|
||||
}
|
||||
|
||||
static getConfiguration() {
|
||||
return configuration;
|
||||
}
|
||||
|
||||
static getToolsGroupsMap() {
|
||||
const toolsGroupsMap = {};
|
||||
configuration.measurementTools.forEach(toolGroup => {
|
||||
toolGroup.childTools.forEach(
|
||||
tool => (toolsGroupsMap[tool.id] = toolGroup.id)
|
||||
);
|
||||
});
|
||||
|
||||
return toolsGroupsMap;
|
||||
}
|
||||
|
||||
static getToolGroupTools(toolsGroupsMap) {
|
||||
const result = {};
|
||||
Object.keys(toolsGroupsMap).forEach(toolType => {
|
||||
const toolGroupId = toolsGroupsMap[toolType];
|
||||
if (!result[toolGroupId]) {
|
||||
result[toolGroupId] = [];
|
||||
}
|
||||
|
||||
result[toolGroupId].push(toolType);
|
||||
});
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
static getToolConfiguration(toolType) {
|
||||
const configuration = MeasurementApi.getConfiguration();
|
||||
const toolsGroupsMap = MeasurementApi.getToolsGroupsMap();
|
||||
|
||||
const toolGroupId = toolsGroupsMap[toolType];
|
||||
const toolGroup = configuration.measurementTools.find(
|
||||
toolGroup => toolGroup.id === toolGroupId
|
||||
);
|
||||
|
||||
let tool;
|
||||
if (toolGroup) {
|
||||
tool = toolGroup.childTools.find(tool => tool.id === toolType);
|
||||
}
|
||||
|
||||
return {
|
||||
toolGroupId,
|
||||
toolGroup,
|
||||
tool,
|
||||
};
|
||||
}
|
||||
|
||||
static syncMeasurementAndToolData(measurement) {
|
||||
log.info('syncMeasurementAndToolData');
|
||||
|
||||
const measurementLabel = getLabel(measurement);
|
||||
if (measurementLabel) {
|
||||
measurement.labels = [measurementLabel];
|
||||
}
|
||||
|
||||
const toolState = cornerstoneTools.globalImageIdSpecificToolStateManager.saveToolState();
|
||||
|
||||
// Stop here if the metadata for the measurement's study is not loaded yet
|
||||
const { studyInstanceUid } = measurement;
|
||||
const metadata = studyMetadataManager.get(studyInstanceUid);
|
||||
if (!metadata) return;
|
||||
|
||||
// Iterate each child tool if the current tool has children
|
||||
const toolType = measurement.toolType;
|
||||
const { tool } = MeasurementApi.getToolConfiguration(toolType);
|
||||
if (Array.isArray(tool.childTools)) {
|
||||
tool.childTools.forEach(childToolKey => {
|
||||
const childMeasurement = measurement[childToolKey];
|
||||
if (!childMeasurement) return;
|
||||
childMeasurement._id = measurement._id;
|
||||
childMeasurement.measurementNumber = measurement.measurementNumber;
|
||||
childMeasurement.lesionNamingNumber = measurement.lesionNamingNumber;
|
||||
|
||||
MeasurementApi.syncMeasurementAndToolData(childMeasurement);
|
||||
});
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
const imageId = getImageIdForImagePath(measurement.imagePath);
|
||||
|
||||
// If no tool state exists for this imageId, create an empty object to store it
|
||||
if (!toolState[imageId]) {
|
||||
toolState[imageId] = {};
|
||||
}
|
||||
|
||||
const currentToolState = toolState[imageId][toolType];
|
||||
const toolData = currentToolState && currentToolState.data;
|
||||
|
||||
// Check if we already have toolData for this imageId and toolType
|
||||
if (toolData && toolData.length) {
|
||||
// If we have toolData, we should search it for any data related to the current Measurement
|
||||
const toolData = toolState[imageId][toolType].data;
|
||||
|
||||
// Create a flag so we know if we've successfully updated the Measurement in the toolData
|
||||
let alreadyExists = false;
|
||||
|
||||
// Loop through the toolData to search for this Measurement
|
||||
toolData.forEach(tool => {
|
||||
// Break the loop if this isn't the Measurement we are looking for
|
||||
if (tool._id !== measurement._id) {
|
||||
return;
|
||||
}
|
||||
|
||||
// If we have found the Measurement, set the flag to True
|
||||
alreadyExists = true;
|
||||
|
||||
// Update the toolData from the Measurement data
|
||||
Object.assign(tool, measurement);
|
||||
return false;
|
||||
});
|
||||
|
||||
// If we have found the Measurement we intended to update, we can stop this function here
|
||||
if (alreadyExists === true) {
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
// If no toolData exists for this toolType, create an empty array to hold some
|
||||
toolState[imageId][toolType] = {
|
||||
data: [],
|
||||
};
|
||||
}
|
||||
|
||||
// If we have reached this point, it means we haven't found the Measurement we are looking for
|
||||
// in the current toolData. This means we need to add it.
|
||||
|
||||
// Add the MeasurementData into the toolData for this imageId
|
||||
toolState[imageId][toolType].data.push(measurement);
|
||||
|
||||
cornerstoneTools.globalImageIdSpecificToolStateManager.restoreToolState(
|
||||
toolState
|
||||
);
|
||||
}
|
||||
|
||||
static isToolIncluded(tool) {
|
||||
return (
|
||||
tool.options &&
|
||||
tool.options.caseProgress &&
|
||||
tool.options.caseProgress.include
|
||||
);
|
||||
}
|
||||
|
||||
constructor(timepointApi, options = {}) {
|
||||
if (MeasurementApi.Instance) {
|
||||
MeasurementApi.Instance.initialize(timepointApi, options);
|
||||
return MeasurementApi.Instance;
|
||||
}
|
||||
|
||||
this.initialize(timepointApi, options);
|
||||
MeasurementApi.Instance = this;
|
||||
}
|
||||
|
||||
initialize(timepointApi, options = {}) {
|
||||
this.timepointApi = timepointApi;
|
||||
this.options = options;
|
||||
this.toolGroups = {};
|
||||
this.tools = {};
|
||||
this.toolsGroupsMap = MeasurementApi.getToolsGroupsMap();
|
||||
this.toolGroupTools = MeasurementApi.getToolGroupTools(this.toolsGroupsMap);
|
||||
|
||||
// Iterate over each tool group and create collection
|
||||
configuration.measurementTools.forEach(toolGroup => {
|
||||
this.toolGroups[toolGroup.id] = [];
|
||||
|
||||
// Iterate over each tool group child tools (e.g. bidirectional, targetCR, etc.) and create collection
|
||||
toolGroup.childTools.forEach(tool => {
|
||||
this.tools[tool.id] = [];
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
onMeasurementsUpdated() {
|
||||
if (typeof this.options.onMeasurementsUpdated !== 'function') {
|
||||
log.warn('Measurements update callback is not defined');
|
||||
return;
|
||||
}
|
||||
|
||||
this.options.onMeasurementsUpdated(Object.assign({}, this.tools));
|
||||
}
|
||||
|
||||
retrieveMeasurements(patientId, timepointIds) {
|
||||
const retrievalFn = configuration.dataExchange.retrieve;
|
||||
if (typeof retrievalFn !== 'function') {
|
||||
log.error('Measurement retrieval function has not been configured.');
|
||||
return;
|
||||
}
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
retrievalFn(patientId, timepointIds).then(measurementData => {
|
||||
if (measurementData) {
|
||||
log.info('Measurement data retrieval');
|
||||
log.info(measurementData);
|
||||
|
||||
Object.keys(measurementData).forEach(measurementTypeId => {
|
||||
const measurements = measurementData[measurementTypeId];
|
||||
|
||||
measurements.forEach(measurement => {
|
||||
const { toolType } = measurement;
|
||||
|
||||
this.addMeasurement(toolType, measurement);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
resolve();
|
||||
|
||||
// Synchronize the new tool data
|
||||
this.syncMeasurementsAndToolData();
|
||||
|
||||
// Let others know that the measurements are updated
|
||||
this.onMeasurementsUpdated();
|
||||
}, reject);
|
||||
});
|
||||
}
|
||||
|
||||
storeMeasurements(timepointId) {
|
||||
const storeFn = configuration.dataExchange.store;
|
||||
if (typeof storeFn !== 'function') {
|
||||
log.error('Measurement store function has not been configured.');
|
||||
return;
|
||||
}
|
||||
|
||||
let measurementData = {};
|
||||
configuration.measurementTools.forEach(toolGroup => {
|
||||
// Skip the tool groups excluded from case progress
|
||||
if (!MeasurementApi.isToolIncluded(toolGroup)) {
|
||||
return;
|
||||
}
|
||||
|
||||
toolGroup.childTools.forEach(tool => {
|
||||
// Skip the tools excluded from case progress
|
||||
if (!MeasurementApi.isToolIncluded(tool)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!measurementData[toolGroup.id]) {
|
||||
measurementData[toolGroup.id] = [];
|
||||
}
|
||||
|
||||
measurementData[toolGroup.id] = measurementData[toolGroup.id].concat(
|
||||
this.tools[tool.id]
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
const timepointFilter = timepointId
|
||||
? tp => tp.timepointId === timepointId
|
||||
: null;
|
||||
const timepoints = this.timepointApi.all(timepointFilter);
|
||||
const timepointIds = timepoints.map(t => t.timepointId);
|
||||
const patientId = timepoints[0].patientId;
|
||||
const filter = {
|
||||
patientId,
|
||||
timepointIds,
|
||||
};
|
||||
|
||||
log.info('Saving Measurements for timepoints:', timepoints);
|
||||
return storeFn(measurementData, filter).then(() => {
|
||||
log.info('Measurement storage completed');
|
||||
});
|
||||
}
|
||||
|
||||
calculateLesionNamingNumber(measurements) {
|
||||
const sortedMeasurements = measurements.sort((a, b) => {
|
||||
if (a.lesionNamingNumber > b.lesionNamingNumber) {
|
||||
return 1;
|
||||
} else if (a.lesionNamingNumber < b.lesionNamingNumber) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
return 0;
|
||||
});
|
||||
|
||||
// Calculate lesion naming number starting from 1 not to miss any measurement (as seen in MM)
|
||||
// A measurement from beginning of the list might be deleted, so a new measurement should replace that
|
||||
let i;
|
||||
for (i = 1; i < sortedMeasurements.length + 1; i++) {
|
||||
if (i < sortedMeasurements[i - 1].lesionNamingNumber) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return i;
|
||||
}
|
||||
|
||||
fetch(toolGroupId, filter) {
|
||||
if (!this.toolGroups[toolGroupId]) {
|
||||
throw new Error(
|
||||
`MeasurementApi: No Collection with the id: ${toolGroupId}`
|
||||
);
|
||||
}
|
||||
|
||||
let items;
|
||||
if (filter) {
|
||||
items = this.toolGroups[toolGroupId].filter(filter);
|
||||
} else {
|
||||
items = this.toolGroups[toolGroupId];
|
||||
}
|
||||
|
||||
return items.map(item => {
|
||||
if (item.toolId) {
|
||||
return this.tools[item.toolId].find(
|
||||
tool => tool._id === item.toolItemId
|
||||
);
|
||||
}
|
||||
|
||||
return { lesionNamingNumber: item.lesionNamingNumber };
|
||||
});
|
||||
}
|
||||
|
||||
getFirstMeasurement(timepointId) {
|
||||
// Get child tools from all included tool groups
|
||||
let childTools = [];
|
||||
configuration.measurementTools.forEach(toolGroup => {
|
||||
// Skip the tool groups excluded from case progress
|
||||
if (!MeasurementApi.isToolIncluded(toolGroup)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
childTools = childTools.concat(toolGroup.childTools);
|
||||
});
|
||||
|
||||
// Get all included child tools
|
||||
const includedChildTools = childTools.filter(tool =>
|
||||
MeasurementApi.isToolIncluded(tool)
|
||||
);
|
||||
|
||||
// Get the first measurement for the given timepoint
|
||||
let measurement = undefined;
|
||||
includedChildTools.every(tool => {
|
||||
measurement = this.tools[tool.id].find(
|
||||
t => t.timepointId === timepointId && t.measurementNumber === 1
|
||||
);
|
||||
|
||||
return !measurement;
|
||||
});
|
||||
|
||||
// Return the found measurement object or undefined if not found
|
||||
return measurement;
|
||||
}
|
||||
|
||||
lesionExistsAtTimepoints(lesionNamingNumber, toolGroupId, timepointIds) {
|
||||
// Retrieve all the data for the given tool group (e.g. 'targets')
|
||||
const measurementsAtTimepoint = this.fetch(toolGroupId, tool =>
|
||||
timepointIds.includes(tool.timepointId)
|
||||
);
|
||||
|
||||
// Return whether or not any lesion at this timepoint has the same lesionNamingNumber
|
||||
return !!measurementsAtTimepoint.find(
|
||||
m => m.lesionNamingNumber === lesionNamingNumber
|
||||
);
|
||||
}
|
||||
|
||||
isNewLesionsMeasurement(measurementData) {
|
||||
if (!measurementData) {
|
||||
return;
|
||||
}
|
||||
|
||||
const toolConfig = MeasurementApi.getToolConfiguration(
|
||||
measurementData.toolType
|
||||
);
|
||||
const toolType = toolConfig.tool.parentTool || measurementData.toolType;
|
||||
const { timepointApi } = this;
|
||||
const currentMeasurement =
|
||||
this.tools[toolType].find(tool => tool._id === measurementData._id) || {};
|
||||
const timepointId =
|
||||
currentMeasurement.timepointId || measurementData.timepointId;
|
||||
const lesionNamingNumber =
|
||||
currentMeasurement.lesionNamingNumber ||
|
||||
measurementData.lesionNamingNumber;
|
||||
|
||||
// Stop here if the needed information is not set
|
||||
if (!timepointApi || !timepointId || !toolConfig) {
|
||||
return;
|
||||
}
|
||||
|
||||
const { toolGroupId } = toolConfig;
|
||||
const current = timepointApi.timepoints.find(
|
||||
tp => tp.timepointId === timepointId
|
||||
);
|
||||
const initialTimepointIds = timepointApi.initialTimepointIds();
|
||||
|
||||
// Stop here if there's no initial timepoint, or if the current is any initial
|
||||
if (
|
||||
!initialTimepointIds ||
|
||||
initialTimepointIds.length < 1 ||
|
||||
initialTimepointIds.some(
|
||||
initialtpid => initialtpid === current.timepointId
|
||||
)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return (
|
||||
this.lesionExistsAtTimepoints(
|
||||
lesionNamingNumber,
|
||||
toolGroupId,
|
||||
initialTimepointIds
|
||||
) === false
|
||||
);
|
||||
}
|
||||
|
||||
calculateLesionMaxMeasurementNumber(groupId, filter) {
|
||||
let measurements = [];
|
||||
if (groupId) {
|
||||
// Get the measurements of the group
|
||||
measurements = this.toolGroups[groupId] || [];
|
||||
} else {
|
||||
// Get all measurements of all groups
|
||||
measurements = Object.keys(this.toolGroups).reduce((acc, val) => {
|
||||
acc.push(...this.toolGroups[val]);
|
||||
return acc;
|
||||
}, []);
|
||||
}
|
||||
|
||||
const sortedMeasurements = measurements.filter(filter).sort((tp1, tp2) => {
|
||||
return tp1.measurementNumber < tp2.measurementNumber ? 1 : -1;
|
||||
});
|
||||
|
||||
for (let i = 0; i < sortedMeasurements.length; i++) {
|
||||
const toolGroupMeasurement = sortedMeasurements[i];
|
||||
const measurement = this.tools[toolGroupMeasurement.toolId].find(
|
||||
tool => tool._id === toolGroupMeasurement.toolItemId
|
||||
);
|
||||
const isNew = this.isNewLesionsMeasurement(measurement);
|
||||
if (!isNew) {
|
||||
return measurement.measurementNumber;
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
calculateNewLesionMaxMeasurementNumber(groupId, filter) {
|
||||
const sortedMeasurements = this.toolGroups[groupId]
|
||||
.filter(filter)
|
||||
.sort((tp1, tp2) => {
|
||||
return tp1.measurementNumber < tp2.measurementNumber ? 1 : -1;
|
||||
});
|
||||
|
||||
for (let i = 0; i < sortedMeasurements.length; i++) {
|
||||
const toolGroupMeasurement = sortedMeasurements[i];
|
||||
const measurement = this.tools[toolGroupMeasurement.toolId].find(
|
||||
tool => tool._id === toolGroupMeasurement.toolItemId
|
||||
);
|
||||
const isNew = this.isNewLesionsMeasurement(measurement);
|
||||
if (isNew) {
|
||||
return measurement.measurementNumber;
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
calculateMeasurementNumber(measurement) {
|
||||
const toolGroupId = this.toolsGroupsMap[measurement.toolType];
|
||||
|
||||
const filter = tool => tool._id !== measurement._id;
|
||||
|
||||
const isNew = this.isNewLesionsMeasurement(measurement);
|
||||
|
||||
if (isNew) {
|
||||
const maxTargetMeasurementNumber = this.calculateLesionMaxMeasurementNumber(
|
||||
'targets',
|
||||
filter
|
||||
);
|
||||
const maxNonTargetMeasurementNumber = this.calculateLesionMaxMeasurementNumber(
|
||||
'nonTargets',
|
||||
filter
|
||||
);
|
||||
const maxNewTargetMeasurementNumber = this.calculateNewLesionMaxMeasurementNumber(
|
||||
'targets',
|
||||
filter
|
||||
);
|
||||
if (toolGroupId === 'targets') {
|
||||
return Math.max(
|
||||
maxTargetMeasurementNumber,
|
||||
maxNonTargetMeasurementNumber,
|
||||
maxNewTargetMeasurementNumber
|
||||
);
|
||||
} else if (toolGroupId === 'nonTargets') {
|
||||
const maxNewNonTargetMeasurementNumber = this.calculateNewLesionMaxMeasurementNumber(
|
||||
'nonTargets',
|
||||
filter
|
||||
);
|
||||
return Math.max(
|
||||
maxTargetMeasurementNumber,
|
||||
maxNonTargetMeasurementNumber,
|
||||
maxNewTargetMeasurementNumber,
|
||||
maxNewNonTargetMeasurementNumber
|
||||
);
|
||||
}
|
||||
} else {
|
||||
const maxTargetMeasurementNumber = this.calculateLesionMaxMeasurementNumber(
|
||||
'targets',
|
||||
filter
|
||||
);
|
||||
if (toolGroupId === 'targets') {
|
||||
return maxTargetMeasurementNumber;
|
||||
} else if (toolGroupId === 'nonTargets') {
|
||||
const maxNonTargetMeasurementNumber = this.calculateLesionMaxMeasurementNumber(
|
||||
'nonTargets',
|
||||
filter
|
||||
);
|
||||
return Math.max(
|
||||
maxTargetMeasurementNumber,
|
||||
maxNonTargetMeasurementNumber
|
||||
);
|
||||
} else {
|
||||
return this.calculateLesionMaxMeasurementNumber(null, filter);
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
getPreviousMeasurement(measurementData) {
|
||||
if (!measurementData) {
|
||||
return;
|
||||
}
|
||||
|
||||
const { timepointId, toolType, lesionNamingNumber } = measurementData;
|
||||
if (!timepointId || !toolType || !lesionNamingNumber) {
|
||||
return;
|
||||
}
|
||||
|
||||
const toolGroupId = this.toolsGroupsMap[measurementData.toolType];
|
||||
|
||||
// TODO: Remove TrialPatientLocationUid from here and override it somehow
|
||||
// by dependant applications. Here we should use the location attribute instead of the uid
|
||||
let filter;
|
||||
const uid =
|
||||
measurementData.additionalData &&
|
||||
measurementData.additionalData.TrialPatientLocationUid;
|
||||
if (uid) {
|
||||
filter = tool =>
|
||||
tool._id !== measurementData._id &&
|
||||
tool.additionalData &&
|
||||
tool.additionalData.TrialPatientLocationUid === uid;
|
||||
} else {
|
||||
filter = tool =>
|
||||
tool._id !== measurementData._id &&
|
||||
tool.lesionNamingNumber === lesionNamingNumber;
|
||||
}
|
||||
|
||||
const childToolTypes = this.toolGroupTools[toolGroupId];
|
||||
for (let i = 0; i < childToolTypes.length; i++) {
|
||||
const childToolType = childToolTypes[i];
|
||||
const toolCollection = this.tools[childToolType];
|
||||
const item = toolCollection.find(filter);
|
||||
|
||||
if (item) {
|
||||
return item;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
hasDuplicateMeasurementNumber(measurementData) {
|
||||
if (!measurementData) {
|
||||
return;
|
||||
}
|
||||
|
||||
const { toolType, measurementNumber } = measurementData;
|
||||
if (!toolType || !measurementNumber) {
|
||||
return;
|
||||
}
|
||||
|
||||
const filter = tool =>
|
||||
tool._id !== measurementData._id &&
|
||||
tool.measurementNumber === measurementData.measurementNumber;
|
||||
|
||||
return configuration.measurementTools
|
||||
.filter(toolGroup => toolGroup.id !== 'temp')
|
||||
.some(toolGroup => {
|
||||
if (this.toolGroups[toolGroup.id].find(filter)) {
|
||||
return true;
|
||||
}
|
||||
return toolGroup.childTools.some(tool => {
|
||||
if (this.tools[tool.id].find(filter)) {
|
||||
return true;
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
updateNumbering(collectionToUpdate, propertyFilter, propertyName, increment) {
|
||||
collectionToUpdate.filter(propertyFilter).forEach(item => {
|
||||
item[propertyName] += increment;
|
||||
});
|
||||
}
|
||||
|
||||
updateMeasurementNumberForAllMeasurements(measurement, increment) {
|
||||
const filter = tool =>
|
||||
tool._id !== measurement._id &&
|
||||
tool.measurementNumber >= measurement.measurementNumber;
|
||||
|
||||
configuration.measurementTools
|
||||
.filter(toolGroup => toolGroup.id !== 'temp')
|
||||
.forEach(toolGroup => {
|
||||
this.updateNumbering(
|
||||
this.toolGroups[toolGroup.id],
|
||||
filter,
|
||||
'measurementNumber',
|
||||
increment
|
||||
);
|
||||
|
||||
toolGroup.childTools.forEach(tool => {
|
||||
this.updateNumbering(
|
||||
this.tools[tool.id],
|
||||
filter,
|
||||
'measurementNumber',
|
||||
increment
|
||||
);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
addMeasurement(toolType, measurement) {
|
||||
const toolGroup = this.toolsGroupsMap[toolType];
|
||||
const groupCollection = this.toolGroups[toolGroup];
|
||||
const collection = this.tools[toolType];
|
||||
|
||||
// Get the related measurement by the measurement number and use its location if defined
|
||||
const relatedMeasurement = collection.find(
|
||||
t =>
|
||||
t.lesionNamingNumber === measurement.lesionNamingNumber &&
|
||||
t.toolType === measurement.toolType
|
||||
);
|
||||
|
||||
// Use the related measurement location if found and defined
|
||||
if (relatedMeasurement && relatedMeasurement.location) {
|
||||
measurement.location = relatedMeasurement.location;
|
||||
}
|
||||
|
||||
// Use the related measurement description if found and defined
|
||||
if (relatedMeasurement && relatedMeasurement.description) {
|
||||
measurement.description = relatedMeasurement.description;
|
||||
}
|
||||
|
||||
measurement._id = guid();
|
||||
|
||||
// Get the timepoint
|
||||
let timepoint;
|
||||
if (measurement.studyInstanceUid) {
|
||||
timepoint = this.timepointApi.study(measurement.studyInstanceUid)[0];
|
||||
} else {
|
||||
const { timepointId } = measurement;
|
||||
timepoint = this.timepointApi.timepoints.find(
|
||||
t => t.timepointId === timepointId
|
||||
);
|
||||
}
|
||||
|
||||
// Preventing errors thrown when non-associated (standalone) study is opened...
|
||||
// @TODO: Make sure this logic is correct.
|
||||
if (!timepoint) return;
|
||||
|
||||
// Empty Item is the lesion just added in cornerstoneTools, but does not have measurement data yet
|
||||
const emptyItem = groupCollection.find(
|
||||
groupTool =>
|
||||
!groupTool.toolId && groupTool.timepointId === timepoint.timepointId
|
||||
);
|
||||
|
||||
// Set the timepointId attribute to measurement to make it easier to filter measurements by timepoint
|
||||
measurement.timepointId = timepoint.timepointId;
|
||||
|
||||
// Check if the measurement data is just added by a cornerstone tool and is still empty
|
||||
if (emptyItem) {
|
||||
// Set relevant initial data and measurement number to the measurement
|
||||
measurement.lesionNamingNumber = emptyItem.lesionNamingNumber;
|
||||
measurement.measurementNumber = emptyItem.measurementNumber;
|
||||
|
||||
groupCollection
|
||||
.filter(
|
||||
groupTool =>
|
||||
groupTool.timepointId === timepoint.timepointId &&
|
||||
groupTool.lesionNamingNumber === measurement.lesionNamingNumber
|
||||
)
|
||||
.forEach(groupTool => {
|
||||
groupTool.toolId = tool.id;
|
||||
groupTool.toolItemId = measurement._id;
|
||||
groupTool.createdAt = measurement.createdAt;
|
||||
groupTool.measurementNumber = measurement.measurementNumber;
|
||||
});
|
||||
} else {
|
||||
// Handle measurements not added by cornerstone tools and update its number
|
||||
const measurementsInTimepoint = groupCollection.filter(
|
||||
groupTool => groupTool.timepointId === timepoint.timepointId
|
||||
);
|
||||
measurement.lesionNamingNumber = this.calculateLesionNamingNumber(
|
||||
measurementsInTimepoint
|
||||
);
|
||||
measurement.measurementNumber =
|
||||
measurement.measurementNumber ||
|
||||
this.calculateMeasurementNumber(measurement) + 1;
|
||||
}
|
||||
|
||||
// Define an update object to reflect the changes in the collection
|
||||
const updateObject = {
|
||||
timepointId: timepoint.timepointId,
|
||||
lesionNamingNumber: measurement.lesionNamingNumber,
|
||||
measurementNumber: measurement.measurementNumber,
|
||||
};
|
||||
|
||||
// Find the matched measurement from other timepoints
|
||||
const found = this.getPreviousMeasurement(measurement);
|
||||
|
||||
// Check if a previous related meausurement was found on other timepoints
|
||||
if (found) {
|
||||
// Use the same number as the previous measurement
|
||||
measurement.lesionNamingNumber = found.lesionNamingNumber;
|
||||
measurement.measurementNumber = found.measurementNumber;
|
||||
|
||||
// TODO: Remove TrialPatientLocationUid from here and override it somehow
|
||||
// by dependant applications
|
||||
|
||||
// Change the update object to set the same number, additionalData,
|
||||
// location, label and description to the current measurement
|
||||
updateObject.lesionNamingNumber = found.lesionNamingNumber;
|
||||
updateObject.measurementNumber = found.measurementNumber;
|
||||
updateObject.additionalData = measurement.additionalData || {};
|
||||
updateObject.additionalData.TrialPatientLocationUid =
|
||||
found.additionalData && found.additionalData.TrialPatientLocationUid;
|
||||
updateObject.location = found.location;
|
||||
updateObject.label = found.label;
|
||||
updateObject.description = found.description;
|
||||
updateObject.isSplitLesion = found.isSplitLesion;
|
||||
updateObject.isNodal = found.isNodal;
|
||||
|
||||
const description = getDescription(found, measurement);
|
||||
if (description) {
|
||||
updateObject.description = description;
|
||||
}
|
||||
} else if (this.hasDuplicateMeasurementNumber(measurement)) {
|
||||
// Update measurementNumber for the measurements with masurementNumber greater or equal than
|
||||
// measurementNumber of the added measurement (except the added one)
|
||||
// only if there is another measurement with the same measurementNumber
|
||||
this.updateMeasurementNumberForAllMeasurements(measurement, 1);
|
||||
}
|
||||
|
||||
let addedMeasurement;
|
||||
|
||||
// Upsert the measurement in collection
|
||||
const toolIndex = collection.findIndex(
|
||||
tool => tool._id === measurement._id
|
||||
);
|
||||
if (toolIndex > -1) {
|
||||
addedMeasurement = Object.assign({}, collection[toolIndex], updateObject);
|
||||
collection[toolIndex] = addedMeasurement;
|
||||
} else {
|
||||
addedMeasurement = Object.assign({}, measurement, updateObject);
|
||||
collection.push(addedMeasurement);
|
||||
}
|
||||
|
||||
if (!emptyItem) {
|
||||
// Reflect the entry in the tool group collection
|
||||
groupCollection.push({
|
||||
toolId: toolType,
|
||||
toolItemId: addedMeasurement._id,
|
||||
timepointId: timepoint.timepointId,
|
||||
studyInstanceUid: addedMeasurement.studyInstanceUid,
|
||||
createdAt: addedMeasurement.createdAt,
|
||||
lesionNamingNumber: addedMeasurement.lesionNamingNumber,
|
||||
measurementNumber: addedMeasurement.measurementNumber,
|
||||
});
|
||||
}
|
||||
|
||||
// Let others know that the measurements are updated
|
||||
this.onMeasurementsUpdated();
|
||||
|
||||
// TODO: Enable reactivity
|
||||
// this.timepointChanged.set(timepoint.timepointId);
|
||||
|
||||
return addedMeasurement;
|
||||
}
|
||||
|
||||
updateMeasurement(toolType, measurement) {
|
||||
const collection = this.tools[toolType];
|
||||
|
||||
const toolIndex = collection.findIndex(
|
||||
tool => tool._id === measurement._id
|
||||
);
|
||||
if (toolIndex < 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
collection[toolIndex] = Object.assign({}, measurement);
|
||||
|
||||
// Let others know that the measurements are updated
|
||||
this.onMeasurementsUpdated();
|
||||
|
||||
// TODO: Enable reactivity
|
||||
// this.timepointChanged.set(timepoint.timepointId);
|
||||
}
|
||||
|
||||
onMeasurementRemoved(toolType, measurement) {
|
||||
const { lesionNamingNumber, measurementNumber } = measurement;
|
||||
|
||||
const toolGroupId = this.toolsGroupsMap[toolType];
|
||||
const groupCollection = this.toolGroups[toolGroupId];
|
||||
|
||||
const groupIndex = groupCollection.findIndex(
|
||||
group => group.toolItemId === measurement._id
|
||||
);
|
||||
if (groupIndex < 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Remove the deleted measurement only in its timepoint from the collection
|
||||
groupCollection.splice(groupIndex, 1);
|
||||
|
||||
// Check which timepoints have the deleted measurement
|
||||
const timepointsWithDeletedMeasurement = groupCollection
|
||||
.filter(tool => tool.measurementNumber === measurementNumber)
|
||||
.map(tool => tool.timepointId);
|
||||
|
||||
// Update lesionNamingNumber and measurementNumber only if there is no timepoint with that measurement
|
||||
if (timepointsWithDeletedMeasurement.length < 1) {
|
||||
// Decrease lesionNamingNumber of all measurements with lesionNamingNumber greater than lesionNamingNumber of the deleted measurement by 1
|
||||
const lesionNamingNumberFilter = tool =>
|
||||
tool.lesionNamingNumber >= lesionNamingNumber;
|
||||
this.updateNumbering(
|
||||
groupCollection,
|
||||
lesionNamingNumberFilter,
|
||||
'lesionNamingNumber',
|
||||
-1
|
||||
);
|
||||
|
||||
const toolGroup = configuration.measurementTools.find(
|
||||
tGroup => tGroup.id === toolGroupId
|
||||
);
|
||||
if (toolGroup && toolGroup.childTools) {
|
||||
toolGroup.childTools.forEach(childTool => {
|
||||
const collection = this.tools[childTool.id];
|
||||
this.updateNumbering(
|
||||
collection,
|
||||
lesionNamingNumberFilter,
|
||||
'lesionNamingNumber',
|
||||
-1
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
// Decrease measurementNumber of all measurements with measurementNumber greater than measurementNumber of the deleted measurement by 1
|
||||
this.updateMeasurementNumberForAllMeasurements(measurement, -1);
|
||||
}
|
||||
|
||||
// Synchronize the new tool data
|
||||
this.syncMeasurementsAndToolData();
|
||||
|
||||
// Let others know that the measurements are updated
|
||||
this.onMeasurementsUpdated();
|
||||
|
||||
// TODO: Enable reactivity
|
||||
// this.timepointChanged.set(timepoint.timepointId);
|
||||
}
|
||||
|
||||
syncMeasurementsAndToolData() {
|
||||
configuration.measurementTools.forEach(toolGroup => {
|
||||
// Skip the tool groups excluded from case progress
|
||||
if (!MeasurementApi.isToolIncluded(toolGroup)) {
|
||||
return;
|
||||
}
|
||||
toolGroup.childTools.forEach(tool => {
|
||||
// Skip the tools excluded from case progress
|
||||
if (!MeasurementApi.isToolIncluded(tool)) {
|
||||
return;
|
||||
}
|
||||
const measurements = this.tools[tool.id];
|
||||
measurements.forEach(measurement => {
|
||||
MeasurementApi.syncMeasurementAndToolData(measurement);
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
deleteMeasurements(toolType, measurementTypeId, filter) {
|
||||
const filterKeys = Object.keys(filter);
|
||||
const groupCollection = this.toolGroups[measurementTypeId];
|
||||
|
||||
// Stop here if it is a temporary toolGroups
|
||||
if (!groupCollection) return;
|
||||
|
||||
// Get the entries information before removing them
|
||||
const groupItems = groupCollection.filter(toolGroup => {
|
||||
return filterKeys.every(
|
||||
filterKey => toolGroup[filterKey] === filter[filterKey]
|
||||
);
|
||||
});
|
||||
const entries = [];
|
||||
groupItems.forEach(groupItem => {
|
||||
if (!groupItem.toolId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const collection = this.tools[groupItem.toolId];
|
||||
const toolIndex = collection.findIndex(
|
||||
tool => tool._id === groupItem.toolItemId
|
||||
);
|
||||
if (toolIndex > -1) {
|
||||
entries.push(collection[toolIndex]);
|
||||
collection.splice(toolIndex, 1);
|
||||
}
|
||||
});
|
||||
|
||||
// Stop here if no entries were found
|
||||
if (!entries.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
// If the filter doesn't have the measurement number, get it from the first entry
|
||||
const lesionNamingNumber =
|
||||
filter.lesionNamingNumber || entries[0].lesionNamingNumber;
|
||||
|
||||
// Synchronize the new data with cornerstone tools
|
||||
const toolState = cornerstoneTools.globalImageIdSpecificToolStateManager.saveToolState();
|
||||
|
||||
entries.forEach(entry => {
|
||||
const measurementsData = [];
|
||||
const { tool } = MeasurementApi.getToolConfiguration(entry.toolType);
|
||||
if (Array.isArray(tool.childTools)) {
|
||||
tool.childTools.forEach(key => {
|
||||
const childMeasurement = entry[key];
|
||||
if (!childMeasurement) return;
|
||||
measurementsData.push(childMeasurement);
|
||||
});
|
||||
} else {
|
||||
measurementsData.push(entry);
|
||||
}
|
||||
|
||||
measurementsData.forEach(measurementData => {
|
||||
const { imagePath, toolType } = measurementData;
|
||||
const imageId = getImageIdForImagePath(imagePath);
|
||||
if (imageId && toolState[imageId]) {
|
||||
const toolData = toolState[imageId][toolType];
|
||||
const measurementEntries = toolData && toolData.data;
|
||||
const measurementEntry = measurementEntries.find(
|
||||
mEntry => mEntry._id === entry._id
|
||||
);
|
||||
if (measurementEntry) {
|
||||
const index = measurementEntries.indexOf(measurementEntry);
|
||||
measurementEntries.splice(index, 1);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
this.onMeasurementRemoved(toolType, entry);
|
||||
});
|
||||
|
||||
cornerstoneTools.globalImageIdSpecificToolStateManager.restoreToolState(
|
||||
toolState
|
||||
);
|
||||
|
||||
// Synchronize the updated measurements with Cornerstone Tools
|
||||
// toolData to make sure the displayed measurements show 'Target X' correctly
|
||||
const syncFilter = Object.assign({}, filter);
|
||||
delete syncFilter.timepointId;
|
||||
delete syncFilter.lesionNamingNumber;
|
||||
|
||||
const syncFilterKeys = Object.keys(syncFilter);
|
||||
|
||||
const toolTypes = [...new Set(entries.map(entry => entry.toolType))];
|
||||
toolTypes.forEach(toolType => {
|
||||
const collection = this.tools[toolType];
|
||||
collection
|
||||
.filter(tool => {
|
||||
return (
|
||||
tool.lesionNamingNumber > lesionNamingNumber - 1 &&
|
||||
syncFilterKeys.every(
|
||||
syncFilterKey => tool[syncFilterKey] === filter[syncFilterKey]
|
||||
)
|
||||
);
|
||||
})
|
||||
.forEach(measurement => {
|
||||
MeasurementApi.syncMeasurementAndToolData(measurement);
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,576 @@
|
||||
import log from '../../log';
|
||||
|
||||
const configuration = {};
|
||||
|
||||
const TIMEPOINT_TYPE_NAMES = {
|
||||
prebaseline: 'Pre-Baseline',
|
||||
baseline: 'Baseline',
|
||||
followup: 'Follow-up',
|
||||
};
|
||||
|
||||
export default class TimepointApi {
|
||||
static Instance;
|
||||
|
||||
static setConfiguration(config) {
|
||||
Object.assign(configuration, config);
|
||||
}
|
||||
|
||||
static getConfiguration() {
|
||||
return configuration;
|
||||
}
|
||||
|
||||
constructor(currentTimepointId, options = {}) {
|
||||
if (TimepointApi.Instance) {
|
||||
TimepointApi.Instance.initialize(currentTimepointId, options);
|
||||
return TimepointApi.Instance;
|
||||
}
|
||||
|
||||
this.initialize(currentTimepointId, options);
|
||||
TimepointApi.Instance = this;
|
||||
}
|
||||
|
||||
initialize(currentTimepointId, options = {}) {
|
||||
this.currentTimepointId = currentTimepointId;
|
||||
this.comparisonTimepointKey = options.comparisonTimepointKey || 'baseline';
|
||||
this.options = options;
|
||||
this.timepoints = [];
|
||||
}
|
||||
|
||||
onTimepointsUpdated() {
|
||||
if (typeof this.options.onTimepointsUpdated !== 'function') {
|
||||
log.warn('Timepoints update callback is not defined');
|
||||
return;
|
||||
}
|
||||
|
||||
this.options.onTimepointsUpdated(Object.assign([], this.timepoints));
|
||||
}
|
||||
|
||||
calculateVisitNumber(timepoint) {
|
||||
// Retrieve all of the relevant follow-up timepoints for this patient
|
||||
const sortedTimepoints = this.timepoints.sort((tp1, tp2) => {
|
||||
return tp1.visitDate > tp2.visitDate ? 1 : -1;
|
||||
});
|
||||
const filteredTimepoints = sortedTimepoints.find(
|
||||
tp =>
|
||||
tp.patientId === timepoint.patientId &&
|
||||
tp.timepointType === timepoint.timepointType
|
||||
);
|
||||
|
||||
// Create an array of just timepointIds, so we can use indexOf
|
||||
// on it to find the current timepoint's relative position
|
||||
const timepointIds = filteredTimepoints.map(
|
||||
timepoint => timepoint.timepointId
|
||||
);
|
||||
|
||||
// Calculate the index of the current timepoint in the array of all
|
||||
// relevant follow-up timepoints
|
||||
const visitNumber = timepointIds.indexOf(timepoint.timepointId) + 1;
|
||||
|
||||
// If visitNumber is 0, it means that the current timepoint was not in the list
|
||||
if (!visitNumber) {
|
||||
throw new Error(
|
||||
'Current timepoint was not in the list of relevant timepoints?'
|
||||
);
|
||||
}
|
||||
|
||||
return visitNumber;
|
||||
}
|
||||
|
||||
retrieveTimepoints(filter) {
|
||||
const retrievalFn = configuration.dataExchange.retrieve;
|
||||
if (typeof retrievalFn !== 'function') {
|
||||
log.error('Timepoint retrieval function has not been configured.');
|
||||
return;
|
||||
}
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
retrievalFn(filter)
|
||||
.then(timepointData => {
|
||||
log.info('Timepoint data retrieval');
|
||||
|
||||
timepointData.forEach(timepoint => {
|
||||
const timepointIndex = this.timepoints.findIndex(
|
||||
tp => tp.timepointId === timepoint.timepointId
|
||||
);
|
||||
if (timepointIndex < 0) {
|
||||
this.timepoints.push(timepoint);
|
||||
} else {
|
||||
this.timepoints[timepointIndex] = timepoint;
|
||||
}
|
||||
});
|
||||
|
||||
// Let others know that the timepoints are updated
|
||||
this.onTimepointsUpdated();
|
||||
|
||||
resolve();
|
||||
})
|
||||
.catch(reason => {
|
||||
log.error(`Timepoint retrieval function failed: ${reason}`);
|
||||
reject(reason);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
storeTimepoints() {
|
||||
const storeFn = configuration.dataExchange.store;
|
||||
if (typeof storeFn !== 'function') {
|
||||
log.error('Timepoint store function has not been configured.');
|
||||
return;
|
||||
}
|
||||
|
||||
log.info('Preparing to store timepoints');
|
||||
log.info(JSON.stringify(this.timepoints, null, 2));
|
||||
|
||||
storeFn(this.timepoints).then(() =>
|
||||
log.info('Timepoint storage completed')
|
||||
);
|
||||
}
|
||||
|
||||
disassociateStudy(timepointIds, studyInstanceUid) {
|
||||
const disassociateFn = configuration.dataExchange.disassociate;
|
||||
if (typeof disassociateFn !== 'function') {
|
||||
log.error('Study disassociate function has not been configured.');
|
||||
return;
|
||||
}
|
||||
|
||||
disassociateFn(timepointIds, studyInstanceUid).then(() => {
|
||||
log.info('Disassociation completed');
|
||||
|
||||
this.timepoints = [];
|
||||
this.retrieveTimepoints({});
|
||||
});
|
||||
}
|
||||
|
||||
removeTimepoint(timepointId) {
|
||||
const removeFn = configuration.dataExchange.remove;
|
||||
if (typeof removeFn !== 'function') {
|
||||
log.error('Timepoint remove function has not been configured.');
|
||||
return;
|
||||
}
|
||||
|
||||
const timepointData = {
|
||||
timepointId,
|
||||
};
|
||||
|
||||
log.info('Preparing to remove timepoint');
|
||||
log.info(JSON.stringify(timepointData, null, 2));
|
||||
|
||||
removeFn(timepointData).then(() => {
|
||||
log.info('Timepoint removal completed');
|
||||
|
||||
const tpIndex = this.timepoints.findIndex(
|
||||
tp => tp.timepointId === timepointId
|
||||
);
|
||||
if (tpIndex > -1) {
|
||||
this.timepoints.splice(tpIndex, 1);
|
||||
}
|
||||
|
||||
// Let others know that the timepoints are updated
|
||||
this.onTimepointsUpdated();
|
||||
});
|
||||
}
|
||||
|
||||
updateTimepoint(timepointId, query) {
|
||||
const updateFn = configuration.dataExchange.update;
|
||||
if (typeof updateFn !== 'function') {
|
||||
log.error('Timepoint update function has not been configured.');
|
||||
return;
|
||||
}
|
||||
|
||||
const timepointData = {
|
||||
timepointId,
|
||||
};
|
||||
|
||||
log.info('Preparing to update timepoint');
|
||||
log.info(JSON.stringify(timepointData, null, 2));
|
||||
log.info(JSON.stringify(query, null, 2));
|
||||
|
||||
updateFn(timepointData, query).then(() => {
|
||||
log.info('Timepoint updated completed');
|
||||
|
||||
const tpIndex = this.timepoints.findIndex(
|
||||
tp => tp.timepointId === timepointId
|
||||
);
|
||||
if (tpIndex > -1) {
|
||||
this.timepoints[tpIndex] = Object.assign(
|
||||
{},
|
||||
this.timepoints[tpIndex],
|
||||
query
|
||||
);
|
||||
}
|
||||
|
||||
// Let others know that the timepoints are updated
|
||||
this.onTimepointsUpdated();
|
||||
});
|
||||
}
|
||||
|
||||
// Return all timepoints
|
||||
all(filter) {
|
||||
let timepointsToReturn;
|
||||
if (filter) {
|
||||
timepointsToReturn = this.timepoints.filter(filter);
|
||||
} else {
|
||||
timepointsToReturn = this.timepoints;
|
||||
}
|
||||
|
||||
return timepointsToReturn.sort((tp1, tp2) => {
|
||||
return tp1.visitDate < tp2.visitDate ? 1 : -1;
|
||||
});
|
||||
}
|
||||
|
||||
// Return only the current timepoint
|
||||
current() {
|
||||
return this.timepoints.find(
|
||||
tp => tp.timepointId === this.currentTimepointId
|
||||
);
|
||||
}
|
||||
|
||||
lock() {
|
||||
const tpIndex = this.timepoints.findIndex(
|
||||
tp => tp.timepointId === this.currentTimepointId
|
||||
);
|
||||
if (tpIndex < 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.timepoints[tpIndex] = Object.assign({}, this.timepoints[tpIndex], {
|
||||
locked: true,
|
||||
});
|
||||
}
|
||||
|
||||
// Return the prior timepoint
|
||||
prior() {
|
||||
const current = this.current();
|
||||
if (!current) {
|
||||
return;
|
||||
}
|
||||
|
||||
return this.all().find(tp => tp.visitDate < current.visitDate);
|
||||
}
|
||||
|
||||
// Return only the current and prior timepoints
|
||||
currentAndPrior() {
|
||||
const timepoints = [];
|
||||
|
||||
const current = this.current();
|
||||
if (current) {
|
||||
timepoints.push(current);
|
||||
}
|
||||
|
||||
const prior = this.prior();
|
||||
if (current && prior && prior.timepointId !== current.timepointId) {
|
||||
timepoints.push(prior);
|
||||
}
|
||||
|
||||
return timepoints;
|
||||
}
|
||||
|
||||
// Return the current and the comparison timepoints
|
||||
currentAndComparison(comparisonTimepointKey = this.comparisonTimepointKey) {
|
||||
const current = this.current();
|
||||
const comparisonTimepoint = this.comparison(comparisonTimepointKey);
|
||||
const timepoints = [current];
|
||||
|
||||
if (
|
||||
comparisonTimepoint &&
|
||||
!timepoints.find(tp => tp.timepointId === comparisonTimepoint.timepointId)
|
||||
) {
|
||||
timepoints.push(comparisonTimepoint);
|
||||
}
|
||||
|
||||
return timepoints;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return true if there are 2 or more baseline timepoints before and at the current timepoint, otherwise false
|
||||
* @returns {boolean}
|
||||
*/
|
||||
isRebaseline(timepointId) {
|
||||
const current = timepointId
|
||||
? this.timepoints.find(tp => tp.timepointId === timepointId)
|
||||
: this.current();
|
||||
if (!current) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const baselines = this.timepoints.filter(
|
||||
tp => tp.timepointType === 'baseline' && tp.visitDate <= current.visitDate
|
||||
);
|
||||
return baselines.length > 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the next (closest future) baseline after current timepoint
|
||||
* @returns {*}
|
||||
*/
|
||||
nextBaselineAfterCurrent() {
|
||||
let current = this.current();
|
||||
|
||||
// Get all next timepoints newer than the current timepoint sorted by visitDate ascending
|
||||
const sortedTimepoints = this.timepoints.sort((tp1, tp2) => {
|
||||
return tp1.visitDate > tp2.visitDate ? 1 : -1;
|
||||
});
|
||||
return sortedTimepoints.find(
|
||||
tp => tp.visitDate > current.visitDate && tp.timepointType === 'baseline'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the current timepoint id
|
||||
* @param timepointId
|
||||
*/
|
||||
setCurrentTimepointId(timepointId) {
|
||||
this.currentTimepointId = timepointId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the comparison timepoint that overrides the default comparison timepoint (called based on user selection in a viewport)
|
||||
* @param timepoint
|
||||
*/
|
||||
setUserComparison(timepoint) {
|
||||
this.userComparison = timepoint;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return only the comparison timepoint
|
||||
* @param {String} [comparisonTimepointKey]
|
||||
* @return {*}
|
||||
*/
|
||||
comparison(comparisonTimepointKey = this.comparisonTimepointKey) {
|
||||
// Return the comparison timepoint set by user if exists
|
||||
if (this.userComparison) {
|
||||
return this.userComparison;
|
||||
}
|
||||
|
||||
const current = this.current();
|
||||
if (!current) {
|
||||
return;
|
||||
}
|
||||
|
||||
// If current timepoint is prebaseline, the first (closest future) BL after current is comparison regardless of default comparison timepoint
|
||||
if (current.timepointType === 'prebaseline') {
|
||||
const nextBaselineAfterCurrent = this.nextBaselineAfterCurrent();
|
||||
// If there is a next baseline, make it comparison, otherwise comparison is done by default comparison timepoint
|
||||
if (nextBaselineAfterCurrent) {
|
||||
return nextBaselineAfterCurrent;
|
||||
}
|
||||
}
|
||||
|
||||
// If current timepoint is baseline, the prior is comparison if exists regardless of default comparison timepoint
|
||||
if (current.timepointType === 'baseline') {
|
||||
const prior = this.prior();
|
||||
if (prior) {
|
||||
return prior;
|
||||
}
|
||||
}
|
||||
|
||||
const comparison = this[comparisonTimepointKey]();
|
||||
|
||||
// Do not return a comparison if it would be identical to
|
||||
// the current.
|
||||
if (comparison && comparison.timepointId === current.timepointId) {
|
||||
return;
|
||||
}
|
||||
|
||||
return comparison;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the latest initial (prebaseline or baseline) timepoint after current and before the next followup timepoint
|
||||
* @returns {*}
|
||||
*/
|
||||
latestInitialTimepointAfterCurrent() {
|
||||
let currentTimepoint = this.current();
|
||||
|
||||
// Skip if the current timepoint is FU since there is no initial timepoint after follow-up
|
||||
if (currentTimepoint.timepointType === 'followup') {
|
||||
return;
|
||||
}
|
||||
|
||||
// Get all next timepoints newer than the current timepoint sorted by visitDate ascending
|
||||
const sortedTimepoints = this.timepoints.sort((tp1, tp2) => {
|
||||
return tp1.visitDate > tp2.visitDate ? 1 : -1;
|
||||
});
|
||||
const allNextTimepoints = sortedTimepoints.filter(
|
||||
tp => tp.visitDate > currentTimepoint.visitDate
|
||||
);
|
||||
|
||||
const nextFollowupIndex = allNextTimepoints.findIndex(
|
||||
tp => tp.timepointType === 'followup'
|
||||
);
|
||||
const latestInitialBeforeNextFUIndex = nextFollowupIndex - 1;
|
||||
|
||||
if (latestInitialBeforeNextFUIndex < 0) {
|
||||
// There is no FU and all next timepoints are initial, so return the last one
|
||||
return allNextTimepoints[allNextTimepoints.length - 1];
|
||||
}
|
||||
|
||||
// Return the latest initial timepoint before the next FU
|
||||
return allNextTimepoints[latestInitialBeforeNextFUIndex];
|
||||
}
|
||||
|
||||
/**
|
||||
* Return timepoint ids of initial timepoints which are prebaseline and baseline
|
||||
* @returns {*}
|
||||
*/
|
||||
initialTimepointIds() {
|
||||
let timepointToCheck = this.current();
|
||||
|
||||
// If the current timepoint is PBL or BL, then get the recent PBL/BL of the current timepoint by its first FU
|
||||
// If it does not exist, then there is no newer initial timepoint, so the current timepoint is used to determine initial timepoint ids
|
||||
if (
|
||||
timepointToCheck.timepointType === 'prebaseline' ||
|
||||
timepointToCheck.timepointType === 'baseline'
|
||||
) {
|
||||
timepointToCheck =
|
||||
this.latestInitialTimepointAfterCurrent() || timepointToCheck;
|
||||
}
|
||||
|
||||
const visitDateToCheck = timepointToCheck.visitDate;
|
||||
|
||||
const preBaselineTimepoints =
|
||||
this.timepoints.filter(
|
||||
tp =>
|
||||
tp.timepointType === 'prebaseline' && tp.visitDate <= visitDateToCheck
|
||||
) || [];
|
||||
const preBaselineTimepointIds = preBaselineTimepoints.map(
|
||||
timepoint => timepoint.timepointId
|
||||
);
|
||||
|
||||
const baselineTimepoints =
|
||||
this.timepoints.filter(
|
||||
tp =>
|
||||
tp.timepointType === 'baseline' && tp.visitDate <= visitDateToCheck
|
||||
) || [];
|
||||
const baselineTimepointIds = baselineTimepoints.map(
|
||||
timepoint => timepoint.timepointId
|
||||
);
|
||||
|
||||
return preBaselineTimepointIds.concat(baselineTimepointIds);
|
||||
}
|
||||
|
||||
// Return only the baseline timepoint
|
||||
baseline() {
|
||||
const currentVisitDate = this.current().visitDate;
|
||||
return this.all().find(
|
||||
tp => tp.timepointType === 'baseline' && tp.visitDate <= currentVisitDate
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return only the nadir timepoint. Must be prior to the current timepoint
|
||||
* @return {any}
|
||||
*/
|
||||
nadir() {
|
||||
const current = this.current();
|
||||
const nadir = this.all().find(
|
||||
tp =>
|
||||
tp.timepointId !== current.timepointId &&
|
||||
tp.timepointKey === 'nadir' &&
|
||||
tp.visitDate <= current.visitDate
|
||||
);
|
||||
|
||||
// If we have found a nadir, return that
|
||||
if (nadir) {
|
||||
return nadir;
|
||||
}
|
||||
|
||||
// Otherwise, return the most recent baseline
|
||||
// This should only happen if we are only at FU1,
|
||||
// so the baseline is the nadir.
|
||||
return this.baseline();
|
||||
}
|
||||
|
||||
// Return only the key timepoints (current, prior, nadir and baseline)
|
||||
key() {
|
||||
const result = [this.current()];
|
||||
const prior = this.prior();
|
||||
const nadir = this.nadir();
|
||||
const baseline = this.baseline();
|
||||
|
||||
const resultIncludes = timepoint =>
|
||||
!!result.find(x => x.timepointId === timepoint.timepointId);
|
||||
|
||||
if (prior && resultIncludes(prior) === false) {
|
||||
result.push(prior);
|
||||
}
|
||||
|
||||
if (nadir && resultIncludes(nadir) === false) {
|
||||
result.push(nadir);
|
||||
}
|
||||
|
||||
if (baseline && resultIncludes(baseline) === false) {
|
||||
result.push(baseline);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
// Return only the timepoints for the given study
|
||||
study(studyInstanceUid) {
|
||||
return this.all().filter(timepoint =>
|
||||
timepoint.studyInstanceUids.includes(studyInstanceUid)
|
||||
);
|
||||
}
|
||||
|
||||
// Return the timepoint's name
|
||||
name(timepoint) {
|
||||
const timepointTypeName = TIMEPOINT_TYPE_NAMES[timepoint.timepointType];
|
||||
|
||||
// Check if this is a Baseline timepoint, if it is, return 'Baseline'
|
||||
if (timepoint.timepointType === 'baseline') {
|
||||
return 'Baseline';
|
||||
} else if (timepoint.visitNumber) {
|
||||
return `${timepointTypeName} ${timepoint.visitNumber}`;
|
||||
}
|
||||
|
||||
const visitNumber = this.calculateVisitNumber(timepoint);
|
||||
|
||||
// Return the timepoint name as 'Follow-up N'
|
||||
return `${timepointTypeName} ${visitNumber}`;
|
||||
}
|
||||
|
||||
// Build the timepoint title based on its date
|
||||
title(timepoint) {
|
||||
const timepointName = this.name(timepoint);
|
||||
|
||||
const all = this.all();
|
||||
let index = -1;
|
||||
let currentIndex = null;
|
||||
for (let i = 0; i < all.length; i++) {
|
||||
const currentTimepoint = all[i];
|
||||
|
||||
// Skip the iterations until we can't find the selected timepoint on study list
|
||||
if (this.currentTimepointId === currentTimepoint.timepointId) {
|
||||
currentIndex = 0;
|
||||
}
|
||||
|
||||
if (currentIndex !== null) {
|
||||
index = currentIndex++;
|
||||
}
|
||||
|
||||
// Break the loop if reached the timepoint to get the title
|
||||
if (currentTimepoint.timepointId === timepoint.timepointId) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
const states = {
|
||||
0: ['Current'],
|
||||
1: ['Prior'],
|
||||
};
|
||||
const parenthesis = states[index] || [];
|
||||
const nadir = this.nadir();
|
||||
|
||||
if (nadir && nadir.timepointId === timepoint.timepointId) {
|
||||
parenthesis.push('Nadir');
|
||||
}
|
||||
|
||||
let parenthesisText = '';
|
||||
if (parenthesis.length) {
|
||||
parenthesisText = `(${parenthesis.join(', ')})`;
|
||||
}
|
||||
|
||||
return `${timepointName} ${parenthesisText}`;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
import MeasurementApi from './MeasurementApi';
|
||||
import TimepointApi from './TimepointApi';
|
||||
|
||||
export { TimepointApi, MeasurementApi };
|
||||
@@ -0,0 +1,41 @@
|
||||
import { TimepointApi, MeasurementApi } from './classes';
|
||||
import { allTools } from './toolGroups/allTools';
|
||||
import {
|
||||
retrieveMeasurements,
|
||||
storeMeasurements,
|
||||
retrieveTimepoints,
|
||||
storeTimepoints,
|
||||
removeTimepoint,
|
||||
updateTimepoint,
|
||||
disassociateStudy,
|
||||
} from './dataExchange';
|
||||
|
||||
MeasurementApi.setConfiguration({
|
||||
measurementTools: [allTools],
|
||||
newLesions: [
|
||||
{
|
||||
id: 'newTargets',
|
||||
name: 'New Targets',
|
||||
toolGroupId: 'targets',
|
||||
},
|
||||
{
|
||||
id: 'newNonTargets',
|
||||
name: 'New Non-Targets',
|
||||
toolGroupId: 'nonTargets',
|
||||
},
|
||||
],
|
||||
dataExchange: {
|
||||
retrieve: retrieveMeasurements,
|
||||
store: storeMeasurements,
|
||||
},
|
||||
});
|
||||
|
||||
TimepointApi.setConfiguration({
|
||||
dataExchange: {
|
||||
retrieve: retrieveTimepoints,
|
||||
store: storeTimepoints,
|
||||
remove: removeTimepoint,
|
||||
update: updateTimepoint,
|
||||
disassociate: disassociateStudy,
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,229 @@
|
||||
import { CriteriaEvaluator } from './CriteriaEvaluator';
|
||||
import * as initialEvaluations from './evaluations';
|
||||
import log from '../../log';
|
||||
|
||||
const evaluations = Object.assign({}, initialEvaluations);
|
||||
|
||||
const BASELINE = 'baseline';
|
||||
const FOLLOWUP = 'followup';
|
||||
const BOTH = 'both';
|
||||
const TARGETS = 'targets';
|
||||
const NONTARGETS = 'nonTargets';
|
||||
|
||||
class ConformanceCriteria {
|
||||
constructor(measurementApi, timepointApi, options = {}) {
|
||||
this.measurementApi = measurementApi;
|
||||
this.timepointApi = timepointApi;
|
||||
this.nonconformities = [];
|
||||
this.groupedNonConformities = [];
|
||||
this.maxTargets = null;
|
||||
this.maxNewTargets = null;
|
||||
this.options = options;
|
||||
}
|
||||
|
||||
loadStudy(studyInstanceUid) {
|
||||
if (typeof this.options.loadStudy !== 'function') {
|
||||
throw new Error('loadStudy callback is not defined');
|
||||
}
|
||||
|
||||
return this.options.loadStudy(null, studyInstanceUid);
|
||||
}
|
||||
|
||||
async validate(trialCriteriaType) {
|
||||
const baselinePromise = this.getData(BASELINE);
|
||||
const followupPromise = this.getData(FOLLOWUP);
|
||||
const [baselineData, followupData] = await Promise.all([
|
||||
baselinePromise,
|
||||
followupPromise,
|
||||
]);
|
||||
const mergedData = {
|
||||
targets: [],
|
||||
nonTargets: [],
|
||||
};
|
||||
|
||||
mergedData.targets = mergedData.targets.concat(baselineData.targets);
|
||||
mergedData.targets = mergedData.targets.concat(followupData.targets);
|
||||
mergedData.nonTargets = mergedData.nonTargets.concat(
|
||||
baselineData.nonTargets
|
||||
);
|
||||
mergedData.nonTargets = mergedData.nonTargets.concat(
|
||||
followupData.nonTargets
|
||||
);
|
||||
|
||||
this.maxTargets = null;
|
||||
this.maxNewTargets = null;
|
||||
const resultBoth = this.validateTimepoint(
|
||||
BOTH,
|
||||
trialCriteriaType,
|
||||
mergedData
|
||||
);
|
||||
const resultBaseline = this.validateTimepoint(
|
||||
BASELINE,
|
||||
trialCriteriaType,
|
||||
baselineData
|
||||
);
|
||||
const resultFollowup = this.validateTimepoint(
|
||||
FOLLOWUP,
|
||||
trialCriteriaType,
|
||||
followupData
|
||||
);
|
||||
const nonconformities = resultBaseline
|
||||
.concat(resultFollowup)
|
||||
.concat(resultBoth);
|
||||
const groupedNonConformities = this.groupNonConformities(nonconformities);
|
||||
|
||||
// Keep both? Group the data only on viewer/measurementTable views?
|
||||
// Work with not grouped data (worse lookup performance on measurementTableRow)?
|
||||
this.nonconformities = nonconformities;
|
||||
this.groupedNonConformities = groupedNonConformities;
|
||||
|
||||
console.warn('nonconformities');
|
||||
console.warn(nonconformities);
|
||||
console.warn('groupedNonConformities');
|
||||
console.warn(groupedNonConformities);
|
||||
|
||||
return nonconformities;
|
||||
}
|
||||
|
||||
groupNonConformities(nonconformities) {
|
||||
const groups = {};
|
||||
const toolsGroupsMap = this.measurementApi.toolsGroupsMap;
|
||||
|
||||
nonconformities.forEach(nonConformity => {
|
||||
if (nonConformity.isGlobal) {
|
||||
groups.globals = groups.globals || { messages: [] };
|
||||
groups.globals.messages.push(nonConformity.message);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
nonConformity.measurements.forEach(measurement => {
|
||||
const groupName = toolsGroupsMap[measurement.toolType];
|
||||
groups[groupName] = groups[groupName] || { measurementNumbers: {} };
|
||||
|
||||
const group = groups[groupName];
|
||||
const measureNumber = measurement.measurementNumber;
|
||||
let measurementNumbers = group.measurementNumbers[measureNumber];
|
||||
|
||||
if (!measurementNumbers) {
|
||||
measurementNumbers = group.measurementNumbers[measureNumber] = {
|
||||
messages: [],
|
||||
measurements: [],
|
||||
};
|
||||
}
|
||||
|
||||
measurementNumbers.messages.push(nonConformity.message);
|
||||
measurementNumbers.measurements.push(measurement);
|
||||
});
|
||||
});
|
||||
|
||||
return groups;
|
||||
}
|
||||
|
||||
validateTimepoint(timepointType, trialCriteriaType, data) {
|
||||
const evaluators = this.getEvaluators(timepointType, trialCriteriaType);
|
||||
let nonconformities = [];
|
||||
|
||||
evaluators.forEach(evaluator => {
|
||||
const maxTargets = evaluator.getMaxTargets(false);
|
||||
const maxNewTargets = evaluator.getMaxTargets(true);
|
||||
if (maxTargets) {
|
||||
this.maxTargets = maxTargets;
|
||||
}
|
||||
|
||||
if (maxNewTargets) {
|
||||
this.maxNewTargets = maxNewTargets;
|
||||
}
|
||||
|
||||
const result = evaluator.evaluate(data);
|
||||
|
||||
if (result.length > 0) {
|
||||
result.forEach(resultItem => {
|
||||
resultItem.timepointType = timepointType;
|
||||
});
|
||||
}
|
||||
|
||||
nonconformities = nonconformities.concat(result);
|
||||
});
|
||||
|
||||
return nonconformities;
|
||||
}
|
||||
|
||||
getEvaluators(timepointType, trialCriteriaType) {
|
||||
const evaluators = [];
|
||||
console.warn(evaluations);
|
||||
const trialCriteriaTypeId = trialCriteriaType.id.toLowerCase();
|
||||
const evaluation = evaluations[trialCriteriaTypeId];
|
||||
|
||||
if (evaluation) {
|
||||
const evaluationTimepoint = evaluation[timepointType];
|
||||
|
||||
if (evaluationTimepoint) {
|
||||
evaluators.push(new CriteriaEvaluator(evaluationTimepoint));
|
||||
}
|
||||
}
|
||||
|
||||
return evaluators;
|
||||
}
|
||||
|
||||
/*
|
||||
* Build the data that will be used to do the conformance criteria checks
|
||||
*/
|
||||
async getData(timepointType) {
|
||||
const data = {
|
||||
targets: [],
|
||||
nonTargets: [],
|
||||
};
|
||||
|
||||
const studyPromises = [];
|
||||
|
||||
const fillData = measurementType => {
|
||||
const measurements = this.measurementApi.fetch(measurementType);
|
||||
|
||||
measurements.forEach(measurement => {
|
||||
const { studyInstanceUid } = measurement;
|
||||
|
||||
const timepointId = measurement.timepointId;
|
||||
const timepoint =
|
||||
timepointId &&
|
||||
this.timepointApi.timepoints.find(a => a.timepointId === timepointId);
|
||||
|
||||
if (
|
||||
!timepoint ||
|
||||
(timepointType !== BOTH && timepoint.timepointType !== timepointType)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
const promise = this.loadStudy(studyInstanceUid);
|
||||
promise.then(
|
||||
studyMetadata => {
|
||||
data[measurementType].push({
|
||||
measurement,
|
||||
metadata: studyMetadata.getFirstInstance(),
|
||||
timepoint,
|
||||
});
|
||||
},
|
||||
error => {
|
||||
throw new Error(error);
|
||||
}
|
||||
);
|
||||
studyPromises.push(promise);
|
||||
});
|
||||
};
|
||||
|
||||
fillData(TARGETS);
|
||||
fillData(NONTARGETS);
|
||||
|
||||
await Promise.all(studyPromises);
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
static setEvaluationDefinitions(evaluationKey, evaluationDefinitions) {
|
||||
evaluations[evaluationKey] = evaluationDefinitions;
|
||||
}
|
||||
}
|
||||
|
||||
export default ConformanceCriteria;
|
||||
//OHIF.measurements.ConformanceCriteria = ConformanceCriteria;
|
||||
@@ -0,0 +1,94 @@
|
||||
import { BaseCriterion } from './criteria/BaseCriterion';
|
||||
import * as initialCriteria from './criteria';
|
||||
import Ajv from 'ajv';
|
||||
|
||||
const Criteria = Object.assign({}, initialCriteria);
|
||||
|
||||
export class CriteriaEvaluator {
|
||||
constructor(criteriaObject) {
|
||||
const criteriaValidator = this.getCriteriaValidator();
|
||||
this.criteria = [];
|
||||
|
||||
if (!criteriaValidator(criteriaObject)) {
|
||||
let message = '';
|
||||
criteriaValidator.errors.forEach(error => {
|
||||
message += `\noptions${error.dataPath} ${error.message}`;
|
||||
});
|
||||
throw new Error(message);
|
||||
}
|
||||
|
||||
Object.keys(criteriaObject).forEach(criterionkey => {
|
||||
const optionsObject = criteriaObject[criterionkey];
|
||||
const Criterion = Criteria[`${criterionkey}Criterion`];
|
||||
const optionsArray =
|
||||
optionsObject instanceof Array ? optionsObject : [optionsObject];
|
||||
optionsArray.forEach(options =>
|
||||
this.criteria.push(new Criterion(options, criterionkey))
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
getMaxTargets(newTarget = false) {
|
||||
let result = 0;
|
||||
this.criteria.forEach(criterion => {
|
||||
const newTargetMatch = newTarget === !!criterion.options.newTarget;
|
||||
if (criterion instanceof Criteria.MaxTargetsCriterion && newTargetMatch) {
|
||||
const { limit } = criterion.options;
|
||||
if (limit > result) {
|
||||
result = limit;
|
||||
}
|
||||
}
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
getCriteriaValidator() {
|
||||
if (CriteriaEvaluator.criteriaValidator) {
|
||||
return CriteriaEvaluator.criteriaValidator;
|
||||
}
|
||||
|
||||
const schema = {
|
||||
properties: {},
|
||||
definitions: {},
|
||||
};
|
||||
|
||||
Object.keys(Criteria).forEach(key => {
|
||||
const Criterion = Criteria[key];
|
||||
if (Criterion.prototype instanceof BaseCriterion) {
|
||||
const criterionkey = key.replace(/Criterion$/, '');
|
||||
const criterionDefinition = `#/definitions/${criterionkey}`;
|
||||
|
||||
schema.definitions[criterionkey] = Criteria[`${criterionkey}Schema`];
|
||||
schema.properties[criterionkey] = {
|
||||
oneOf: [
|
||||
{ $ref: criterionDefinition },
|
||||
{
|
||||
type: 'array',
|
||||
items: {
|
||||
$ref: criterionDefinition,
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
CriteriaEvaluator.criteriaValidator = new Ajv().compile(schema);
|
||||
return CriteriaEvaluator.criteriaValidator;
|
||||
}
|
||||
|
||||
evaluate(data) {
|
||||
const nonconformities = [];
|
||||
this.criteria.forEach(criterion => {
|
||||
const criterionResult = criterion.evaluate(data);
|
||||
if (!criterionResult.passed) {
|
||||
nonconformities.push(criterionResult);
|
||||
}
|
||||
});
|
||||
return nonconformities;
|
||||
}
|
||||
|
||||
static setCriterion(criterionKey, criterionDefinitions) {
|
||||
Criteria[criterionKey] = criterionDefinitions;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
export class BaseCriterion {
|
||||
constructor(options, criterionName) {
|
||||
this.options = options;
|
||||
this.criterionName = criterionName;
|
||||
}
|
||||
|
||||
generateResponse(message, measurements) {
|
||||
const passed = !message;
|
||||
const isGlobal = !measurements || !measurements.length;
|
||||
|
||||
return {
|
||||
passed,
|
||||
isGlobal,
|
||||
message,
|
||||
measurements,
|
||||
criterionName: this.criterionName,
|
||||
};
|
||||
}
|
||||
|
||||
getNewTargetNumbers(data) {
|
||||
const { options } = this;
|
||||
const baselineMeasurementNumbers = [];
|
||||
const newTargetNumbers = new Set();
|
||||
|
||||
if (options.newTarget) {
|
||||
data.targets.forEach(target => {
|
||||
const { measurementNumber } = target.measurement;
|
||||
if (target.timepoint.timepointType === 'baseline') {
|
||||
baselineMeasurementNumbers.push(measurementNumber);
|
||||
}
|
||||
});
|
||||
data.targets.forEach(target => {
|
||||
const { measurementNumber } = target.measurement;
|
||||
if (target.timepoint.timepointType === 'followup') {
|
||||
if (!baselineMeasurementNumbers.includes(measurementNumber)) {
|
||||
newTargetNumbers.add(measurementNumber);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return newTargetNumbers;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { BaseCriterion } from './BaseCriterion';
|
||||
|
||||
export const LocationSchema = {
|
||||
type: 'object',
|
||||
};
|
||||
|
||||
/* LocationCriterion
|
||||
* Check if the there are non-target measurements with response different than "present" on baseline
|
||||
*/
|
||||
export class LocationCriterion extends BaseCriterion {
|
||||
constructor(...props) {
|
||||
super(...props);
|
||||
}
|
||||
|
||||
evaluate(data) {
|
||||
const items = data.targets.concat(data.nonTargets);
|
||||
const measurements = [];
|
||||
let message;
|
||||
|
||||
items.forEach(item => {
|
||||
const measurement = item.measurement;
|
||||
|
||||
if (!measurement.location) {
|
||||
measurements.push(measurement);
|
||||
}
|
||||
});
|
||||
|
||||
if (measurements.length) {
|
||||
message = 'All measurements should have a location';
|
||||
}
|
||||
|
||||
return this.generateResponse(message, measurements);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
import { BaseCriterion } from './BaseCriterion';
|
||||
|
||||
export const MaxTargetsSchema = {
|
||||
type: 'object',
|
||||
properties: {
|
||||
limit: {
|
||||
label: 'Max targets allowed in study',
|
||||
type: 'integer',
|
||||
minimum: 0,
|
||||
},
|
||||
newTarget: {
|
||||
label: 'Flag to evaluate only new targets',
|
||||
type: 'boolean',
|
||||
},
|
||||
locationIn: {
|
||||
label:
|
||||
'Filter to evaluate only measurements with the specified locations',
|
||||
type: 'array',
|
||||
items: {
|
||||
type: 'string',
|
||||
},
|
||||
minItems: 1,
|
||||
uniqueItems: true,
|
||||
},
|
||||
locationNotIn: {
|
||||
label:
|
||||
'Filter to evaluate only measurements without the specified locations',
|
||||
type: 'array',
|
||||
items: {
|
||||
type: 'string',
|
||||
},
|
||||
minItems: 1,
|
||||
uniqueItems: true,
|
||||
},
|
||||
isNodal: {
|
||||
label: 'Filter to evaluate only nodal or extranodal measurements',
|
||||
type: 'boolean'
|
||||
},
|
||||
message: {
|
||||
label: 'Message to be displayed in case of nonconformity',
|
||||
type: 'string',
|
||||
}
|
||||
},
|
||||
required: ['limit'],
|
||||
};
|
||||
|
||||
/* MaxTargetsCriterion
|
||||
* Check if the number of target measurements exceeded the limit allowed
|
||||
* Options:
|
||||
* limit: Max targets allowed in study
|
||||
* newTarget: Flag to evaluate only new targets (must be evaluated on both)
|
||||
* locationIn: Filter to evaluate only measurements with the specified locations
|
||||
* locationNotIn: Filter to evaluate only measurements without the specified locations
|
||||
* isNodal: Filter to evaluate only nodal or extranodal measurements
|
||||
* message: Message to be displayed in case of nonconformity
|
||||
*/
|
||||
export class MaxTargetsCriterion extends BaseCriterion {
|
||||
constructor(...props) {
|
||||
super(...props);
|
||||
}
|
||||
|
||||
evaluate(data) {
|
||||
const { options } = this;
|
||||
|
||||
const newTargetNumbers = this.getNewTargetNumbers(data);
|
||||
const measurementNumbers = [];
|
||||
data.targets.forEach(target => {
|
||||
const { location, measurementNumber, isSplitLesion, isNodal } = target.measurement;
|
||||
|
||||
if (isSplitLesion)
|
||||
return;
|
||||
|
||||
if (typeof isNodal === 'boolean' && typeof options.isNodal === 'boolean' && options.isNodal !== isNodal)
|
||||
return;
|
||||
|
||||
if (options.newTarget && !newTargetNumbers.has(measurementNumber))
|
||||
return;
|
||||
|
||||
if (options.locationIn && options.locationIn.indexOf(location) === -1)
|
||||
return;
|
||||
|
||||
if (options.locationNotIn && options.locationNotIn.indexOf(location) > -1)
|
||||
return;
|
||||
|
||||
measurementNumbers.push(measurementNumber);
|
||||
});
|
||||
|
||||
let lesionType = '';
|
||||
if (typeof options.isNodal === 'boolean') {
|
||||
lesionType = options.isNodal ? 'nodal ' : 'extranodal ';
|
||||
}
|
||||
|
||||
let message;
|
||||
if (measurementNumbers.length > options.limit) {
|
||||
const increment = options.newTarget ? 'new ' : '';
|
||||
const plural = options.limit === 1 ? '' : 's';
|
||||
const amount = options.limit === 0 ? '' : `more than ${options.limit}`;
|
||||
message =
|
||||
options.message ||
|
||||
`The study should not have ${amount} ${increment}${lesionType}target${plural}.`;
|
||||
}
|
||||
|
||||
return this.generateResponse(message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
import { BaseCriterion } from './BaseCriterion';
|
||||
|
||||
export const MaxTargetsPerOrganSchema = {
|
||||
type: 'object',
|
||||
properties: {
|
||||
limit: {
|
||||
label: 'Max targets allowed per organ',
|
||||
type: 'integer',
|
||||
minimum: 1,
|
||||
},
|
||||
newTarget: {
|
||||
label: 'Flag to evaluate only new targets',
|
||||
type: 'boolean',
|
||||
},
|
||||
isNodal: {
|
||||
label: 'Filter to evaluate only nodal or extranodal measurements',
|
||||
type: 'boolean'
|
||||
},
|
||||
message: {
|
||||
label: 'Message to be displayed in case of nonconformity',
|
||||
type: 'string',
|
||||
}
|
||||
},
|
||||
required: ['limit'],
|
||||
};
|
||||
|
||||
/*
|
||||
* MaxTargetsPerOrganCriterion
|
||||
* Check if the number of target measurements per organ exceeded the limit allowed
|
||||
* Options:
|
||||
* limit: Max targets allowed in study
|
||||
* newTarget: Flag to evaluate only new targets (must be evaluated on both)
|
||||
* isNodal: Filter to evaluate only nodal or extranodal measurements
|
||||
* message: Message to be displayed in case of nonconformity
|
||||
*/
|
||||
export class MaxTargetsPerOrganCriterion extends BaseCriterion {
|
||||
constructor(...props) {
|
||||
super(...props);
|
||||
}
|
||||
|
||||
evaluate(data) {
|
||||
const { options } = this;
|
||||
const targetsPerOrgan = {};
|
||||
let measurements = [];
|
||||
|
||||
const newTargetNumbers = this.getNewTargetNumbers(data);
|
||||
data.targets.forEach(target => {
|
||||
const { measurement } = target;
|
||||
const { location, measurementNumber, isSplitLesion, isNodal } = measurement;
|
||||
|
||||
if (isSplitLesion)
|
||||
return;
|
||||
|
||||
if (typeof isNodal === 'boolean' && typeof options.isNodal === 'boolean' && options.isNodal !== isNodal)
|
||||
return;
|
||||
|
||||
if (!targetsPerOrgan[location]) {
|
||||
targetsPerOrgan[location] = new Set();
|
||||
}
|
||||
|
||||
if (!options.newTarget || newTargetNumbers.has(measurementNumber)) {
|
||||
targetsPerOrgan[location].add(measurementNumber);
|
||||
}
|
||||
|
||||
if (targetsPerOrgan[location].size > options.limit) {
|
||||
measurements.push(measurement);
|
||||
}
|
||||
});
|
||||
|
||||
let message;
|
||||
if (measurements.length) {
|
||||
const increment = options.newTarget ? 'new ' : '';
|
||||
message =
|
||||
options.message ||
|
||||
`Each organ should not have more than ${
|
||||
options.limit
|
||||
} ${increment}targets.`;
|
||||
}
|
||||
|
||||
return this.generateResponse(message, measurements);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
import { BaseCriterion } from './BaseCriterion';
|
||||
|
||||
export const MeasurementsLengthSchema = {
|
||||
type: 'object',
|
||||
properties: {
|
||||
longAxis: {
|
||||
label: 'Minimum length of long axis',
|
||||
type: 'number',
|
||||
minimum: 0,
|
||||
},
|
||||
shortAxis: {
|
||||
label: 'Minimum length of short axis',
|
||||
type: 'number',
|
||||
minimum: 0,
|
||||
},
|
||||
longAxisSliceThicknessMultiplier: {
|
||||
label: 'Length of long axis multiplier',
|
||||
type: 'number',
|
||||
minimum: 0,
|
||||
},
|
||||
shortAxisSliceThicknessMultiplier: {
|
||||
label: 'Length of short axis multiplier',
|
||||
type: 'number',
|
||||
minimum: 0,
|
||||
},
|
||||
modalityIn: {
|
||||
label:
|
||||
'Filter to evaluate only measurements with the specified modalities',
|
||||
type: 'array',
|
||||
items: {
|
||||
type: 'string',
|
||||
},
|
||||
minItems: 1,
|
||||
uniqueItems: true,
|
||||
},
|
||||
modalityNotIn: {
|
||||
label:
|
||||
'Filter to evaluate only measurements without the specified modalities',
|
||||
type: 'array',
|
||||
items: {
|
||||
type: 'string',
|
||||
},
|
||||
minItems: 1,
|
||||
uniqueItems: true,
|
||||
},
|
||||
locationIn: {
|
||||
label:
|
||||
'Filter to evaluate only measurements with the specified locations',
|
||||
type: 'array',
|
||||
items: {
|
||||
type: 'string',
|
||||
},
|
||||
minItems: 1,
|
||||
uniqueItems: true,
|
||||
},
|
||||
locationNotIn: {
|
||||
label:
|
||||
'Filter to evaluate only measurements without the specified locations',
|
||||
type: 'array',
|
||||
items: {
|
||||
type: 'string',
|
||||
},
|
||||
minItems: 1,
|
||||
uniqueItems: true,
|
||||
},
|
||||
isNodal: {
|
||||
label: 'Filter to evaluate only nodal or extranodal measurements',
|
||||
type: 'boolean'
|
||||
},
|
||||
message: {
|
||||
label: 'Message to be displayed in case of nonconformity',
|
||||
type: 'string',
|
||||
},
|
||||
},
|
||||
anyOf: [
|
||||
{ required: ['message', 'longAxis'] },
|
||||
{ required: ['message', 'shortAxis'] },
|
||||
{ required: ['message', 'longAxisSliceThicknessMultiplier'] },
|
||||
{ required: ['message', 'shortAxisSliceThicknessMultiplier'] },
|
||||
],
|
||||
};
|
||||
|
||||
/*
|
||||
* MeasurementsLengthCriterion
|
||||
* Check the measurements of all bidirectional tools based on
|
||||
* short axis, long axis, modalities, location and slice thickness
|
||||
* Options:
|
||||
* longAxis: Minimum length of long axis
|
||||
* shortAxis: Minimum length of short axis
|
||||
* longAxisSliceThicknessMultiplier: Length of long axis multiplier
|
||||
* shortAxisSliceThicknessMultiplier: Length of short axis multiplier
|
||||
* modalityIn: Filter to evaluate only measurements with the specified modalities
|
||||
* modalityNotIn: Filter to evaluate only measurements without the specified modalities
|
||||
* locationIn: Filter to evaluate only measurements with the specified locations
|
||||
* locationNotIn: Filter to evaluate only measurements without the specified locations
|
||||
* isNodal: Filter to evaluate only nodal or extranodal measurements
|
||||
* message: Message to be displayed in case of nonconformity
|
||||
*/
|
||||
export class MeasurementsLengthCriterion extends BaseCriterion {
|
||||
constructor(...props) {
|
||||
super(...props);
|
||||
}
|
||||
|
||||
evaluate(data) {
|
||||
let message;
|
||||
let measurements = [];
|
||||
const { options } = this;
|
||||
const longMultiplier = options.longAxisSliceThicknessMultiplier;
|
||||
const shortMultiplier = options.shortAxisSliceThicknessMultiplier;
|
||||
|
||||
data.targets.forEach(item => {
|
||||
const { metadata, measurement } = item;
|
||||
const { location } = measurement;
|
||||
|
||||
let { longestDiameter, shortestDiameter, isNodal } = measurement;
|
||||
if (measurement.childToolsCount) {
|
||||
const child = measurement.bidirectional;
|
||||
longestDiameter = (child && child.longestDiameter) || 0;
|
||||
shortestDiameter = (child && child.shortestDiameter) || 0;
|
||||
}
|
||||
|
||||
const { sliceThickness } = metadata;
|
||||
const modality = (metadata.getRawValue('x00080060') || '').toUpperCase();
|
||||
|
||||
// Stop here if the measurement does not match the modality and location filters
|
||||
if (typeof isNodal === 'boolean' && typeof options.isNodal === 'boolean' && options.isNodal !== isNodal)
|
||||
return;
|
||||
if (options.locationIn && options.locationIn.indexOf(location) === -1)
|
||||
return;
|
||||
if (options.modalityIn && options.modalityIn.indexOf(modality) === -1)
|
||||
return;
|
||||
if (options.locationNotIn && options.locationNotIn.indexOf(location) > -1)
|
||||
return;
|
||||
if (options.modalityNotIn && options.modalityNotIn.indexOf(modality) > -1)
|
||||
return;
|
||||
|
||||
// Check the measurement length
|
||||
const failed =
|
||||
(options.longAxis && longestDiameter < options.longAxis) ||
|
||||
(options.shortAxis && shortestDiameter < options.shortAxis) ||
|
||||
(longMultiplier &&
|
||||
!isNaN(sliceThickness) &&
|
||||
longestDiameter < longMultiplier * sliceThickness) ||
|
||||
(shortMultiplier &&
|
||||
!isNaN(sliceThickness) &&
|
||||
shortestDiameter < shortMultiplier * sliceThickness);
|
||||
|
||||
// Mark this measurement as invalid if some of the checks have failed
|
||||
if (failed) {
|
||||
measurements.push(measurement);
|
||||
}
|
||||
});
|
||||
|
||||
// Use the options' message if some measurement is invalid
|
||||
if (measurements.length) {
|
||||
message = options.message;
|
||||
}
|
||||
|
||||
return this.generateResponse(message, measurements);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import { BaseCriterion } from './BaseCriterion';
|
||||
|
||||
export const ModalitySchema = {
|
||||
type: 'object',
|
||||
properties: {
|
||||
method: {
|
||||
label: 'Specify if it\'s goinig to "allow" or "deny" the modalities',
|
||||
type: 'string',
|
||||
enum: ['allow', 'deny'],
|
||||
},
|
||||
measurementTypes: {
|
||||
label: 'List of measurement types that will be evaluated',
|
||||
type: 'array',
|
||||
items: {
|
||||
type: 'string',
|
||||
},
|
||||
minItems: 1,
|
||||
uniqueItems: true,
|
||||
},
|
||||
modalities: {
|
||||
label: 'List of allowed/denied modalities',
|
||||
type: 'array',
|
||||
items: {
|
||||
type: 'string',
|
||||
},
|
||||
minItems: 1,
|
||||
uniqueItems: true,
|
||||
},
|
||||
},
|
||||
required: ['method', 'modalities'],
|
||||
};
|
||||
|
||||
/*
|
||||
* ModalityCriteria
|
||||
* Check if a modality is allowed or denied
|
||||
* Options:
|
||||
* method (string): Specify if it\'s goinig to "allow" or "deny" the modalities
|
||||
* measurementTypes (string[]): List of measurement types that will be evaluated
|
||||
* modalities (string[]): List of allowed/denied modalities
|
||||
*/
|
||||
export class ModalityCriterion extends BaseCriterion {
|
||||
constructor(...props) {
|
||||
super(...props);
|
||||
}
|
||||
|
||||
evaluate(data) {
|
||||
const measurementTypes = this.options.measurementTypes || ['targets'];
|
||||
const modalitiesSet = new Set(this.options.modalities);
|
||||
const validationMethod = this.options.method;
|
||||
const measurements = [];
|
||||
const invalidModalities = new Set();
|
||||
let message;
|
||||
|
||||
measurementTypes.forEach(measurementType => {
|
||||
const items = data[measurementType];
|
||||
|
||||
items.forEach(item => {
|
||||
const { measurement, metadata } = item;
|
||||
const modality = (
|
||||
metadata.getRawValue('x00080060') || ''
|
||||
).toUpperCase();
|
||||
|
||||
if (
|
||||
(validationMethod === 'allow' && !modalitiesSet.has(modality)) ||
|
||||
(validationMethod === 'deny' && modalitiesSet.has(modality))
|
||||
) {
|
||||
measurements.push(measurement);
|
||||
invalidModalities.add(modality);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
if (measurements.length) {
|
||||
const uniqueModalities = Array.from(invalidModalities);
|
||||
const uniqueModalitiesText = uniqueModalities.join(', ');
|
||||
const modalityText =
|
||||
uniqueModalities.length > 1 ? 'modalities' : 'modality';
|
||||
|
||||
message = `The ${modalityText} ${uniqueModalitiesText} should not be used as a method of measurement`;
|
||||
}
|
||||
|
||||
return this.generateResponse(message, measurements);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { BaseCriterion } from './BaseCriterion';
|
||||
|
||||
export const NonTargetResponseSchema = {
|
||||
type: 'object',
|
||||
};
|
||||
|
||||
/* NonTargetResponseCriterion
|
||||
* Check if the there are non-target measurements with response different than "present" on baseline
|
||||
*/
|
||||
export class NonTargetResponseCriterion extends BaseCriterion {
|
||||
constructor(...props) {
|
||||
super(...props);
|
||||
}
|
||||
|
||||
evaluate(data) {
|
||||
const items = data.nonTargets;
|
||||
const measurements = [];
|
||||
let message;
|
||||
|
||||
items.forEach(item => {
|
||||
const measurement = item.measurement;
|
||||
const response = (measurement.response || '').toLowerCase();
|
||||
|
||||
if (response !== 'present') {
|
||||
measurements.push(measurement);
|
||||
}
|
||||
});
|
||||
|
||||
if (measurements.length) {
|
||||
message = 'Non-targets can only be assessed as "present"';
|
||||
}
|
||||
|
||||
return this.generateResponse(message, measurements);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import { BaseCriterion } from './BaseCriterion';
|
||||
|
||||
export const TargetTypeSchema = {
|
||||
type: 'object',
|
||||
};
|
||||
|
||||
/* TargetTypeCriterion
|
||||
* Check if the there are non-bidirectional target measurements on baseline
|
||||
*/
|
||||
export class TargetTypeCriterion extends BaseCriterion {
|
||||
constructor(...props) {
|
||||
super(...props);
|
||||
}
|
||||
|
||||
evaluate(data) {
|
||||
const items = data.targets;
|
||||
const measurements = [];
|
||||
let message;
|
||||
|
||||
items.forEach(item => {
|
||||
const measurement = item.measurement;
|
||||
|
||||
if (
|
||||
measurement.toolType !== 'Bidirectional' &&
|
||||
!measurement.bidirectional
|
||||
) {
|
||||
measurements.push(measurement);
|
||||
}
|
||||
});
|
||||
|
||||
if (measurements.length) {
|
||||
message =
|
||||
'Target lesions must have measurements (cannot be assessed as CR, UN/NE, EX)';
|
||||
}
|
||||
|
||||
return this.generateResponse(message, measurements);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
export * from './Location';
|
||||
export * from './MaxTargetsPerOrgan';
|
||||
export * from './MaxTargets';
|
||||
export * from './MeasurementsLength';
|
||||
export * from './Modality';
|
||||
export * from './NonTargetResponse';
|
||||
export * from './TargetType';
|
||||
@@ -0,0 +1,3 @@
|
||||
import * as recistEvaluation from './recist.json';
|
||||
|
||||
export const recist11 = recistEvaluation;
|
||||
@@ -0,0 +1,38 @@
|
||||
{
|
||||
"both": {
|
||||
"Location": {}
|
||||
},
|
||||
"baseline": {
|
||||
"TargetType": {},
|
||||
"MaxTargetsPerOrgan": {
|
||||
"limit": 2
|
||||
},
|
||||
"MaxTargets": {
|
||||
"limit": 5
|
||||
},
|
||||
"MeasurementsLength": [
|
||||
{
|
||||
"longAxis": 10,
|
||||
"longAxisSliceThicknessMultiplier": 2,
|
||||
"modalityIn": ["CT", "MR"],
|
||||
"locationNotIn": ["Lymph Node"],
|
||||
"message": "Extranodal lesions must be >= 10mm long axis AND >= double the acquisition slice thickness by CT and MR"
|
||||
},
|
||||
{
|
||||
"shortAxis": 20,
|
||||
"longAxis": 20,
|
||||
"modalityIn": ["PX", "XA"],
|
||||
"locationNotIn": ["Lymph Node"],
|
||||
"message": "Extranodal lesions must be >= 20mm on chest x-ray (although x-rays rarely used for clinical trial assessment)"
|
||||
},
|
||||
{
|
||||
"shortAxis": 15,
|
||||
"shortAxisSliceThicknessMultiplier": 2,
|
||||
"modalityIn": ["CT", "MR"],
|
||||
"locationIn": ["Lymph Node"],
|
||||
"message": "Nodal lesions must be >= 15mm short axis AND >= double the acquisition slice thickness by CT and MR"
|
||||
}
|
||||
]
|
||||
},
|
||||
"followup": {}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
import ConformanceCriteria from './ConformanceCriteria';
|
||||
|
||||
export { ConformanceCriteria };
|
||||
@@ -0,0 +1,36 @@
|
||||
import log from '../log';
|
||||
|
||||
export const retrieveMeasurements = (patientId, timepointIds) => {
|
||||
log.error('retrieveMeasurements');
|
||||
return Promise.resolve();
|
||||
};
|
||||
|
||||
export const storeMeasurements = (measurementData, timepointIds) => {
|
||||
log.error('storeMeasurements');
|
||||
return Promise.resolve();
|
||||
};
|
||||
|
||||
export const retrieveTimepoints = filter => {
|
||||
log.error('retrieveTimepoints');
|
||||
return Promise.resolve();
|
||||
};
|
||||
|
||||
export const storeTimepoints = timepointData => {
|
||||
log.error('storeTimepoints');
|
||||
return Promise.resolve();
|
||||
};
|
||||
|
||||
export const updateTimepoint = (timepointData, query) => {
|
||||
log.error('updateTimepoint');
|
||||
return Promise.resolve();
|
||||
};
|
||||
|
||||
export const removeTimepoint = timepointId => {
|
||||
log.error('removeTimepoint');
|
||||
return Promise.resolve();
|
||||
};
|
||||
|
||||
export const disassociateStudy = (timepointIds, studyInstanceUid) => {
|
||||
log.error('disassociateStudy');
|
||||
return Promise.resolve();
|
||||
};
|
||||
@@ -0,0 +1,28 @@
|
||||
import './configuration';
|
||||
|
||||
import * as tools from './tools';
|
||||
|
||||
import { MeasurementApi, TimepointApi } from './classes';
|
||||
|
||||
import { ConformanceCriteria } from './conformance';
|
||||
import MeasurementHandlers from './measurementHandlers';
|
||||
import getDescription from './lib/getDescription';
|
||||
import getImageAttributes from './lib/getImageAttributes';
|
||||
import getImageIdForImagePath from './lib/getImageIdForImagePath';
|
||||
import getLabel from './lib/getLabel';
|
||||
import ltTools from './ltTools';
|
||||
|
||||
const measurements = {
|
||||
TimepointApi,
|
||||
MeasurementApi,
|
||||
ConformanceCriteria,
|
||||
MeasurementHandlers,
|
||||
ltTools,
|
||||
tools,
|
||||
getLabel,
|
||||
getDescription,
|
||||
getImageAttributes,
|
||||
getImageIdForImagePath,
|
||||
};
|
||||
|
||||
export default measurements;
|
||||
@@ -0,0 +1,3 @@
|
||||
export default function(measurement) {
|
||||
return measurement.description;
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import cornerstone from 'cornerstone-core';
|
||||
|
||||
export default function(element) {
|
||||
// Get the Cornerstone imageId
|
||||
const enabledElement = cornerstone.getEnabledElement(element);
|
||||
const imageId = enabledElement.image.imageId;
|
||||
|
||||
// Get studyInstanceUid & patientId
|
||||
const study = cornerstone.metaData.get('study', imageId);
|
||||
const studyInstanceUid = study.studyInstanceUid;
|
||||
const patientId = study.patientId;
|
||||
|
||||
// Get seriesInstanceUid
|
||||
const series = cornerstone.metaData.get('series', imageId);
|
||||
const seriesInstanceUid = series.seriesInstanceUid;
|
||||
|
||||
// Get sopInstanceUid
|
||||
const sopInstance = cornerstone.metaData.get('instance', imageId);
|
||||
const sopInstanceUid = sopInstance.sopInstanceUid;
|
||||
const frameIndex = sopInstance.frame || 0;
|
||||
|
||||
const imagePath = [
|
||||
studyInstanceUid,
|
||||
seriesInstanceUid,
|
||||
sopInstanceUid,
|
||||
frameIndex,
|
||||
].join('_');
|
||||
|
||||
return {
|
||||
patientId,
|
||||
studyInstanceUid,
|
||||
seriesInstanceUid,
|
||||
sopInstanceUid,
|
||||
frameIndex,
|
||||
imagePath,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import studyMetadataManager from '../../utils/studyMetadataManager';
|
||||
|
||||
export default function(imagePath, thumbnail = false) {
|
||||
const [
|
||||
studyInstanceUid,
|
||||
seriesInstanceUid,
|
||||
sopInstanceUid,
|
||||
frameIndex,
|
||||
] = imagePath.split('_');
|
||||
const studyMetadata = studyMetadataManager.get(studyInstanceUid);
|
||||
const series = studyMetadata.getSeriesByUID(seriesInstanceUid);
|
||||
const instance = series.getInstanceByUID(sopInstanceUid);
|
||||
return instance.getImageId(frameIndex, thumbnail);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
export default function(measurement) {
|
||||
if (!measurement) {
|
||||
return;
|
||||
}
|
||||
|
||||
switch (measurement.toolType) {
|
||||
case 'Bidirectional':
|
||||
case 'TargetCR':
|
||||
case 'TargetNE':
|
||||
case 'TargetUN':
|
||||
return `Target ${measurement.lesionNamingNumber}`;
|
||||
case 'NonTarget':
|
||||
return `Non-Target ${measurement.lesionNamingNumber}`;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { targets } from './toolGroups/targets';
|
||||
import { nonTargets } from './toolGroups/nonTargets';
|
||||
import { temp } from './toolGroups/temp';
|
||||
import cloneDeep from 'lodash.clonedeep';
|
||||
|
||||
const ltTools = cloneDeep([targets, nonTargets, temp]);
|
||||
|
||||
ltTools.forEach(toolGroup => {
|
||||
toolGroup.childTools.forEach(tool => {
|
||||
tool.toolGroup = toolGroup.id;
|
||||
});
|
||||
});
|
||||
|
||||
export default ltTools;
|
||||
@@ -0,0 +1,98 @@
|
||||
import cornerstone from 'cornerstone-core';
|
||||
import { MeasurementApi } from '../classes';
|
||||
import log from '../../log';
|
||||
import user from '../../user';
|
||||
import getImageAttributes from '../lib/getImageAttributes';
|
||||
import getLabel from '../lib/getLabel';
|
||||
|
||||
export default function({ eventData, tool, toolGroupId, toolGroup }) {
|
||||
const measurementApi = MeasurementApi.Instance;
|
||||
if (!measurementApi) {
|
||||
log.warn('Measurement API is not initialized');
|
||||
}
|
||||
|
||||
const { measurementData } = eventData;
|
||||
|
||||
const collection = measurementApi.tools[tool.parentTool];
|
||||
|
||||
// Stop here if the tool data shall not be persisted (e.g. temp tools)
|
||||
if (!collection) return;
|
||||
|
||||
// Stop here if there's no measurement data or if it was cancelled
|
||||
if (!measurementData || measurementData.cancelled) return;
|
||||
|
||||
log.info('CornerstoneToolsMeasurementAdded');
|
||||
|
||||
const imageAttributes = getImageAttributes(eventData.element);
|
||||
|
||||
const additionalProperties = Object.assign(imageAttributes, {
|
||||
userId: user.getUserId(),
|
||||
});
|
||||
|
||||
const childMeasurement = Object.assign(
|
||||
{},
|
||||
measurementData,
|
||||
additionalProperties
|
||||
);
|
||||
|
||||
const parentMeasurement = collection.find(
|
||||
t =>
|
||||
t.toolType === tool.parentTool &&
|
||||
t.patientId === imageAttributes.patientId &&
|
||||
t[tool.attribute] === null
|
||||
);
|
||||
|
||||
// Check if a measurement to fit this child tool already exists
|
||||
if (parentMeasurement) {
|
||||
const key = tool.attribute;
|
||||
|
||||
// Add the createdAt attribute
|
||||
childMeasurement.createdAt = new Date();
|
||||
|
||||
// Update the parent measurement
|
||||
parentMeasurement[key] = childMeasurement;
|
||||
parentMeasurement.childToolsCount =
|
||||
(parentMeasurement.childToolsCount || 0) + 1;
|
||||
measurementApi.updateMeasurement(tool.parentTool, parentMeasurement);
|
||||
|
||||
// Update the measurementData ID and lesionNamingNumber
|
||||
measurementData._id = parentMeasurement._id;
|
||||
measurementData.lesionNamingNumber = parentMeasurement.lesionNamingNumber;
|
||||
} else {
|
||||
const measurement = {
|
||||
toolType: tool.parentTool,
|
||||
lesionNamingNumber: measurementData.lesionNamingNumber,
|
||||
userId: user.getUserId(),
|
||||
patientId: imageAttributes.patientId,
|
||||
studyInstanceUid: imageAttributes.studyInstanceUid,
|
||||
};
|
||||
|
||||
measurement[tool.attribute] = Object.assign(
|
||||
{},
|
||||
measurementData,
|
||||
additionalProperties
|
||||
);
|
||||
|
||||
const addedMeasurement = measurementApi.addMeasurement(
|
||||
tool.parentTool,
|
||||
measurement
|
||||
);
|
||||
Object.assign(measurementData, addedMeasurement);
|
||||
}
|
||||
|
||||
const measurementLabel = getLabel(measurementData);
|
||||
if (measurementLabel) {
|
||||
measurementData.labels = [measurementLabel];
|
||||
}
|
||||
|
||||
// TODO: This is very hacky, but will work for now
|
||||
cornerstone.getEnabledElements().forEach(enabledElement => {
|
||||
cornerstone.updateImage(enabledElement.element);
|
||||
});
|
||||
|
||||
// TODO: Notify about the last activated measurement
|
||||
|
||||
if (MeasurementApi.isToolIncluded(tool)) {
|
||||
// TODO: Notify that viewer suffered changes
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import cornerstone from 'cornerstone-core';
|
||||
import { MeasurementApi } from '../classes';
|
||||
import log from '../../log';
|
||||
|
||||
export default function({ eventData, tool, toolGroupId, toolGroup }) {
|
||||
const measurementApi = MeasurementApi.Instance;
|
||||
if (!measurementApi) {
|
||||
log.warn('Measurement API is not initialized');
|
||||
}
|
||||
|
||||
const { measurementData } = eventData;
|
||||
|
||||
const collection = measurementApi.tools[tool.parentTool];
|
||||
|
||||
// Stop here if the tool data shall not be persisted (e.g. temp tools)
|
||||
if (!collection) return;
|
||||
|
||||
log.info('CornerstoneToolsMeasurementModified');
|
||||
|
||||
const measurement = collection.find(t => t._id === measurementData._id);
|
||||
let childMeasurement = measurement && measurement[tool.attribute];
|
||||
|
||||
// Stop here if the measurement is already deleted
|
||||
if (!childMeasurement) return;
|
||||
|
||||
childMeasurement = Object.assign(childMeasurement, measurementData);
|
||||
childMeasurement.viewport = cornerstone.getViewport(eventData.element);
|
||||
|
||||
// Update the parent measurement
|
||||
measurement[tool.attribute] = childMeasurement;
|
||||
measurementApi.updateMeasurement(tool.parentTool, measurement);
|
||||
|
||||
// TODO: Notify about the last activated measurement
|
||||
|
||||
if (MeasurementApi.isToolIncluded(tool)) {
|
||||
// TODO: Notify that viewer suffered changes
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import cornerstone from 'cornerstone-core';
|
||||
import { MeasurementApi } from '../classes';
|
||||
import log from '../../log';
|
||||
|
||||
export default function({ eventData, tool, toolGroupId, toolGroup }) {
|
||||
log.info('CornerstoneToolsMeasurementRemoved');
|
||||
const { measurementData } = eventData;
|
||||
|
||||
const measurementApi = MeasurementApi.Instance;
|
||||
if (!measurementApi) {
|
||||
log.warn('Measurement API is not initialized');
|
||||
}
|
||||
|
||||
const collection = measurementApi.tools[tool.parentTool];
|
||||
|
||||
// Stop here if the tool data shall not be persisted (e.g. temp tools)
|
||||
if (!collection) return;
|
||||
|
||||
const measurementIndex = collection.findIndex(
|
||||
t => t._id === measurementData._id
|
||||
);
|
||||
const measurement =
|
||||
measurementIndex > -1 ? collection[measurementIndex] : null;
|
||||
|
||||
// Stop here if the measurement is already gone or never existed
|
||||
if (!measurement) return;
|
||||
|
||||
if (measurement.childToolsCount === 1) {
|
||||
// Remove the measurement
|
||||
collection.splice(measurementIndex, 1);
|
||||
measurementApi.onMeasurementRemoved(tool.parentTool, measurement);
|
||||
} else {
|
||||
// Update the measurement
|
||||
measurement[tool.attribute] = null;
|
||||
measurement.childToolsCount = (measurement.childToolsCount || 0) - 1;
|
||||
measurementApi.updateMeasurement(tool.parentTool, measurement);
|
||||
}
|
||||
|
||||
// TODO: This is very hacky, but will work for now
|
||||
cornerstone.getEnabledElements().forEach(enabledElement => {
|
||||
cornerstone.updateImage(enabledElement.element);
|
||||
});
|
||||
|
||||
if (MeasurementApi.isToolIncluded(tool)) {
|
||||
// TODO: Notify that viewer suffered changes
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import cornerstone from 'cornerstone-core';
|
||||
import { MeasurementApi } from '../classes';
|
||||
import log from '../../log';
|
||||
import user from '../../user';
|
||||
import getImageAttributes from '../lib/getImageAttributes';
|
||||
import getLabel from '../lib/getLabel';
|
||||
|
||||
export default function handleSingleMeasurementAdded({ eventData, tool }) {
|
||||
const measurementApi = MeasurementApi.Instance;
|
||||
if (!measurementApi) {
|
||||
log.warn('Measurement API is not initialized');
|
||||
}
|
||||
|
||||
const { measurementData, toolType } = eventData;
|
||||
|
||||
const collection = measurementApi.tools[toolType];
|
||||
|
||||
// Stop here if the tool data shall not be persisted (e.g. temp tools)
|
||||
if (!collection) return;
|
||||
|
||||
// Stop here if there's no measurement data or if it was cancelled
|
||||
if (!measurementData || measurementData.cancelled) return;
|
||||
|
||||
log.info('CornerstoneToolsMeasurementAdded');
|
||||
|
||||
const imageAttributes = getImageAttributes(eventData.element);
|
||||
const measurement = Object.assign({}, measurementData, imageAttributes, {
|
||||
lesionNamingNumber: measurementData.lesionNamingNumber,
|
||||
userId: user.getUserId(),
|
||||
toolType,
|
||||
});
|
||||
|
||||
const addedMeasurement = measurementApi.addMeasurement(toolType, measurement);
|
||||
Object.assign(measurementData, addedMeasurement);
|
||||
|
||||
const measurementLabel = getLabel(measurementData);
|
||||
if (measurementLabel) {
|
||||
measurementData.labels = [measurementLabel];
|
||||
}
|
||||
|
||||
// TODO: This is very hacky, but will work for now
|
||||
cornerstone.getEnabledElements().forEach(enabledElement => {
|
||||
cornerstone.updateImage(enabledElement.element);
|
||||
});
|
||||
|
||||
// TODO: Notify about the last activated measurement
|
||||
|
||||
if (MeasurementApi.isToolIncluded(tool)) {
|
||||
// TODO: Notify that viewer suffered changes
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import cornerstone from 'cornerstone-core';
|
||||
import { MeasurementApi } from '../classes';
|
||||
import log from '../../log';
|
||||
|
||||
export default function({ eventData, tool, toolGroupId, toolGroup }) {
|
||||
const measurementApi = MeasurementApi.Instance;
|
||||
if (!measurementApi) {
|
||||
log.warn('Measurement API is not initialized');
|
||||
}
|
||||
|
||||
const { measurementData, toolType } = eventData;
|
||||
|
||||
const collection = measurementApi.tools[toolType];
|
||||
|
||||
// Stop here if the tool data shall not be persisted (e.g. temp tools)
|
||||
if (!collection) return;
|
||||
|
||||
log.info('CornerstoneToolsMeasurementModified');
|
||||
let measurement = collection.find(t => t._id === measurementData._id);
|
||||
|
||||
// Stop here if the measurement is already deleted
|
||||
if (!measurement) return;
|
||||
|
||||
measurement = Object.assign(measurement, measurementData);
|
||||
measurement.viewport = cornerstone.getViewport(eventData.element);
|
||||
|
||||
measurementApi.updateMeasurement(toolType, measurement);
|
||||
|
||||
// TODO: Notify about the last activated measurement
|
||||
|
||||
if (MeasurementApi.isToolIncluded(tool)) {
|
||||
// TODO: Notify that viewer suffered changes
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import cornerstone from 'cornerstone-core';
|
||||
import { MeasurementApi } from '../classes';
|
||||
import log from '../../log';
|
||||
|
||||
export default function handleSingleMeasurementRemoved({
|
||||
eventData,
|
||||
tool,
|
||||
toolGroupId,
|
||||
toolGroup,
|
||||
}) {
|
||||
log.info('CornerstoneToolsMeasurementRemoved');
|
||||
const { measurementData, toolType } = eventData;
|
||||
|
||||
const measurementApi = MeasurementApi.Instance;
|
||||
if (!measurementApi) {
|
||||
log.warn('Measurement API is not initialized');
|
||||
}
|
||||
|
||||
const collection = measurementApi.tools[toolType];
|
||||
|
||||
// Stop here if the tool data shall not be persisted (e.g. temp tools)
|
||||
if (!collection) return;
|
||||
|
||||
const measurementTypeId = measurementApi.toolsGroupsMap[toolType];
|
||||
const measurement = collection.find(t => t._id === measurementData._id);
|
||||
|
||||
// Stop here if the measurement is already gone or never existed
|
||||
if (!measurement) return;
|
||||
|
||||
// Remove all the measurements with the given type and number
|
||||
const { lesionNamingNumber, timepointId } = measurement;
|
||||
measurementApi.deleteMeasurements(toolType, measurementTypeId, {
|
||||
lesionNamingNumber,
|
||||
timepointId,
|
||||
});
|
||||
|
||||
// TODO: This is very hacky, but will work for now
|
||||
cornerstone.getEnabledElements().forEach(enabledElement => {
|
||||
cornerstone.updateImage(enabledElement.element);
|
||||
});
|
||||
|
||||
if (MeasurementApi.isToolIncluded(tool)) {
|
||||
// TODO: Notify that viewer suffered changes
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
import { MeasurementApi } from '../classes';
|
||||
import handleSingleMeasurementAdded from './handleSingleMeasurementAdded';
|
||||
import handleChildMeasurementAdded from './handleChildMeasurementAdded';
|
||||
import handleSingleMeasurementModified from './handleSingleMeasurementModified';
|
||||
import handleChildMeasurementModified from './handleChildMeasurementModified';
|
||||
import handleSingleMeasurementRemoved from './handleSingleMeasurementRemoved';
|
||||
import handleChildMeasurementRemoved from './handleChildMeasurementRemoved';
|
||||
|
||||
const getEventData = event => {
|
||||
const eventData = event.detail;
|
||||
if (eventData.toolName) {
|
||||
eventData.toolType = eventData.toolName;
|
||||
}
|
||||
|
||||
return eventData;
|
||||
};
|
||||
|
||||
const MeasurementHandlers = {
|
||||
handleSingleMeasurementAdded,
|
||||
handleChildMeasurementAdded,
|
||||
handleSingleMeasurementModified,
|
||||
handleChildMeasurementModified,
|
||||
handleSingleMeasurementRemoved,
|
||||
handleChildMeasurementRemoved,
|
||||
|
||||
onAdded(event) {
|
||||
const eventData = getEventData(event);
|
||||
const { toolType } = eventData;
|
||||
const {
|
||||
toolGroupId,
|
||||
toolGroup,
|
||||
tool,
|
||||
} = MeasurementApi.getToolConfiguration(toolType);
|
||||
const params = {
|
||||
eventData,
|
||||
tool,
|
||||
toolGroupId,
|
||||
toolGroup,
|
||||
};
|
||||
|
||||
if (!tool) return;
|
||||
|
||||
if (tool.parentTool) {
|
||||
handleChildMeasurementAdded(params);
|
||||
} else {
|
||||
handleSingleMeasurementAdded(params);
|
||||
}
|
||||
},
|
||||
|
||||
onModified(event) {
|
||||
const eventData = getEventData(event);
|
||||
const { toolType } = eventData;
|
||||
const {
|
||||
toolGroupId,
|
||||
toolGroup,
|
||||
tool,
|
||||
} = MeasurementApi.getToolConfiguration(toolType);
|
||||
const params = {
|
||||
eventData,
|
||||
tool,
|
||||
toolGroupId,
|
||||
toolGroup,
|
||||
};
|
||||
|
||||
if (!tool) return;
|
||||
|
||||
if (tool.parentTool) {
|
||||
handleChildMeasurementModified(params);
|
||||
} else {
|
||||
handleSingleMeasurementModified(params);
|
||||
}
|
||||
},
|
||||
|
||||
onRemoved(event) {
|
||||
const eventData = getEventData(event);
|
||||
const { toolType } = eventData;
|
||||
const {
|
||||
toolGroupId,
|
||||
toolGroup,
|
||||
tool,
|
||||
} = MeasurementApi.getToolConfiguration(toolType);
|
||||
const params = {
|
||||
eventData,
|
||||
tool,
|
||||
toolGroupId,
|
||||
toolGroup,
|
||||
};
|
||||
|
||||
if (!tool) return;
|
||||
|
||||
if (tool.parentTool) {
|
||||
handleChildMeasurementRemoved(params);
|
||||
} else {
|
||||
handleSingleMeasurementRemoved(params);
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
export default MeasurementHandlers;
|
||||
@@ -0,0 +1,16 @@
|
||||
import * as tools from '../tools';
|
||||
|
||||
const childTools = [];
|
||||
Object.keys(tools).forEach(key => childTools.push(tools[key]));
|
||||
|
||||
export const allTools = {
|
||||
id: 'allTools',
|
||||
name: 'Measurements',
|
||||
childTools: childTools,
|
||||
options: {
|
||||
caseProgress: {
|
||||
include: true,
|
||||
evaluate: true,
|
||||
},
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,13 @@
|
||||
import { nonTarget } from '../tools';
|
||||
|
||||
export const nonTargets = {
|
||||
id: 'nonTargets',
|
||||
name: 'Non-Targets',
|
||||
childTools: [nonTarget],
|
||||
options: {
|
||||
caseProgress: {
|
||||
include: true,
|
||||
evaluate: true,
|
||||
},
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,13 @@
|
||||
import { bidirectional, targetCR, targetUN, targetNE } from '../tools';
|
||||
|
||||
export const targets = {
|
||||
id: 'targets',
|
||||
name: 'Targets',
|
||||
childTools: [bidirectional, targetCR, targetUN, targetNE],
|
||||
options: {
|
||||
caseProgress: {
|
||||
include: true,
|
||||
evaluate: true,
|
||||
},
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,26 @@
|
||||
import { length, ellipticalRoi } from '../tools';
|
||||
import cloneDeep from 'lodash.clonedeep';
|
||||
|
||||
const childTools = cloneDeep([length, ellipticalRoi]);
|
||||
|
||||
// Exclude temp tools from case progress
|
||||
childTools.forEach(childTool => {
|
||||
childTool.options = Object.assign({}, childTool.options, {
|
||||
caseProgress: {
|
||||
include: false,
|
||||
evaluate: false,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
export const temp = {
|
||||
id: 'temp',
|
||||
name: 'Temporary',
|
||||
childTools,
|
||||
options: {
|
||||
caseProgress: {
|
||||
include: false,
|
||||
evaluate: false,
|
||||
},
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,23 @@
|
||||
const displayFunction = data => {
|
||||
let text = '';
|
||||
if (data.rAngle) {
|
||||
text = data.rAngle.toFixed(2) + String.fromCharCode(parseInt('00B0', 16));
|
||||
}
|
||||
return text;
|
||||
};
|
||||
|
||||
export const angle = {
|
||||
id: 'Angle',
|
||||
name: 'Angle',
|
||||
toolGroup: 'allTools',
|
||||
cornerstoneToolType: 'Angle',
|
||||
options: {
|
||||
measurementTable: {
|
||||
displayFunction,
|
||||
},
|
||||
caseProgress: {
|
||||
include: true,
|
||||
evaluate: true,
|
||||
},
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,19 @@
|
||||
const displayFunction = data => {
|
||||
return data.text || '';
|
||||
};
|
||||
|
||||
export const arrowAnnotate = {
|
||||
id: 'ArrowAnnotate',
|
||||
name: 'ArrowAnnotate',
|
||||
toolGroup: 'allTools',
|
||||
cornerstoneToolType: 'ArrowAnnotate',
|
||||
options: {
|
||||
measurementTable: {
|
||||
displayFunction,
|
||||
},
|
||||
caseProgress: {
|
||||
include: true,
|
||||
evaluate: true,
|
||||
},
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,24 @@
|
||||
const displayFunction = data => {
|
||||
if (data.shortestDiameter) {
|
||||
// TODO: Make this check criteria again to see if we should display shortest x longest
|
||||
return data.longestDiameter + ' x ' + data.shortestDiameter;
|
||||
}
|
||||
|
||||
return data.longestDiameter;
|
||||
};
|
||||
|
||||
export const bidirectional = {
|
||||
id: 'Bidirectional',
|
||||
name: 'Target',
|
||||
toolGroup: 'allTools',
|
||||
cornerstoneToolType: 'Bidirectional',
|
||||
options: {
|
||||
measurementTable: {
|
||||
displayFunction,
|
||||
},
|
||||
caseProgress: {
|
||||
include: true,
|
||||
evaluate: true,
|
||||
},
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,24 @@
|
||||
const displayFunction = data => {
|
||||
let meanValue = '';
|
||||
const { cachedStats } = data;
|
||||
if (cachedStats && cachedStats.mean) {
|
||||
meanValue = cachedStats.mean.toFixed(2) + ' HU';
|
||||
}
|
||||
return meanValue;
|
||||
};
|
||||
|
||||
export const circleRoi = {
|
||||
id: 'CircleRoi',
|
||||
name: 'Circle',
|
||||
toolGroup: 'allTools',
|
||||
cornerstoneToolType: 'CircleRoi',
|
||||
options: {
|
||||
measurementTable: {
|
||||
displayFunction,
|
||||
},
|
||||
caseProgress: {
|
||||
include: true,
|
||||
evaluate: true,
|
||||
},
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,24 @@
|
||||
const displayFunction = data => {
|
||||
let meanValue = '';
|
||||
const { cachedStats } = data;
|
||||
if (cachedStats && cachedStats.mean) {
|
||||
meanValue = cachedStats.mean.toFixed(2) + ' HU';
|
||||
}
|
||||
return meanValue;
|
||||
};
|
||||
|
||||
export const ellipticalRoi = {
|
||||
id: 'EllipticalRoi',
|
||||
name: 'Ellipse',
|
||||
toolGroup: 'allTools',
|
||||
cornerstoneToolType: 'EllipticalRoi',
|
||||
options: {
|
||||
measurementTable: {
|
||||
displayFunction,
|
||||
},
|
||||
caseProgress: {
|
||||
include: true,
|
||||
evaluate: true,
|
||||
},
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,23 @@
|
||||
const displayFunction = data => {
|
||||
let meanValue = '';
|
||||
if (data.meanStdDev && data.meanStdDev.mean) {
|
||||
meanValue = data.meanStdDev.mean.toFixed(2) + ' HU';
|
||||
}
|
||||
return meanValue;
|
||||
};
|
||||
|
||||
export const freehandMouse = {
|
||||
id: 'FreehandMouse',
|
||||
name: 'Freehand',
|
||||
toolGroup: 'allTools',
|
||||
cornerstoneToolType: 'FreehandMouse',
|
||||
options: {
|
||||
measurementTable: {
|
||||
displayFunction,
|
||||
},
|
||||
caseProgress: {
|
||||
include: true,
|
||||
evaluate: true,
|
||||
},
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,27 @@
|
||||
import { arrowAnnotate } from './arrowAnnotate';
|
||||
import { bidirectional } from './bidirectional';
|
||||
import { ellipticalRoi } from './ellipticalRoi';
|
||||
import { circleRoi } from './circleRoi';
|
||||
import { freehandMouse } from './freehandMouse';
|
||||
import { length } from './length';
|
||||
import { nonTarget } from './nonTarget';
|
||||
import { rectangleRoi } from './rectangleRoi';
|
||||
import { angle } from './angle';
|
||||
import { targetCR } from './targetCR';
|
||||
import { targetNE } from './targetNE';
|
||||
import { targetUN } from './targetUN';
|
||||
|
||||
export {
|
||||
arrowAnnotate,
|
||||
bidirectional,
|
||||
ellipticalRoi,
|
||||
circleRoi,
|
||||
freehandMouse,
|
||||
length,
|
||||
nonTarget,
|
||||
rectangleRoi,
|
||||
angle,
|
||||
targetCR,
|
||||
targetNE,
|
||||
targetUN,
|
||||
};
|
||||
@@ -0,0 +1,23 @@
|
||||
const displayFunction = data => {
|
||||
let lengthValue = '';
|
||||
if (data.length) {
|
||||
lengthValue = data.length.toFixed(2) + ' mm';
|
||||
}
|
||||
return lengthValue;
|
||||
};
|
||||
|
||||
export const length = {
|
||||
id: 'Length',
|
||||
name: 'Length',
|
||||
toolGroup: 'allTools',
|
||||
cornerstoneToolType: 'Length',
|
||||
options: {
|
||||
measurementTable: {
|
||||
displayFunction,
|
||||
},
|
||||
caseProgress: {
|
||||
include: true,
|
||||
evaluate: true,
|
||||
},
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,15 @@
|
||||
export const nonTarget = {
|
||||
id: 'NonTarget',
|
||||
name: 'Non-Target',
|
||||
toolGroup: 'allTools',
|
||||
cornerstoneToolType: 'NonTarget',
|
||||
options: {
|
||||
measurementTable: {
|
||||
displayFunction: data => data.response,
|
||||
},
|
||||
caseProgress: {
|
||||
include: true,
|
||||
evaluate: true,
|
||||
},
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,24 @@
|
||||
const displayFunction = data => {
|
||||
let meanValue = '';
|
||||
const { cachedStats } = data;
|
||||
if (cachedStats && cachedStats.mean) {
|
||||
meanValue = cachedStats.mean.toFixed(2) + ' HU';
|
||||
}
|
||||
return meanValue;
|
||||
};
|
||||
|
||||
export const rectangleRoi = {
|
||||
id: 'RectangleRoi',
|
||||
name: 'Rectangle',
|
||||
toolGroup: 'allTools',
|
||||
cornerstoneToolType: 'RectangleRoi',
|
||||
options: {
|
||||
measurementTable: {
|
||||
displayFunction,
|
||||
},
|
||||
caseProgress: {
|
||||
include: true,
|
||||
evaluate: true,
|
||||
},
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,15 @@
|
||||
export const targetCR = {
|
||||
id: 'TargetCR',
|
||||
name: 'CR Target',
|
||||
toolGroup: 'allTools',
|
||||
cornerstoneToolType: 'TargetCR',
|
||||
options: {
|
||||
measurementTable: {
|
||||
displayFunction: data => data.response,
|
||||
},
|
||||
caseProgress: {
|
||||
include: true,
|
||||
evaluate: true,
|
||||
},
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,15 @@
|
||||
export const targetNE = {
|
||||
id: 'TargetNE',
|
||||
name: 'NE Target',
|
||||
toolGroup: 'allTools',
|
||||
cornerstoneToolType: 'TargetNE',
|
||||
options: {
|
||||
measurementTable: {
|
||||
displayFunction: data => data.response,
|
||||
},
|
||||
caseProgress: {
|
||||
include: true,
|
||||
evaluate: true,
|
||||
},
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,15 @@
|
||||
export const targetUN = {
|
||||
id: 'TargetUN',
|
||||
name: 'UN Target',
|
||||
toolGroup: 'allTools',
|
||||
cornerstoneToolType: 'TargetUN',
|
||||
options: {
|
||||
measurementTable: {
|
||||
displayFunction: data => data.response,
|
||||
},
|
||||
caseProgress: {
|
||||
include: true,
|
||||
evaluate: true,
|
||||
},
|
||||
},
|
||||
};
|
||||
Reference in new issue
Block a user