diff --git a/ci/unit_tests/test_coronaryArtery_ct_segmentation.py b/ci/unit_tests/test_coronaryArtery_ct_segmentation.py new file mode 100644 index 00000000..b2a7be49 --- /dev/null +++ b/ci/unit_tests/test_coronaryArtery_ct_segmentation.py @@ -0,0 +1,83 @@ +#!/bin/python +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os +import shutil +import sys +import tempfile +import unittest +from pathlib import Path + +import nibabel as nib +import numpy as np +from monai.bundle import ConfigWorkflow +from parameterized import parameterized +from utils import check_workflow + +ROOT = Path(__file__).parent.parent.parent +bundle_path = os.path.join(ROOT, "models", "CoronSegmentator") + +if bundle_path not in sys.path: + sys.path.insert(0, bundle_path) + print(f"Added to sys.path: {bundle_path}") + +TEST_CASE_1 = [{"bundle_root": r"models/CoronSegmentator"}] # inference + + +def test_order(test_name1, test_name2): + def get_order(name): + if "train" in name: + return 1 + if "eval" in name: + return 2 + if "infer" in name: + return 3 + return 4 + + return get_order(test_name1) - get_order(test_name2) + + +class TestCoronaryArteryCTSeg(unittest.TestCase): + def setUp(self): + self.dataset_dir = tempfile.mkdtemp() + dataset_size = 10 + input_shape = (128, 128, 128) + for s in range(dataset_size): + test_image = np.random.randint(low=-1024, high=1000, size=input_shape).astype(np.int8) + test_label = np.random.randint(low=0, high=1, size=input_shape).astype(np.int8) + image_filename = os.path.join(self.dataset_dir, f"image_{s}.nii.gz") + label_filename = os.path.join(self.dataset_dir, f"label_{s}.nii.gz") + nib.save(nib.Nifti1Image(test_image, np.eye(4)), image_filename) + nib.save(nib.Nifti1Image(test_label, np.eye(4)), label_filename) + + def tearDown(self): + shutil.rmtree(self.dataset_dir) + + @parameterized.expand([TEST_CASE_1]) + def test_infer_config(self, override): + override["dataset_dir"] = self.dataset_dir + bundle_root = override["bundle_root"] + + inferrer = ConfigWorkflow( + workflow_type="infer", + config_file=Path(bundle_root) / "configs/inference.json", + logging_file=Path(bundle_root) / "configs/logging.conf", + meta_file=Path(bundle_root) / "configs/metadata.json", + **override, + ) + check_workflow(inferrer, check_properties=True) + + +if __name__ == "__main__": + loader = unittest.TestLoader() + loader.sortTestMethodsUsing = test_order + unittest.main(testLoader=loader) diff --git a/models/CoronSegmentator/.gitignore b/models/CoronSegmentator/.gitignore new file mode 100644 index 00000000..588369da --- /dev/null +++ b/models/CoronSegmentator/.gitignore @@ -0,0 +1,5 @@ +*__pycache__ +*zip +.python-version + +/env diff --git a/models/CoronSegmentator/LICENSE b/models/CoronSegmentator/LICENSE new file mode 100644 index 00000000..d48610fd --- /dev/null +++ b/models/CoronSegmentator/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright © 2025 Hon Hai Precision Industry Co.,Ltd. All rights reserved + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/models/CoronSegmentator/configs/inference.json b/models/CoronSegmentator/configs/inference.json new file mode 100644 index 00000000..9cb55534 --- /dev/null +++ b/models/CoronSegmentator/configs/inference.json @@ -0,0 +1,25 @@ +{ + "imports": [ + "$import glob" + ], + "bundle_root": ".", + "ckpt_dir": "$@bundle_root + '/models'", + "dataset_dir": "", + "data": "$list(sorted(glob.glob(@dataset_dir + '/*.nii.gz')))", + "output_ext": ".usd", + "output_dir": "$@bundle_root + '/Output'", + "device": "$torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')", + "inferer": { + "_target_": "scripts.heart_digital_twin.CoroSegmentatorPipeline", + "input_params": { + "inputFile": "$@data[0]", + "outputDir": "$@output_dir" + } + }, + "dataset": {}, + "evaluator": {}, + "network_def": {}, + "run": [ + "$@inferer.run()" + ] +} diff --git a/models/CoronSegmentator/configs/logging.conf b/models/CoronSegmentator/configs/logging.conf new file mode 100644 index 00000000..91c1a21c --- /dev/null +++ b/models/CoronSegmentator/configs/logging.conf @@ -0,0 +1,21 @@ +[loggers] +keys=root + +[handlers] +keys=consoleHandler + +[formatters] +keys=fullFormatter + +[logger_root] +level=INFO +handlers=consoleHandler + +[handler_consoleHandler] +class=StreamHandler +level=INFO +formatter=fullFormatter +args=(sys.stdout,) + +[formatter_fullFormatter] +format=%(asctime)s - %(name)s - %(levelname)s - %(message)s diff --git a/models/CoronSegmentator/configs/metadata.json b/models/CoronSegmentator/configs/metadata.json new file mode 100644 index 00000000..9307815b --- /dev/null +++ b/models/CoronSegmentator/configs/metadata.json @@ -0,0 +1,78 @@ +{ + "schema": "https://github.com/Project-MONAI/MONAI-extra-test-data/releases/download/0.8.1/meta_schema_20220324.json", + "name": "coronaryArtery_ct_segmentation", + "version": "1.0.0", + "monai_version": "1.5.0", + "pytorch_version": "2.6.0", + "numpy_version": "2.2.6", + "required_packages_version": { + "fire": "0.7.0", + "nnunetv2": "2.6.2", + "nibabel": "5.3.2", + "numpy": "2.2.6", + "numpy-stl": "3.2.0", + "pynrrd": "1.1.3", + "scipy": "1.15.3", + "simpleitk": "2.5.2", + "scikit-image": "0.25.2", + "torch": "2.6.0" + }, + "task": "Coronary artery ct segmentation", + "description": "Coronsegmentator is an automated pipeline that performs coronary artery segmentation on cardiac CT images, focusing on coronary artery structures. Use a custom nnU-Net model for detailed coronary artery segmentation.", + "authors": "Y. Ke, MC. Chen, TY. Lin, YC. Chan Foxconn Digital Health AI Team", + "copyright": "Copyright \u00a9 2025 Hon Hai Precision Industry Co.,Ltd. All rights reserved", + "data_source": "The ImageCAS dataset is publicly available at: https://github.com/XiaoweiXu/ImageCAS-A-Large-Scale-Dataset-and-Benchmark-for-Coronary-Artery-Segmentation-based-on-CT.git", + "data_type": "nifti", + "image_classes": "3D volume data", + "label_classes": "single channel data, 1 is coronary artery, 0 is background", + "pred_classes": "2 channels OneHot data, channel 1 is coronary artery, channel 0 is background", + "intended_use": "This is an example, not to be used for diagnostic purposes", + "references": [ + "Zeng, An, et al. ImageCAS: A large-scale dataset and benchmark for coronary artery segmentation based on computed tomography angiography images. Computerized Medical Imaging and Graphics 109 (2023): 102287.", + "Isensee, Fabian, et al. nnU-Net: a self-configuring method for deep learning-based biomedical image segmentation. Nature methods 18.2 (2021): 203-211." + ], + "network_data_format": { + "inputs": { + "image": { + "type": "image", + "format": "hounsfield", + "modality": "CT", + "num_channels": 1, + "spatial_shape": [ + 512, + 512, + 256 + ], + "dtype": "float32", + "value_range": [ + 0, + 1 + ], + "is_patch_data": true, + "channel_def": { + "0": "image" + } + } + }, + "outputs": { + "pred": { + "type": "usd", + "format": "segmentation", + "num_channels": 1, + "spatial_shape": [ + 512, + 512, + 256 + ], + "dtype": "float32", + "value_range": [ + 0, + 1 + ], + "channel_def": { + "0": "Coronary Artery (1 = target, 0 = background)" + } + } + } + } +} diff --git a/models/CoronSegmentator/docs/README.md b/models/CoronSegmentator/docs/README.md new file mode 100644 index 00000000..76aa3c9d --- /dev/null +++ b/models/CoronSegmentator/docs/README.md @@ -0,0 +1,63 @@ +# Coronsegmentator + +### **Authors** + +Y. Ke, MC. Chen, TY. Lin, YC. Chan Foxconn Digital Health AI Team + +### **Tags** + +Segmentation, CT, Heart, Coronary Artery, USD, MONAI, nnU-Net, 3D Reconstruction + +## **Model Description** + +Coronsegmentator is an automated pipeline that performs dual-task segmentation on cardiac CT images, focusing on both whole-heart and coronary artery structures. It integrates MONAI’s Auto3DSeg for general cardiac segmentation and a custom nnU-Net model for detailed coronary artery segmentation. The pipeline further converts segmentation results (in STL format) into USD files for downstream 3D visualization and digital twin simulation using NVIDIA Omniverse. + +The entire workflow is designed to enable precise, scalable, and automated generation of personalized coronary artery digital twins, supporting clinical planning, AI-based diagnosis, and medical visualization in research or pre-operative planning workflows. + +## **Data** + +The Coronsegmentator model was trained on ImageCAS, a dataset consisting of annotated images for training/validation respectively. + +The input data consists of anonymized 3D CT scans in .nii.gz format. This pipeline was designed to be compatible with preoperative cardiac CT data, including varying scanner vendors (e.g., Siemens, Philips). + +Each image is processed by: + +1. Segmenting the cardiac chambers using MONAI Auto3DSeg + +2. Segmenting coronary arteries using a pretrained nnU-Net model + +3. Saving segmentation as STL files and converting them into USD + +#### **Preprocessing** + +Input: .nii.gz NIfTI format (CT scan) + +Resolution normalization handled internally + +No manual annotation required for inference + +#### **Inference** + +```bash +python -m monai.bundle run --config_file "configs/inference.json" +``` + +The ImageCAS dataset is publicly available at: +https://github.com/XiaoweiXu/ImageCAS-A-Large-Scale-Dataset-and-Benchmark-for-Coronary-Artery-Segmentation-based-on-CT.git'' + +## **Limitations** + +This model is intended for research use only. It has not been validated for clinical deployment and should not be used for patient treatment decisions. + +## **References** + +[1] Zeng, An, et al. "ImageCAS: A large-scale dataset and benchmark for coronary artery segmentation based on computed tomography angiography images." Computerized Medical Imaging and Graphics 109 (2023): 102287. + +[2] Isensee, Fabian, et al. "nnU-Net: a self-configuring method for deep learning-based biomedical image segmentation." Nature methods 18.2 (2021): 203-211. + +## **License** + +Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. diff --git a/models/CoronSegmentator/docs/data_license.txt b/models/CoronSegmentator/docs/data_license.txt new file mode 100644 index 00000000..1d611443 --- /dev/null +++ b/models/CoronSegmentator/docs/data_license.txt @@ -0,0 +1,28 @@ +Copyright © 2025 Hon Hai Precision Industry Co.,Ltd. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +Third Party Licenses +----------------------------------------------------------------------- +i. ImageCAS Dataset +The ImageCAS dataset is generously provided by Dr. An Zeng and colleagues from the Department of Radiology, Guangdong Provincial People's Hospital and Guangdong Academy of Medical Sciences. + +The dataset is publicly available via Kaggle (https://www.kaggle.com/datasets/xiaoweixumedicalai/imagecas/data) and the official GitHub repository (https://github.com/XiaoweiXu/ImageCAS-A-Large-Scale-Dataset-and-Benchmark-for-Coronary-Artery-Segmentation-based-on-CT#imagecas-a-large-scale-dataset-and-benchmark-for-coronary-artery-segmentation-based-on-computed-tomo.), and is released under the Apache License 2.0. + +Please cite the original publication when using the dataset: +Zeng, A., Wu, C., Lin, G., et al. ImageCAS: A large-scale dataset and benchmark for coronary artery segmentation based on computed tomography angiography images. Computerized Medical Imaging and Graphics, 109, 102287 (2023). https://doi.org/10.1016/j.compmedimag.2023.102287 + + + +----------------------------------------------------------------------- +Package Version License(s) Copyright Holder / Author +monai 1.4.0 Apache-2.0 MONAI Consortium / Project MONAI +usd-core 25.5 Apache-2.0 Pixar Animation Studios +nnunetv2 (editable) 2.5.1 Apache-2.0 Fabian Isensee / Helmholtz Munich diff --git a/models/CoronSegmentator/large_file.yml b/models/CoronSegmentator/large_file.yml new file mode 100644 index 00000000..d47e94c6 --- /dev/null +++ b/models/CoronSegmentator/large_file.yml @@ -0,0 +1,11 @@ +large_files: + - path: "models/cardiacModel.pt" + # url: "https://mega.nz/file/L8oz3QhA#illHJWSCmsmV5xqbXktwiu-1jUebbpJ0HSKv0hbMFCc" + url: "https://drive.google.com/file/d/11-pgULhmSZyAAfZG9n1vOusWHeH-hpwE/view?usp=drive_link" + hash_val: "0e783497e94293c86995392e5fbbc790" + hash_type: "md5" + - path: "models/CAseg066.zip" + # url: "https://mega.nz/file/74YjjLBJ#xtz5R2UgqyKK_M0F5oP1-t7OzN9LMSqIoGYJgvD8REY" + url: "https://drive.google.com/file/d/12q8fKIUcwij4l9jiBFuIM28wwx6kvBaK/view?usp=drive_link" + hash_val: "b0f1870fabf29386ab8929d2e1d1af1c" + hash_type: "md5" diff --git a/models/CoronSegmentator/scripts/__init__.py b/models/CoronSegmentator/scripts/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/models/CoronSegmentator/scripts/coronaryArtery_segmentation/coronaryArtery_seg.py b/models/CoronSegmentator/scripts/coronaryArtery_segmentation/coronaryArtery_seg.py new file mode 100644 index 00000000..1799b4e5 --- /dev/null +++ b/models/CoronSegmentator/scripts/coronaryArtery_segmentation/coronaryArtery_seg.py @@ -0,0 +1,506 @@ +# -*- coding: utf-8 -*- +""" +File : coronaryArtery_seg.py +Author: John Y. Ke, MC. Chen, TY. Lin, YC. Chan +Copyright © 2025 Hon Hai Precision Industry Co.,Ltd. All rights reserved. +License: Apache License 2.0 + +Description: +This script performs segmentation of coronary arteries using nnUNetv2 +and processes the results for 3D visualization. +""" + +import gc +import logging +import os +import shutil +import subprocess +import uuid +from collections import defaultdict +from pathlib import Path +from tempfile import TemporaryDirectory + +import numpy as np +import torch +from scipy.spatial import cKDTree +from stl import mesh + +# Configure logging +logger = logging.getLogger("CoronaryArterySeg") + + +# Class representing information about each component (a group of connected +# triangles in the mesh) +class ComponentInfo: + """ + Initializes a ComponentInfo instance with vertices. + Computes the bounding box for the given vertices. + """ + + def __init__(self, vertices): + self.vertices = vertices # List of vertices for the component + self.bbox = self.compute_bbox(vertices) # Compute the bounding box for the component + + @staticmethod + def compute_bbox(vertices): + """ + Computes the bounding box for the given vertices. + The bounding box is represented by two points (min_coords, max_coords) + in 3D space. Optimized for performance with empty vertex handling. + """ + if len(vertices) == 0: + return (np.zeros(3), np.zeros(3)) + min_coords = np.min(vertices, axis=0) + max_coords = np.max(vertices, axis=0) + return (min_coords, max_coords) + + +# Disjoint Set Union (DSU) class to keep track of connected components +class DSU: + def __init__(self, components_info): + """ + Initializes the DSU data structure. + Sets up parent, rank (for union by rank), and stores the component + info. + """ + self.parent = list(range(len(components_info))) + self.rank = [0] * len(components_info) + self.info = components_info + + def find(self, x): + """ + Finds the root of the set that x belongs to, using path compression. + """ + if self.parent[x] != x: + self.parent[x] = self.find(self.parent[x]) + return self.parent[x] + + def union(self, x, y): + """ + Unites the sets containing x and y. Performs union by rank. + Also merges the vertices of the two components and updates their + bounding box. Optimized to reduce memory usage during vertex merging. + """ + x_root = self.find(x) + y_root = self.find(y) + if x_root == y_root: + return + if self.rank[x_root] < self.rank[y_root]: + x_root, y_root = y_root, x_root + self.parent[y_root] = x_root + + # Convert to list of tuples for hashability in set operations + vertices_x = set(map(tuple, self.info[x_root].vertices)) + vertices_y = set(map(tuple, self.info[y_root].vertices)) + merged_vertices = vertices_x.union(vertices_y) + merged_vertices = np.array([list(v) for v in merged_vertices]) + + self.info[x_root] = ComponentInfo(merged_vertices) + if self.rank[x_root] == self.rank[y_root]: + self.rank[x_root] += 1 + + +# Class to handle STL splitting based on distance threshold +class STLSplitter: + """ + Initializes the STLSplitter instance. + Reads the STL file and initializes relevant data structures. + """ + + def __init__(self, stl_file, distance_threshold=10, decimals=4): + self.stl_file = stl_file + self.distance_threshold = distance_threshold + self.decimals = decimals + self.original_mesh = mesh.Mesh.from_file(stl_file) + self.num_triangles = len(self.original_mesh.vectors) + self.vertex_map = defaultdict(list) + self.initialize_vertex_map() + + def initialize_vertex_map(self): + """ + Initializes the vertex map by iterating over all triangles in the mesh. + Rounds the vertex coordinates to the specified number of decimals to + avoid floating-point precision issues. + """ + if self.num_triangles == 0: + return + + vectors = self.original_mesh.vectors + # Process in batches to reduce memory pressure + batch_size = min(10000, self.num_triangles) # Adjust batch size based on available memory + for batch_start in range(0, self.num_triangles, batch_size): + batch_end = min(batch_start + batch_size, self.num_triangles) + for idx in range(batch_start, batch_end): + triangle = vectors[idx] + for vertex in triangle: + rounded = tuple(np.round(vertex, self.decimals)) + self.vertex_map[rounded].append(idx) + + @staticmethod + def bbox_distance(bbox_a, bbox_b): + """ + Calculates the Euclidean distance between the bounding boxes of two + components. + """ + a_min, a_max = bbox_a + b_min, b_max = bbox_b + + # Compute the distance between boxes + deltas = np.maximum(0, np.maximum(a_min - b_max, b_min - a_max)) + + return np.linalg.norm(deltas) + + @staticmethod + def has_nearby_points(vertices_a, vertices_b, threshold): + """ + Checks if two sets of vertices are close to each other within the + specified threshold using a KD-Tree for efficient querying. + """ + if len(vertices_a) == 0 or len(vertices_b) == 0: + return False + + # Use the smaller set to build the KD-Tree for better performance + if len(vertices_a) > len(vertices_b): + vertices_a, vertices_b = vertices_b, vertices_a + + # Build KD-Tree only once + tree = cKDTree(vertices_a) + + # Process vertices_b in batches to reduce memory usage + batch_size = min(1000, max(100, len(vertices_b) // 10)) + + # Use query_ball_tree for batch processing when vertices_b is large + if len(vertices_b) > 10000: + # Process in larger chunks for very large datasets + for i in range(0, len(vertices_b), batch_size * 5): + batch = vertices_b[i : i + batch_size * 5] + # Use query_ball_point with r=threshold and return_length=True + # for early termination + indices = tree.query_ball_point(batch, threshold, return_length=True) + if any(indices): + return True + else: + # For smaller datasets, process point by point + # for early termination + for i in range(0, len(vertices_b), batch_size): + batch = vertices_b[i : i + batch_size] + for point in batch: + # Early termination: return True as soon as + # we find any nearby point + if tree.query_ball_point(point, threshold, return_length=True): + return True + return False + + def split(self): + """ + Splits the STL mesh into independent components based on the + distance threshold. Saves each component as a separate STL file. + """ + # Step 1: Initial component identification using DSU + logger.debug("Starting initial component identification") + dsu_original = self.DSUOriginal(self.num_triangles) + + # Process vertex map in batches to reduce memory pressure + batch_size = 10000 # Adjust based on available memory + vertex_items = list(self.vertex_map.items()) + for i in range(0, len(vertex_items), batch_size): + batch_end = min(i + batch_size, len(vertex_items)) + for _vert, tris in vertex_items[i:batch_end]: + if len(tris) > 1: + root = tris[0] + for t in tris[1:]: + dsu_original.union(root, t) + + # Step 2: Group triangles by component + logger.debug("Grouping triangles by component") + components = defaultdict(list) + for idx in range(self.num_triangles): + root = dsu_original.find(idx) + components[root].append(idx) + initial_components = list(components.values()) + del components # Free memory + + # Step 3: Extract vertices for each component + logger.debug(f"Processing {len(initial_components)} initial components") + component_info_list = [] + # Process components in batches to reduce memory pressure + batch_size = 100 # Adjust based on available memory + for i in range(0, len(initial_components), batch_size): + batch_end = min(i + batch_size, len(initial_components)) + batch_components = initial_components[i:batch_end] + + for comp in batch_components: + vertices = set() + # Process triangles in smaller chunks + chunk_size = 1000 # Adjust based on component size + for j in range(0, len(comp), chunk_size): + chunk_end = min(j + chunk_size, len(comp)) + for tri_idx in comp[j:chunk_end]: + triangle = self.original_mesh.vectors[tri_idx] + for vertex in triangle: + rounded_vertex = np.round(vertex, decimals=self.decimals) + vertices.add(tuple(rounded_vertex)) + + # Convert to numpy array efficiently + vertices = np.array([list(v) for v in vertices]) + component_info_list.append(ComponentInfo(vertices)) + + # Step 4: Merge components based on distance threshold + logger.debug("Merging components based on distance threshold") + dsu = DSU(component_info_list) + + # Use a more efficient merging strategy + roots = list({dsu.find(i) for i in range(len(component_info_list))}) + + # Pre-compute bounding box distances to avoid redundant calculations + merge_candidates = [] + for i in range(len(roots)): + for j in range(i + 1, len(roots)): + root_i = roots[i] + root_j = roots[j] + if dsu.find(root_i) != dsu.find(root_j): + info_i = dsu.info[root_i] + info_j = dsu.info[root_j] + dist_bbox = self.bbox_distance(info_i.bbox, info_j.bbox) + if dist_bbox <= self.distance_threshold: + merge_candidates.append((root_i, root_j, dist_bbox)) + + # Sort candidates by distance for more efficient merging + merge_candidates.sort(key=lambda x: x[2]) + + # Perform merging + for root_i, root_j, _ in merge_candidates: + if dsu.find(root_i) != dsu.find(root_j): + info_i = dsu.info[dsu.find(root_i)] + info_j = dsu.info[dsu.find(root_j)] + if self.has_nearby_points(info_i.vertices, info_j.vertices, self.distance_threshold): + dsu.union(root_i, root_j) + + # Step 5: Create final components + logger.debug("Creating final component meshes") + final_components = defaultdict(list) + for i, comp in enumerate(initial_components): + root = dsu.find(i) + final_components[root].extend(comp) + + logger.info(f"Split into {len(final_components)} independent models.") + + # Step 6: Save each component as a separate STL file + stl_files = [] + for comp_id, tri_indices in final_components.items(): + # Process in batches to reduce memory usage + batch_size = min(10000, len(tri_indices)) + data = np.zeros(len(tri_indices), dtype=mesh.Mesh.dtype) + + for i in range(0, len(tri_indices), batch_size): + end_idx = min(i + batch_size, len(tri_indices)) + batch_indices = tri_indices[i:end_idx] + data["vectors"][i:end_idx] = self.original_mesh.vectors[batch_indices] + data["normals"][i:end_idx] = self.original_mesh.normals[batch_indices] + + component_mesh = mesh.Mesh(data, remove_empty_areas=False) + file_path = os.path.join(os.path.dirname(self.stl_file), f"coronary_artery_{comp_id}.stl") + component_mesh.save(file_path) + stl_files.append(file_path) + + return stl_files + + # Helper class for DSU (Disjoint Set Union) operations + # specific to the triangles + class DSUOriginal: + def __init__(self, size): + self.parent = list(range(size)) + self.rank = [0] * size + + def find(self, x): + """ + Finds the root of the set containing x using path compression. + """ + if self.parent[x] != x: + self.parent[x] = self.find(self.parent[x]) + return self.parent[x] + + def union(self, x, y): + """ + Unites the sets containing x and y using union by rank. + """ + x_root = self.find(x) + y_root = self.find(y) + if x_root == y_root: + return + if self.rank[x_root] < self.rank[y_root]: + self.parent[x_root] = y_root + else: + self.parent[y_root] = x_root + if self.rank[x_root] == self.rank[y_root]: + self.rank[x_root] += 1 + + +class NNUnetPredictor: + """ + A class to handle NN-UNet-based segmentation tasks, including + preprocessing, prediction, and post-processing of segmentation results. + """ + + def __init__(self, input_path, output_path, dataset_id=66, configuration="3d_lowres"): + """ + Initializes the NNUnetPredictor class with input paths, output paths, + and model configuration. + """ + # Fixed paths for the nnUNet environment + self.instance_id = uuid.uuid4().hex + self.dataset_id = dataset_id + self.configuration = configuration + + self.base_name = Path(input_path).stem.split(".nii")[0] + self.temp_dir = TemporaryDirectory(prefix=f"nnunet_{self.instance_id}_") + try: + script_path = Path(os.path.abspath(__file__)) + self.raw_path = os.path.join(self.temp_dir.name, "nnUNet/nnUNet_raw") + self.preprocessed_path = os.path.join(script_path.parent, "nnUNet/nnUNet_preprocessed") + self.results_path = os.path.join(script_path.parent.parent.parent, "models/nnUNet_results") + self.model_weight = [ + os.path.join(script_path.parent.parent.parent, "models", f) + for f in os.listdir(os.path.join(script_path.parent.parent.parent, "models")) + if f.split(".")[-1] == "zip" + ] # check if any model weight exist + + # Path for coronary artery dataset and output + self.img_path = os.path.join(self.raw_path, f"Dataset{dataset_id:03d}_CoronaryArtery") + self.seg_path = os.path.join(self.temp_dir.name, "seg_output") + + # Input and output paths for CT data and results + self.input_path = input_path + self.output_path = output_path + self.coronary_nii_file = os.path.join(self.seg_path, f"{self.base_name}.nii.gz") + + # Initialize directory structure + self.create_directory(self.img_path) + self.create_directory(self.seg_path) + self.create_directory(self.output_path) + + except Exception as e: + # logger.error(f"Failed to initialize paths: {str(e)}") + raise RuntimeError(f"NNUnetPredictor initialization failed: {str(e)}") from e + + @staticmethod + def create_directory(path): + """Creates a directory if it does not exist.""" + os.makedirs(path, exist_ok=True) + + def _copy_input_file(self): + """Copy input file to nnUNet's expected location.""" + try: + shutil.copy(self.input_path, os.path.join(self.img_path, f"{self.base_name}_0000.nii.gz")) + except Exception as e: + # logger.error(f"Failed to copy input file: {str(e)}") + raise RuntimeError(f"Failed to copy input file: {str(e)}") from e + + def _run_nnunet(self): + """ + Runs the nnUNet prediction using the provided input and + model configuration. + """ + # Check if GPU is available and set device + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + + env = os.environ.copy() + env.update( + { + "nnUNet_raw": self.raw_path, + "nnUNet_preprocessed": self.preprocessed_path, + "nnUNet_results": self.results_path, + } + ) + + # Construct the nnUNet prediction command + command = [ + "nnUNetv2_predict", + "-i", + self.img_path, # Input folder + "-o", + self.seg_path, # Output folder + "-d", + f"{self.dataset_id:03d}", # Dataset ID + "-c", + self.configuration, # Configuration + "-device", + device.type, # Device (CPU or GPU) + "--disable_tta", + ] + + try: + subprocess.run( + command, check=True, env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, text=True + ) + shutil.move(self.coronary_nii_file, os.path.join(self.output_path, f"{self.base_name}.nii.gz")) + except subprocess.CalledProcessError as e: + logger.error( + f"Coronary artery <{os.path.basename(self.input_path)}> \ + segmentation inference failed with code {e.returncode}" + ) + raise RuntimeError("nnUNet prediction failed") from e + + def set_model_weight(self, model_weight): + """get model weight from zip file""" + env = os.environ.copy() + env.update( + { + "nnUNet_raw": self.raw_path, + "nnUNet_preprocessed": self.preprocessed_path, + "nnUNet_results": self.results_path, + } + ) + + # Construct the nnUNet prediction command + command = ["nnUNetv2_install_pretrained_model_from_zip", f"{model_weight}"] + + try: + subprocess.run( + command, check=True, env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, text=True + ) + except subprocess.CalledProcessError as e: + logger.error( + f"Coronary artery Segmentation: nnUnetv2 model weight \ + from {model_weight} failed to extract with code {e.returncode}" + ) + raise RuntimeError("Load the model weight is failed") from e + + def run(self): + """ + Runs the entire pipeline: file handling, nnUNet inference, + and result post-processing. + """ + try: + if self.model_weight: # get the model weight from + for w in self.model_weight: + self.set_model_weight(w) + + # Step 1: Copy input file to nnUNet's expected location + self._copy_input_file() + # Step 2: Run nnUNet inference + self._run_nnunet() + gc.collect() + + except FileNotFoundError as e: + logger.error(f"File not found error: {str(e)}") + raise RuntimeError(f"Input file not found or accessible: {str(e)}") from e + except PermissionError as e: + logger.error(f"Permission error: {str(e)}") + raise RuntimeError(f"Permission denied when accessing files: {str(e)}") from e + except subprocess.CalledProcessError as e: + logger.error(f"nnUNet process error (code {e.returncode}): {str(e)}") + raise RuntimeError(f"nnUNet processing failed with code {e.returncode}") from e + except Exception as e: + logger.error(f"Processing failed: {str(e)}") + raise RuntimeError(f"Coronary artery segmentation failed: {str(e)}") from e + finally: + # Clean up temporary directory + try: + self.temp_dir.cleanup() + logger.debug(f"Cleaned up temporary directory: {self.temp_dir.name}") + except Exception as cleanup_error: + logger.warning( + f"Failed to clean up temporary directory:\ + {str(cleanup_error)}" + ) diff --git a/models/CoronSegmentator/scripts/heart_digital_twin.py b/models/CoronSegmentator/scripts/heart_digital_twin.py new file mode 100644 index 00000000..56a49221 --- /dev/null +++ b/models/CoronSegmentator/scripts/heart_digital_twin.py @@ -0,0 +1,104 @@ +# -*- coding: utf-8 -*- +""" +File : heart_digital_twin.py +Author: John Y. Ke, MC. Chen, TY. Lin, YC. Chan +Copyright © 2025 Hon Hai Precision Industry Co.,Ltd. All rights reserved. +License: Apache License 2.0 + +Description: +This script performs . +""" + +import argparse +import gc +import logging +import os +from pathlib import Path + +import yaml +from monai.apps.utils import download_url +from scripts.coronaryArtery_segmentation.coronaryArtery_seg import NNUnetPredictor + +BUNDLE_ROOT = Path(__file__).parent.parent +DOWNLOAD_CONFIG = os.path.join(BUNDLE_ROOT, "large_file.yml") +NII_GZ_EXT = ".nii.gz" +STL_EXT = ".stl" +USD_EXT = ".usd" + +# Configure logging +logging.basicConfig( + level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", datefmt="%Y-%m-%d %H:%M:%S" +) +logger = logging.getLogger("HeartDigitalTwin") + + +def parse_arg(): + parser = argparse.ArgumentParser() + parser.add_argument( + "--json", default="./configs/inference.json", help="The json file which define the input config." + ) + + return parser.parse_args() + + +def create_output_folder(output_dir, nii_file): + """ + Create an output folder based on the + NIfTI file name (removes the suffix). + """ + seg_folder = os.path.join(output_dir, nii_file[: -len(NII_GZ_EXT)]) + os.makedirs(seg_folder, exist_ok=True) + return seg_folder + + +def run_coronary_artery_segmentation(nii_file_path, seg_folder): + """Perform coronary artery segmentation.""" + try: + NNUnetPredictor(nii_file_path, seg_folder).run() + logger.info(f"{os.path.basename(nii_file_path)} segmentation completed.") + except Exception as e: + logger.error(f"Coronary artery segmentation failed: {str(e)}") + raise + + +class CoroSegmentatorPipeline: + def __init__(self, input_params: dict): + self.input_image = input_params["inputFile"] + self.output_dir = input_params["outputDir"] + self.nii_file = os.path.basename(self.input_image) + + def run(self): + """ + Process a single NIfTI file: segment cardiac and coronary artery + regions, and convert to USD format. + """ + # Download the weights of models according to large_file.yml + with open(DOWNLOAD_CONFIG, "r") as file: + download_config = yaml.safe_load(file) + + for file_info in download_config["large_files"]: + rel_path = file_info.get("path") + url = file_info.get("url") + expected_hash = file_info.get("hash_val") + + destination_path = BUNDLE_ROOT / rel_path + destination_dir = Path(destination_path).parent + destination_dir.mkdir(parents=True, exist_ok=True) + download_url(url, filepath=destination_path, hash_val=expected_hash) + + logger.info(f"Starting processing of {self.nii_file}") + nii_path = self.input_image + seg_folder = create_output_folder(self.output_dir, self.nii_file) + try: + run_coronary_artery_segmentation(nii_path, seg_folder) + return True + except Exception as e: + logger.error(f"Processing failed for {self.nii_file}: {str(e)}") + # Remove the output folder if failed + if os.path.exists(seg_folder): + for f in os.listdir(seg_folder): + os.remove(os.path.join(seg_folder, f)) + os.rmdir(seg_folder) + return False + finally: + gc.collect()