-
Notifications
You must be signed in to change notification settings - Fork 3
[DTOSS 12685] Emulate modality workflow #112
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
7ae2cd6
Filter completed and discontinued worklist items
steventux 3c12a06
Add modality emulator
steventux 1725d6f
Add modality emulator container definition
steventux d90e4d8
Include emulator in deploy and rollback
steventux 019f6e6
Add sample images to release script
steventux 8d9010f
Include licence in packaged release
steventux a6cc5cd
Configure sample images path and default path
steventux 85fff93
Add an ADR for modality emulator
steventux 3eae6ff
Only start emulator for dev and review deployments
steventux 759a5ce
Recover gracefully from general exceptions
steventux File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,36 @@ | ||
| # ADR-006: Use a modality emulator for non-production environments | ||
|
|
||
| Date: 2026-06-04 | ||
|
|
||
| Status: Accepted | ||
|
|
||
| ## Context | ||
|
|
||
| The Manage Breast Screening service sends worklist items corresponding to screening appointments as the appointment starts. These are received by the gateway via Azure Relay and processed to trigger DICOM API uploads of the screening study data. The worklist items are queried via DICOM C-FIND requests to the gateway MWL server and stored on the gateway PACS server using the DICOM C-STORE protocol. | ||
|
|
||
| In production this query is performed by the modality, which is a physical machine in the hospital network that runs software to query the MWL and display results to radiographers. The modality then sends the resulting study DICOM files to the Gateway PACS server using C-STORE. The PACS server then compresses the image data in the DICOM files and uploads it to the DICOM API hosted on Manage. | ||
|
|
||
| In non-production environments, there is no modality available to perform this query. This means that testing the full flow of worklist items through the gateway and into the DICOM API is difficult without deploying to production or using complex stubs/mocks. | ||
|
|
||
| ## Decision | ||
|
|
||
| To facilitate end-to-end testing of the worklist flow in non-production environments, we will implement a simple modality emulator. This will be a lightweight service that simulates the behavior of a real modality by performing queries against the MWL server and storing the emulated study data on the Gateway PACS server, mimicking the behavior of a real modality. | ||
|
|
||
| The emulator runs on the same host as the MWL and PACS servers in non-production environments. It runs as a Python process that makes a C-FIND request at a configurable polling interval, checking for new worklist items. When it finds a new item, it creates a DICOM dataset from the worklist details, includes some sample image data and sends them to the PACS server via C-STORE. | ||
|
|
||
| The sample image data corresponds to the 4 main laterality and view position combinations (LCC, LMLO, RCC, RMLO) to allow testing of the laterality and view position logic in the gateway images screens as the DICOM files are uploaded to Manage. | ||
|
|
||
| ## Consequences | ||
|
|
||
| We no longer have to use a third party emulator or do any UI work to test the happy path of worklist items flowing through the gateway and into the DICOM API in non-production environments. This also allows us to make more comprehensive end-to-end tests that cover the full flow, including the C-FIND and C-STORE interactions with the MWL and PACS servers. | ||
|
|
||
| ### Positive Consequences | ||
|
|
||
| - **End-to-end testing:** Enables testing of the full worklist flow in non-production environments without needing a physical modality or complex stubs/mocks. | ||
| - **Simplified test setup:** Developers can run the emulator locally or in test environments to simulate modality behavior without additional infrastructure. | ||
| - **Improved test coverage:** Allows for more comprehensive tests that cover the interactions with the MWL and PACS servers, as well as the gateway's processing logic for worklist items. | ||
| - **Configurable behavior:** The emulator can be configured to simulate different scenarios, such as varying polling intervals or different worklist item details, to test edge cases and error handling in the gateway. | ||
|
|
||
| ### Negative Consequences | ||
|
|
||
| - The emulator and sample images are packaged with every release. This increases the size of the release artifact and may have implications for storage and distribution. |
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,215 @@ | ||
| import datetime | ||
| import logging | ||
| import os | ||
| import time | ||
|
|
||
| import numpy as np | ||
| from PIL import Image | ||
| from pydicom.dataset import Dataset, FileMetaDataset | ||
| from pydicom.uid import ExplicitVRLittleEndian, generate_uid | ||
| from pynetdicom import AE | ||
| from pynetdicom.sop_class import ( | ||
| DigitalMammographyXRayImageStorageForPresentation, # type: ignore | ||
| ModalityWorklistInformationFind, # type: ignore | ||
| ) | ||
|
|
||
| from environment import Environment | ||
| from services.dicom import PENDING, PENDING_WARNING, SUCCESS | ||
| from services.mwl import MWLStatus | ||
| from services.storage import MWLStorage | ||
|
|
||
| logging.basicConfig( | ||
| level=os.getenv("LOG_LEVEL", "INFO").upper(), | ||
| format=os.getenv("LOG_FORMAT", "%(asctime)s - %(name)s - %(levelname)s - %(message)s"), | ||
| ) | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| DICOM_LATERALITIES = ["L", "R"] | ||
| DICOM_VIEWS = ["CC", "MLO"] | ||
| EMULATED_PROCEDURE_DURATION_SECONDS = int(os.getenv("EMULATED_PROCEDURE_DURATION_SECONDS", "5")) | ||
| MODALITY = "MG" | ||
| MWL_AET = os.getenv("MWL_AET", "SCREENING_MWL") | ||
| MWL_DB_PATH = os.getenv("MWL_DB_PATH", "/var/lib/pacs/worklist.db") | ||
| MWL_HOST = os.getenv("MWL_HOST", "localhost") | ||
| MWL_PORT = int(os.getenv("MWL_PORT", "4243")) | ||
| PACS_AET = os.getenv("PACS_AET", "SCREENING_PACS") | ||
| PACS_DB_PATH = os.getenv("PACS_DB_PATH", "/var/lib/pacs/pacs.db") | ||
| PACS_HOST = os.getenv("PACS_HOST", "localhost") | ||
| PACS_PORT = int(os.getenv("PACS_PORT", "4244")) | ||
| SAMPLE_IMAGES_PATH = os.getenv("SAMPLE_IMAGES_PATH", "sample_images") | ||
|
|
||
|
|
||
| class DicomExample: | ||
| def __init__( | ||
| self, dataset: Dataset | None, laterality: str, view: str, study_instance_uid: str, series_number: int | ||
| ): | ||
| self.dataset = dataset | ||
| self.laterality = laterality | ||
| self.view = view | ||
| self.study_instance_uid = study_instance_uid | ||
| self.series_number = series_number | ||
| self.data = self.generate_dicom() | ||
|
|
||
| def generate_dicom(self) -> Dataset: | ||
| ds = Dataset() | ||
| if not self.dataset: | ||
| logger.error("No dataset provided for DICOM generation") | ||
| return ds | ||
|
|
||
| img_path = f"{SAMPLE_IMAGES_PATH}/L{self.view}.jpg" | ||
| img = Image.open(img_path).convert("L") | ||
| if self.laterality == "R": | ||
| img = img.transpose(Image.Transpose.FLIP_LEFT_RIGHT) | ||
| columns, rows = img.size | ||
| pixel_array = np.array(img, dtype=np.uint8) | ||
| pixel_bytes = pixel_array.tobytes() | ||
| if len(pixel_bytes) % 2 != 0: | ||
| pixel_bytes += b"\x00" | ||
|
|
||
| file_meta = FileMetaDataset() | ||
| file_meta.MediaStorageSOPClassUID = DigitalMammographyXRayImageStorageForPresentation | ||
| file_meta.MediaStorageSOPInstanceUID = generate_uid() | ||
| file_meta.ImplementationClassUID = generate_uid() | ||
| file_meta.TransferSyntaxUID = ExplicitVRLittleEndian | ||
|
|
||
| ds.SOPClassUID = file_meta.MediaStorageSOPClassUID | ||
| ds.SOPInstanceUID = file_meta.MediaStorageSOPInstanceUID | ||
| ds.SamplesPerPixel = 1 | ||
| ds.PhotometricInterpretation = "MONOCHROME2" | ||
| ds.Rows = rows | ||
| ds.Columns = columns | ||
| ds.BitsAllocated = 8 | ||
| ds.BitsStored = 8 | ||
| ds.HighBit = 7 | ||
| ds.PixelRepresentation = 0 | ||
| ds.PixelData = pixel_bytes | ||
| ds.ImageLaterality = self.laterality | ||
| ds.ViewPosition = self.view | ||
|
|
||
| ds.AccessionNumber = self.dataset.AccessionNumber | ||
| ds.PatientID = self.dataset.PatientID | ||
| ds.PatientName = self.dataset.PatientName | ||
| ds.PatientBirthDate = self.dataset.PatientBirthDate | ||
| ds.PatientSex = self.dataset.PatientSex | ||
| scheduled_step = self.dataset.ScheduledProcedureStepSequence[0] | ||
| ds.StudyDate = scheduled_step.ScheduledProcedureStepStartDate | ||
| ds.StudyTime = scheduled_step.ScheduledProcedureStepStartTime | ||
| ds.StudyInstanceUID = self.study_instance_uid | ||
| ds.StudyID = f"STUDY{self.study_instance_uid[-8:]}" | ||
| ds.SeriesInstanceUID = generate_uid() | ||
| ds.SeriesNumber = self.series_number | ||
| ds.Modality = MODALITY | ||
| ds.InstanceNumber = 1 | ||
| ds.file_meta = file_meta | ||
|
|
||
| logger.debug(f"Generated DICOM for worklist item {self.dataset.AccessionNumber} - {self.laterality}{self.view}") | ||
| logger.debug(f"{ds}") | ||
|
|
||
| return ds | ||
|
|
||
|
|
||
| class ModalityEmulator: | ||
| def __init__(self, mwl_storage: MWLStorage): | ||
| self.mwl_storage = mwl_storage | ||
| self.processed_items = set() | ||
|
|
||
| def process_worklist_items(self, ae: AE): | ||
| """ | ||
| Queries the MWL for items scheduled for today and sends generated DICOM files to the PACS server for each item. | ||
| """ | ||
| mwl_assoc = ae.associate(MWL_HOST, MWL_PORT, ae_title=MWL_AET) | ||
| pacs_assoc = ae.associate(PACS_HOST, PACS_PORT, ae_title=PACS_AET) | ||
|
|
||
| if mwl_assoc.is_established and pacs_assoc.is_established: | ||
| logger.info(f"Connected to MWL server {MWL_HOST}:{MWL_PORT} ({MWL_AET})") | ||
| logger.info(f"Connected to PACS server {PACS_HOST}:{PACS_PORT} ({PACS_AET})") | ||
|
|
||
| logger.info("Querying MWL for scheduled items...") | ||
| responses = mwl_assoc.send_c_find(self.c_find_dataset, query_model=ModalityWorklistInformationFind) | ||
| for status, ds in responses: | ||
| status_code = getattr(status, "Status", SUCCESS) | ||
|
|
||
| if status_code in (PENDING, PENDING_WARNING): | ||
| accession_number = getattr(ds, "AccessionNumber", "UNKNOWN") | ||
|
|
||
| if accession_number in self.processed_items: | ||
| logger.info(f"Skipping already processed worklist item {accession_number}") | ||
| continue | ||
|
|
||
| self.processed_items.add(accession_number) | ||
| study_instance_uid = generate_uid() | ||
| series_number = 1 | ||
| for laterality in DICOM_LATERALITIES: | ||
| for view in DICOM_VIEWS: | ||
| logger.info( | ||
| f"Processing worklist item {accession_number} - generating DICOM for {laterality}{view}" | ||
| ) | ||
| dicom_example = DicomExample(ds, laterality, view, study_instance_uid, series_number) | ||
| dataset = dicom_example.data | ||
|
|
||
| if getattr(dataset, "SOPInstanceUID", None) is None: | ||
| logger.error( | ||
| f"Skipping DICOM generation for {laterality}{view} of worklist item {accession_number}" | ||
| ) | ||
| continue | ||
|
|
||
| pacs_assoc.send_c_store(dataset) | ||
| logger.info( | ||
| f"Sent DICOM for {laterality}{view} of worklist item {accession_number}. Series# {series_number}" | ||
| ) | ||
| series_number += 1 | ||
|
|
||
| time.sleep(1) # Allow C-STORE operations to complete before updating status | ||
|
|
||
| self.mwl_storage.update_status(accession_number, MWLStatus.COMPLETED.value) | ||
| logger.info(f"Completed processing for worklist item {accession_number}") | ||
| elif status_code == SUCCESS: | ||
| logger.info("C-FIND query completed successfully") | ||
| else: | ||
| logger.error(f"C-FIND query failed with status: 0x{status_code:04X}") | ||
|
|
||
| else: | ||
| logger.error("Failed to make MWL and PACS associations") | ||
|
|
||
| mwl_assoc.release() | ||
| pacs_assoc.release() | ||
|
|
||
| @property | ||
| def c_find_dataset(self) -> Dataset: | ||
| date_today = datetime.date.today() | ||
| ds = Dataset() | ||
| sps_dataset = Dataset() | ||
| sps_dataset.Modality = MODALITY | ||
| sps_dataset.ScheduledProcedureStepStartDate = date_today.strftime("%Y%m%d") | ||
| sps_dataset.ScheduledProcedureStepStartTime = "000000-" | ||
| ds.ScheduledProcedureStepSequence = [sps_dataset] | ||
| return ds | ||
|
|
||
|
|
||
| def main(): | ||
| if Environment().production: | ||
| raise RuntimeError("Modality Emulator should not be run in production environment") | ||
|
|
||
| logger.info("Modality Emulator Starting...") | ||
| mwl_storage = MWLStorage(db_path=MWL_DB_PATH) | ||
| emulator = ModalityEmulator(mwl_storage) | ||
| ae = AE(ae_title="ModalityEmulator") | ||
| ae.add_requested_context(DigitalMammographyXRayImageStorageForPresentation) | ||
| ae.add_requested_context(ModalityWorklistInformationFind) | ||
|
|
||
| while True: | ||
| try: | ||
| time.sleep(EMULATED_PROCEDURE_DURATION_SECONDS) | ||
| emulator.process_worklist_items(ae) | ||
| except KeyboardInterrupt: | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. worth catching |
||
| logger.warning("\n Modality Emulator shutting down...") | ||
| break | ||
| except Exception: | ||
| logger.exception("Error in Modality Emulator") | ||
| time.sleep(5) # Wait before retrying to avoid tight error loop | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| main() | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.