All files / platform/core/src/services/MeasurementService MeasurementService.ts

53.05% Statements 139/262
30.23% Branches 26/86
50% Functions 25/50
53.17% Lines 134/252

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867                                                                34x                                                                         34x                         34x                         68x                                     34x         34x           34x   34x 34x 34x   34x       34x                                                                                             110x 110x 79x                     2760x       60x 60x 28x     32x   32x                             34x       34x           34x   34x             34x 34x           34x 5231x     34x       34x       34x 34x   34x       36x 36x   36x       2x 2x   2x                           578x       578x       578x       578x       578x       578x             578x 544x   34x                                                                                   2x       2x         2x   2x   2x           2x                         2x         2x   2x         2x         2x 2x 2x 2x     2x                 2x             2x 2x 2x 2x     2x   2x                 2x             2x 2x 2x               2x                         5231x     5231x       5231x 5231x       5231x 5231x 5231x 5231x 84060x   5231x 4892x 4892x   339x     339x 339x 291x     48x                                   48x             48x 48x             48x   48x             48x         48x     37x 37x 26x           11x 11x           11x 11x     48x                                                                                                                     34x 34x     34x 34x 34x 34x                                                         4x   4x       4x               4x 4x       38x   38x 38x   38x     38x                                                                         5233x                   5811x                   5233x                   50x 997x         997x                           34x             34x                                                                                                                           34x         34x        
import log from '../../log';
import guid from '../../utils/guid';
import { PubSubService } from '../_shared/pubSubServiceInterface';
 
/**
 * Measurement source schema
 *
 * @typedef {Object} MeasurementSource
 * @property {number} id -
 * @property {string} name -
 * @property {string} version -
 */
 
/**
 * Measurement schema
 *
 * @typedef {Object} Measurement
 * @property {number} uid -
 * @property {string} SOPInstanceUID -
 * @property {string} FrameOfReferenceUID -
 * @property {string} referenceSeriesUID -
 * @property {string} label -
 * @property {string} description -
 * @property {string} type -
 * @property {string} unit -
 * @property {number} area -
 * @property {Array} points -
 * @property {MeasurementSource} source -
 * @property {boolean} selected -
 */
 
/* Measurement schema keys for object validation. */
const MEASUREMENT_SCHEMA_KEYS = [
  'uid',
  'color',
  'data',
  'getReport',
  'displayText',
  'SOPInstanceUID',
  'FrameOfReferenceUID',
  'referenceStudyUID',
  'referenceSeriesUID',
  'frameNumber',
  'displaySetInstanceUID',
  'label',
  'isLocked',
  'isVisible',
  'description',
  'type',
  'unit',
  'points',
  'source',
  'toolName',
  'metadata',
  // Todo: we shouldn't need to have all these here.
  'area', // TODO: Add concept names instead (descriptor)
  'mean',
  'stdDev',
  'perimeter',
  'length',
  'shortestDiameter',
  'longestDiameter',
  'cachedStats',
  'isSelected',
  'textBox',
  'referencedImageId',
  'isDirty',
];
 
const EVENTS = {
  MEASUREMENT_UPDATED: 'event::measurement_updated',
  INTERNAL_MEASUREMENT_UPDATED: 'event:internal_measurement_updated',
  MEASUREMENT_ADDED: 'event::measurement_added',
  RAW_MEASUREMENT_ADDED: 'event::raw_measurement_added',
  MEASUREMENT_REMOVED: 'event::measurement_removed',
  MEASUREMENTS_CLEARED: 'event::measurements_cleared',
  // Give the viewport a chance to jump to the measurement
  JUMP_TO_MEASUREMENT_VIEWPORT: 'event:jump_to_measurement_viewport',
  // Give the layout a chance to jump to the measurement
  JUMP_TO_MEASUREMENT_LAYOUT: 'event:jump_to_measurement_layout',
};
 
const VALUE_TYPES = {
  ANGLE: 'value_type::polyline',
  POLYLINE: 'value_type::polyline',
  POINT: 'value_type::point',
  BIDIRECTIONAL: 'value_type::shortAxisLongAxis', // TODO -> Discuss with Danny. => just using SCOORD values isn't enough here.
  ELLIPSE: 'value_type::ellipse',
  RECTANGLE: 'value_type::rectangle',
  MULTIPOINT: 'value_type::multipoint',
  CIRCLE: 'value_type::circle',
  ROI_THRESHOLD: 'value_type::roiThreshold',
  ROI_THRESHOLD_MANUAL: 'value_type::roiThresholdManual',
};
 
enum MeasurementChangeType {
  HandlesUpdated = 'HandlesUpdated',
  LabelChange = 'LabelChange',
}
 
export type MeasurementFilter = (measurement) => boolean;
 
/**
 * MeasurementService class that supports source management and measurement management.
 * Sources can be any library that can provide "annotations" (e.g. cornerstone-tools, cornerstone, etc.)
 * The flow, is that by creating a source and mappings (annotation <-> measurement), we
 * can convert back and forth between the two. MeasurementPanel in OHIF uses the measurement service
 * to manage the measurements, and any edit to the measurements will be reflected back at the
 * library level state (e.g. cornerstone-tools, cornerstone, etc.) by converting the
 * edited measurements back to the original annotations and then updating the annotations.
 *
 * Note and Todo: We should be able to support measurements that are composed of multiple
 * annotations, but that is not the case at the moment.
 */
class MeasurementService extends PubSubService {
  public static REGISTRATION = {
    name: 'measurementService',
    altName: 'MeasurementService',
    create: _options => {
      return new MeasurementService();
    },
  };
 
  public static readonly EVENTS = EVENTS;
  public static VALUE_TYPES = VALUE_TYPES;
  public readonly VALUE_TYPES = VALUE_TYPES;
 
  private measurements = new Map();
  private unmappedMeasurements = new Map();
  private isMeasurementDeletedIndividually: boolean;
 
  private sources = {};
  private mappings = {};
 
  constructor() {
    super(EVENTS);
  }
 
  /**
   * Adds the given schema to the measurement service schema list.
   * This method should be used to add custom tool schema to the measurement service.
   * @param {Array} schema schema for validation
   */
  public addMeasurementSchemaKeys(schema): void {
    Iif (!Array.isArray(schema)) {
      schema = [schema];
    }
 
    MEASUREMENT_SCHEMA_KEYS.push(...schema);
  }
 
  /**
   * Adds the given valueType to the measurement service valueType object.
   * This method should be used to add custom valueType to the measurement service.
   * @param {*} valueType
   * @returns
   */
  addValueType(valueType) {
    Iif (VALUE_TYPES[valueType]) {
      return;
    }
 
    // check if valuetype is valid , and if values are strings
    Iif (!valueType || typeof valueType !== 'object') {
      console.warn(`MeasurementService: addValueType: invalid valueType: ${valueType}`);
      return;
    }
 
    Object.keys(valueType).forEach(key => {
      Iif (!VALUE_TYPES[key]) {
        VALUE_TYPES[key] = valueType[key];
      }
    });
  }
 
  /**
   * Gets measurements, optionally filtered by the filter
   * function.
   *
   * @return {Measurement[]} Array of measurements
   */
  public getMeasurements(filter?: MeasurementFilter) {
    const measurements = [...this.measurements.values()];
    return filter
      ? measurements.filter(measurement => filter.call(this, measurement))
      : measurements;
  }
 
  /**
   * Get specific measurement by its uid.
   *
   * @param {string} uid measurement uid
   * @return {Measurement} Measurement instance
   */
  public getMeasurement(measurementUID: string) {
    return this.measurements.get(measurementUID);
  }
 
  public setMeasurementSelected(measurementUID: string, selected: boolean): void {
    const measurement = this.getMeasurement(measurementUID);
    if (!measurement) {
      return;
    }
 
    measurement.isSelected = selected;
 
    this._broadcastEvent(this.EVENTS.MEASUREMENT_UPDATED, {
      source: measurement.source,
      measurement,
      notYetUpdatedAtSource: false,
    });
  }
 
  /**
   * Create a new source.
   *
   * @param {string} name Name of the source
   * @param {string} version Source name
   * @return {MeasurementSource} Measurement source instance
   */
  createSource(name, version) {
    Iif (!name) {
      throw new Error('Source name not provided.');
    }
 
    Iif (!version) {
      throw new Error('Source version not provided.');
    }
 
    // Go over all the keys inside the sources and check if the source
    // name and version matches with the existing sources.
    const sourceKeys = Object.keys(this.sources);
 
    for (let i = 0; i < sourceKeys.length; i++) {
      const source = this.sources[sourceKeys[i]];
      Iif (source.name === name && source.version === version) {
        return source;
      }
    }
 
    const uid = guid();
    const source = {
      uid,
      name,
      version,
    };
 
    source.annotationToMeasurement = (annotationType, annotation, isUpdate = false) => {
      return this.annotationToMeasurement(source, annotationType, annotation, isUpdate);
    };
 
    source.remove = (measurementUID, eventDetails) => {
      return this.remove(measurementUID, source, eventDetails);
    };
 
    source.getAnnotation = (annotationType, measurementId) => {
      return this.getAnnotation(source, annotationType, measurementId);
    };
 
    log.info(`New '${name}@${version}' source added.`);
    this.sources[uid] = source;
 
    return source;
  }
 
  getSource(name, version) {
    const { sources } = this;
    const uid = this._getSourceUID(name, version);
 
    return sources[uid];
  }
 
  getSourceMappings(name, version) {
    const { mappings } = this;
    const uid = this._getSourceUID(name, version);
 
    return mappings[uid];
  }
 
  /**
   * Add a new measurement matching criteria along with mapping functions.
   *
   * @param {MeasurementSource} source Measurement source instance
   * @param {string} annotationType annotation type to match which can be e.g., Length, Bidirectional, etc.
   * @param {MatchingCriteria} matchingCriteria The matching criteria
   * @param {Function} toAnnotationSchema Mapping function to annotation schema
   * @param {Function} toMeasurementSchema Mapping function to measurement schema
   * @return void
   */
  addMapping(source, annotationType, matchingCriteria, toAnnotationSchema, toMeasurementSchema) {
    Iif (!this._isValidSource(source)) {
      throw new Error('Invalid source.');
    }
 
    Iif (!matchingCriteria) {
      throw new Error('Matching criteria not provided.');
    }
 
    Iif (!annotationType) {
      throw new Error('annotationType not provided.');
    }
 
    Iif (!toAnnotationSchema) {
      throw new Error('Mapping function to source schema not provided.');
    }
 
    Iif (!toMeasurementSchema) {
      throw new Error('Measurement mapping function not provided.');
    }
 
    const mapping = {
      matchingCriteria,
      annotationType,
      toAnnotationSchema,
      toMeasurementSchema,
    };
 
    if (Array.isArray(this.mappings[source.uid])) {
      this.mappings[source.uid].push(mapping);
    } else {
      this.mappings[source.uid] = [mapping];
    }
 
    // log.info(`New measurement mapping added to source '${this._getSourceToString(source)}'.`);
  }
 
  /**
   * Get annotation for specific source.
   *
   * @param {MeasurementSource} source Measurement source instance
   * @param {string} annotationType The source annotationType
   * @param {string} measurementUID The measurement service measurement uid
   * @return {Object} Source measurement schema
   */
  getAnnotation(source, annotationType, measurementUID) {
    Iif (!this._isValidSource(source)) {
      log.warn('Invalid source. Exiting early.');
      return;
    }
 
    Iif (!annotationType) {
      log.warn('No source annotationType provided. Exiting early.');
      return;
    }
 
    const measurement = this.getMeasurement(measurementUID);
    const mapping = this._getMappingByMeasurementSource(measurement, annotationType);
 
    Iif (mapping) {
      return mapping.toAnnotationSchema(measurement, annotationType);
    }
 
    const matchingMapping = this._getMatchingMapping(source, annotationType, measurement);
 
    Iif (matchingMapping) {
      log.info('Matching mapping found:', matchingMapping);
      const { toAnnotationSchema, annotationType } = matchingMapping;
      return toAnnotationSchema(measurement, annotationType);
    }
  }
 
  update(measurementUID: string, measurement, notYetUpdatedAtSource = false) {
    Iif (!this.measurements.has(measurementUID)) {
      return;
    }
 
    const updatedMeasurement = {
      ...measurement,
      modifiedTimestamp: Math.floor(Date.now() / 1000),
    };
 
    log.info(`Updating internal measurement representation...`, updatedMeasurement);
 
    this.measurements.set(measurementUID, updatedMeasurement);
 
    this._broadcastEvent(this.EVENTS.MEASUREMENT_UPDATED, {
      source: measurement.source,
      measurement: updatedMeasurement,
      notYetUpdatedAtSource,
    });
 
    return updatedMeasurement.uid;
  }
 
  /**
   * Add a raw measurement into a source so that it may be
   * Converted to/from annotation in the same way. E.g. import serialized data
   * of the same form as the measurement source.
   * @param {MeasurementSource} source The measurement source instance.
   * @param {string} annotationType The source annotationType you want to add the measurement to.
   * @param {object} data The data you wish to add to the source.
   * @param {function} toMeasurementSchema A function to get the `data` into the same shape as the source annotationType.
   */
  addRawMeasurement(source, annotationType, data, toMeasurementSchema, dataSource = {}) {
    Iif (!this._isValidSource(source)) {
      log.warn('Invalid source. Exiting early.');
      return;
    }
 
    const sourceInfo = this._getSourceToString(source);
 
    Iif (!annotationType) {
      log.warn('No source annotationType provided. Exiting early.');
      return;
    }
 
    Iif (!this._sourceHasMappings(source)) {
      log.warn(`No measurement mappings found for '${sourceInfo}' source. Exiting early.`);
      return;
    }
 
    let measurement = {};
    try {
      measurement = toMeasurementSchema(data);
      Iif (!measurement) {
        return;
      }
      measurement.source = source;
    } catch (error) {
      log.warn(
        `Failed to map '${sourceInfo}' measurement for annotationType ${annotationType}:`,
        error
      );
      return;
    }
 
    Iif (!this._isValidMeasurement(measurement)) {
      log.warn(
        `Attempting to add or update a invalid measurement provided by '${sourceInfo}'. Exiting early.`
      );
      return;
    }
 
    let internalUID = data.id;
    if (!internalUID) {
      internalUID = guid();
      log.warn(`Measurement ID not found. Generating UID: ${internalUID}`);
    }
 
    const annotationData = data.annotation.data;
 
    const newMeasurement = {
      finding: annotationData.finding,
      findingSites: annotationData.findingSites,
      site: annotationData.findingSites?.[0],
      ...measurement,
      modifiedTimestamp: Math.floor(Date.now() / 1000),
      uid: internalUID,
    };
 
    Iif (this.measurements.get(internalUID)) {
      this.measurements.set(internalUID, newMeasurement);
      this._broadcastEvent(this.EVENTS.MEASUREMENT_UPDATED, {
        source,
        measurement: newMeasurement,
      });
    } else {
      log.info('Measurement added', newMeasurement);
      this.measurements.set(internalUID, newMeasurement);
      this._broadcastEvent(this.EVENTS.RAW_MEASUREMENT_ADDED, {
        source,
        measurement: newMeasurement,
        data,
        dataSource,
      });
    }
 
    return newMeasurement.uid;
  }
 
  /**
   * Adds or update persisted measurements.
   *
   * @param {MeasurementSource} source The measurement source instance
   * @param {string} annotationType The source annotationType
   * @param {EventDetail} sourceAnnotationDetail for the annotation event
   * @param {boolean} isUpdate is this an update or an add/completed instead?
   * @return {string} A measurement uid
   */
  annotationToMeasurement(source, annotationType, sourceAnnotationDetail, isUpdate = false) {
    Iif (!this._isValidSource(source)) {
      throw new Error('Invalid source.');
    }
    Iif (!annotationType) {
      throw new Error('No source annotationType provided.');
    }
 
    const sourceInfo = this._getSourceToString(source);
    Iif (!this._sourceHasMappings(source)) {
      throw new Error(`No measurement mappings found for '${sourceInfo}' source. Exiting early.`);
    }
 
    let measurement = {};
    try {
      const sourceMappings = this.mappings[source.uid];
      const sourceMapping = sourceMappings.find(
        mapping => mapping.annotationType === annotationType
      );
      if (!sourceMapping) {
        console.log('No source mapping', source);
        return;
      }
      const { toMeasurementSchema } = sourceMapping;
 
      /* Convert measurement */
      measurement = toMeasurementSchema(sourceAnnotationDetail);
      if (!measurement) {
        return;
      }
 
      measurement.source = source;
    } catch (error) {
      // Todo: handle other
      this.unmappedMeasurements.set(sourceAnnotationDetail.uid, {
        ...sourceAnnotationDetail,
        source: {
          name: source.name,
          version: source.version,
          uid: source.uid,
        },
      });
 
      console.log('Failed to map', error);
      throw new Error(
        `Failed to map '${sourceInfo}' measurement for annotationType ${annotationType}: ${error.message}`
      );
    }
 
    Iif (!this._isValidMeasurement(measurement)) {
      throw new Error(
        `Attempting to add or update a invalid measurement provided by '${sourceInfo}'. Exiting early.`
      );
    }
 
    // Todo: we are using uid on the eventDetail, it should be uid of annotation
    let internalUID = sourceAnnotationDetail.uid;
    Iif (!internalUID) {
      internalUID = guid();
      log.info(
        `Annotation does not have UID, Generating UID for the created Measurement: ${internalUID}`
      );
    }
 
    const oldMeasurement = this.measurements.get(internalUID);
 
    const newMeasurement = {
      ...oldMeasurement,
      ...measurement,
      modifiedTimestamp: Math.floor(Date.now() / 1000),
      uid: internalUID,
    };
 
    newMeasurement.isDirty =
      sourceAnnotationDetail.changeType === MeasurementChangeType.HandlesUpdated ||
      sourceAnnotationDetail.changeType === MeasurementChangeType.LabelChange ||
      oldMeasurement?.isDirty;
 
    if (oldMeasurement) {
      // TODO: Ultimately, each annotation should have a selected flag right from the source.
      // For now, it is just added in OHIF here and in setMeasurementSelected.
      this.measurements.set(internalUID, newMeasurement);
      if (isUpdate) {
        this._broadcastEvent(this.EVENTS.MEASUREMENT_UPDATED, {
          source,
          measurement: newMeasurement,
          notYetUpdatedAtSource: false,
        });
      } else {
        log.info('Measurement added.', newMeasurement);
        this._broadcastEvent(this.EVENTS.MEASUREMENT_ADDED, {
          source,
          measurement: newMeasurement,
        });
      }
    } else {
      log.info('Measurement started.', newMeasurement);
      this.measurements.set(internalUID, newMeasurement);
    }
 
    return newMeasurement.uid;
  }
 
  /**
   * Removes a measurement and broadcasts the removed event.
   *
   * @param {string} measurementUID The measurement uid
   */
  remove(measurementUID: string): void {
    const measurement =
      this.measurements.get(measurementUID) || this.unmappedMeasurements.get(measurementUID);
 
    Iif (!measurementUID || !measurement) {
      console.debug(`No uid provided, or unable to find measurement by uid.`);
      return;
    }
 
    const source = measurement.source;
 
    this.unmappedMeasurements.delete(measurementUID);
    this.measurements.delete(measurementUID);
    this.isMeasurementDeletedIndividually = true;
    this._broadcastEvent(this.EVENTS.MEASUREMENT_REMOVED, {
      source,
      measurement: measurementUID,
    });
  }
 
  /**
   * Remove multiple measurements at once.
   */
  removeMany(measurementUIDs: string[]): void {
    const measurements = [];
    for (const measurementUID of measurementUIDs) {
      const measurement =
        this.measurements.get(measurementUID) || this.unmappedMeasurements.get(measurementUID);
 
      Iif (!measurementUID || !measurement) {
        console.debug(`No uid provided, or unable to find measurement by uid.`);
        continue;
      }
 
      this.unmappedMeasurements.delete(measurementUID);
      this.measurements.delete(measurementUID);
      measurements.push(measurement);
    }
    Iif (!measurements.length) {
      return;
    }
    this._broadcastEvent(this.EVENTS.MEASUREMENTS_CLEARED, { measurements });
  }
 
  /**
   * Clears measurements that match the filter, defaulting to all of them.
   * That allows, for example, clearing all of a single studies measurements
   * without needing to clear other measurements.
   */
  public clearMeasurements(filter?: MeasurementFilter) {
    // Make a copy of the measurements
    const toClear = this.getMeasurements(filter);
    const unmappedClear = filter
      ? [...this.unmappedMeasurements.values()].filter(filter)
      : this.unmappedMeasurements;
    const measurements = [...toClear, ...unmappedClear];
    unmappedClear.forEach(measurement => this.unmappedMeasurements.delete(measurement.uid));
    toClear.forEach(measurement => this.measurements.delete(measurement.uid));
    this._broadcastEvent(this.EVENTS.MEASUREMENTS_CLEARED, { measurements });
  }
 
  /**
   * Called after the mode.onModeExit is called to reset the state.
   * To store measurements for later use, store them in the mode.onModeExit
   * and restore them in the mode onModeEnter.
   */
  onModeExit() {
    this.clearMeasurements();
  }
 
  /**
   * This method calls the subscriptions for JUMP_TO_MEASUREMENT_VIEWPORT
   * and JUMP_TO_MEASUREMENT_LAYOUT.  There are two events which are
   * fired because there are two different items which might want to handle
   * the event.  First, there might already be a viewport which can handle
   * the event.  If so, then the layout doesn't need to necessarily change.
   * This is communicated by the isConsumed value on the event itself.
   * Otherwise, the layout itself may need to be navigated to in order
   * to provide a viewport which can show the given measurement.
   *
   * When a viewport decides to apply the event, it should call the consume()
   * method on the event, so that other listeners know they do not need to
   * navigate.  This does NOT affect whether the layout event is fired, and
   * merely causes it to fire the event with the isConsumed set to true.
   */
 
  public jumpToMeasurement(viewportId: string, measurementUID: string): void {
    const measurement = this.measurements.get(measurementUID);
 
    Iif (!measurement) {
      log.warn(`No measurement uid, or unable to find by uid.`);
      return;
    }
    const consumableEvent = this.createConsumableEvent({
      viewportId,
      measurement,
    });
 
    // Important: we should broadcast the layout event first, since
    // in the layout there might be a viewport that we can match and choose
    // and jump in it before we decide on changing the orientation of different viewports
    this._broadcastEvent(EVENTS.JUMP_TO_MEASUREMENT_LAYOUT, consumableEvent);
    this._broadcastEvent(EVENTS.JUMP_TO_MEASUREMENT_VIEWPORT, consumableEvent);
  }
 
  _getSourceUID(name, version) {
    const { sources } = this;
 
    const sourceUID = Object.keys(sources).find(sourceUID => {
      const source = sources[sourceUID];
 
      return source.name === name && source.version === version;
    });
 
    return sourceUID;
  }
 
  _getMappingByMeasurementSource(measurement, annotationType) {
    Iif (this._isValidSource(measurement.source)) {
      return this.mappings[measurement.source.uid].find(m => m.annotationType === annotationType);
    }
  }
 
  /**
   * Get measurement mapping function if matching criteria.
   *
   * @param {MeasurementSource} source Measurement source instance
   * @param {string} annotationType The source annotationType
   * @param {Measurement} measurement The measurement service measurement
   * @return {Object} The mapping based on matched criteria
   */
  _getMatchingMapping(source, annotationType, measurement) {
    const sourceMappings = this.mappings[source.uid];
 
    const sourceMappingsByDefinition = sourceMappings.filter(
      mapping => mapping.annotationType === annotationType
    );
 
    /* Criteria Matching */
    return sourceMappingsByDefinition.find(({ matchingCriteria }) => {
      return measurement.points && measurement.points.length === matchingCriteria.points;
    });
  }
 
  /**
   * Returns formatted string with source info.
   *
   * @param {MeasurementSource} source Measurement source
   * @return {string} Source information
   */
  _getSourceToString(source) {
    return `${source.name}@${source.version}`;
  }
 
  /**
   * Checks if given source is valid.
   *
   * @param {MeasurementSource} source Measurement source
   * @return {boolean} Measurement source validation
   */
  _isValidSource(source) {
    return source && this.sources[source.uid];
  }
 
  /**
   * Checks if a given source has mappings.
   *
   * @param {MeasurementSource} source The measurement source
   * @return {boolean} Validation if source has mappings
   */
  _sourceHasMappings(source) {
    return Array.isArray(this.mappings[source.uid]) && this.mappings[source.uid].length;
  }
 
  /**
   * Check if a given measurement data is valid.
   *
   * @param {Measurement} measurementData Measurement data
   * @return {boolean} Measurement validation
   */
  _isValidMeasurement(measurementData) {
    return Object.keys(measurementData).every(key => {
      Iif (!MEASUREMENT_SCHEMA_KEYS.includes(key)) {
        log.warn(`Invalid measurement key: ${key}`);
        return false;
      }
 
      return true;
    });
  }
 
  /**
   * Check if a given measurement service event is valid.
   *
   * @param {string} eventName The name of the event
   * @return {boolean} Event name validation
  //  */
  // _isValidEvent(eventName) {
  //   return Object.values(this.EVENTS).includes(eventName);
  // }
 
  /**
   * Converts object of objects to array.
   *
   * @return {Array} Array of objects
   */
  _arrayOfObjects = obj => {
    return Object.entries(obj).map(e => ({ [e[0]]: e[1] }));
  };
 
  public toggleLockMeasurement(measurementUID: string): void {
    const measurement = this.measurements.get(measurementUID);
 
    Iif (!measurement) {
      console.debug(`No measurement found for uid: ${measurementUID}`);
      return;
    }
 
    measurement.isLocked = !measurement.isLocked;
 
    this._broadcastEvent(this.EVENTS.MEASUREMENT_UPDATED, {
      source: measurement.source,
      measurement,
      notYetUpdatedAtSource: true,
    });
  }
 
  public toggleVisibilityMeasurement(measurementUID: string, visibility?: boolean): void {
    const measurement = this.measurements.get(measurementUID);
 
    Iif (!measurement) {
      console.debug(`No measurement found for uid: ${measurementUID}`);
      return;
    }
 
    Iif (measurement.isVisible === visibility && visibility !== undefined) {
      return;
    }
    measurement.isVisible = visibility !== undefined ? visibility : !measurement.isVisible;
 
    this._broadcastEvent(this.EVENTS.MEASUREMENT_UPDATED, {
      source: measurement.source,
      measurement,
      notYetUpdatedAtSource: true,
    });
  }
 
  public toggleVisibilityMeasurementMany(measurementUIDs: string[], visibility?: boolean): void {
    return measurementUIDs.forEach(uid => this.toggleVisibilityMeasurement(uid, visibility));
  }
 
  public updateColorMeasurement(measurementUID: string, color: number[]): void {
    const measurement = this.measurements.get(measurementUID);
 
    Iif (!measurement) {
      console.debug(`No measurement found for uid: ${measurementUID}`);
      return;
    }
 
    measurement.color = color;
 
    this._broadcastEvent(this.EVENTS.MEASUREMENT_UPDATED, {
      source: measurement.source,
      measurement,
      notYetUpdatedAtSource: true,
    });
  }
 
  public setIsMeasurementDeletedIndividually = isDeletedIndividually => {
    this.isMeasurementDeletedIndividually = isDeletedIndividually;
  };
 
  public getIsMeasurementDeletedIndividually = () => {
    return this.isMeasurementDeletedIndividually;
  };
}
 
export default MeasurementService;
export { EVENTS, VALUE_TYPES };