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..6e4fda2a --- /dev/null +++ b/ci/unit_tests/test_coronaryArtery_ct_segmentation.py @@ -0,0 +1,86 @@ +# 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 tempfile +import unittest +from pathlib import Path +import sys + +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 = [ # inference + { + "bundle_root": "models\CoronSegmentator", + } +] + +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..38113901 --- /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.CoroSegmentator_Pipeline", + "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..b2c85d7b --- /dev/null +++ b/models/CoronSegmentator/configs/metadata.json @@ -0,0 +1,82 @@ +{ + "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.3.2", + "pytorch_version": "1.4.0", + "numpy_version": "2.3.1", + "required_packages_version": { + "fire": "0.7.0", + "monai": " 1.4.0", + "nnunetv2": "2.6.0", + "nibabel": "5.3.2", + "numpy": "2.3.1", + "numpy_stl": "3.2.0", + "pynrrd": "1.1.3", + "scipy": "1.16.0", + "simpleitk": "2.5.0", + "scikit-image": "0.25.2", + "torch": "2.7.0+cu126", + "trimesh": "4.6.10", + "usd_core": "25.5.1", + "numpy-stl": "3.2.0" + }, + "task": "Coronary artery ct segmentation", + "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 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.", + "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/cardiac_segmentation/auto3dseg_segresnet_inference.py b/models/CoronSegmentator/scripts/cardiac_segmentation/auto3dseg_segresnet_inference.py new file mode 100644 index 00000000..4a3c9180 --- /dev/null +++ b/models/CoronSegmentator/scripts/cardiac_segmentation/auto3dseg_segresnet_inference.py @@ -0,0 +1,263 @@ +""" +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 +""" + +import os +import time +from collections import OrderedDict + +import fire +import nrrd +import numpy as np +import torch +from monai.bundle import ConfigParser +from monai.data import decollate_batch, list_data_collate +from monai.inferers import SlidingWindowInfererAdapt +from monai.transforms import ( + Compose, + ConcatItemsd, + CropForegroundd, + EnsureTyped, + Invertd, + KeepLargestConnectedComponentd, + Lambdad, + LoadImaged, + NormalizeIntensityd, + Orientationd, + Resized, + ScaleIntensityRanged, + Spacingd, +) +from monai.utils import MetaKeys, convert_to_dst_type +from torch.cuda.amp import autocast + + +def logits2pred(logits, sigmoid=False, dim=1): + if isinstance(logits, (list, tuple)): + logits = logits[0] + + if sigmoid: + pred = torch.sigmoid(logits) + pred = pred >= 0.5 + else: + pred = torch.softmax(logits, dim=dim) + pred = torch.argmax(pred, dim=dim, keepdim=True).to(dtype=torch.uint8) + + return pred + + +@torch.no_grad() +def auto3dseg_inference( + model_file, + image_file, + result_file, + save_mode=None, + image_file_2=None, + image_file_3=None, + image_file_4=None, + **kwargs, +): + start_time = time.time() + timing_checkpoints = [] # list of (operation, time) tuples + + # Checking for model file + + if not os.path.exists(model_file): + raise ValueError("Cannot find model file:" + str(model_file)) + + checkpoint = torch.load(model_file, map_location="cpu") + + if "config" not in checkpoint: + raise ValueError("Config not found in checkpoint (not a auto3dseg/segresnet model):" + str(model_file)) + + config = checkpoint["config"] + + state_dict = checkpoint["state_dict"] + + epoch = checkpoint.get("epoch", 0) + best_metric = checkpoint.get("best_metric", 0) + sigmoid = config.get("sigmoid", False) + + model = ConfigParser(config["network"]).get_parsed_content() + model.load_state_dict(state_dict, strict=True) + + # print(f"Model epoch {epoch} metric {best_metric}") + + device = torch.device("cpu") if torch.cuda.device_count() == 0 else torch.device(0) + model = model.to(device=device, memory_format=torch.channels_last_3d) # gpu + model.eval() + + image_files = {} + for index, img in enumerate([image_file, image_file_2, image_file_3, image_file_4]): + if img is not None: + image_files[f"image{index + 1}"] = img + + keys = list(image_files.keys()) + + for img in image_files.keys(): + if image_files[img] is None or not os.path.exists(image_files[img]): + raise ValueError(f'Incorrect image filename for {img}: "{image_files[img]}"') + + # Loading volumes + loader = LoadImaged(keys=keys, ensure_channel_first=True, dtype=None, allow_missing_keys=True, image_only=False) + images_loaded = loader(image_files) + timing_checkpoints.append(("Loading volumes", time.time())) + + if len(keys) > 1: + # Loading size of image 1 + image1_shape = images_loaded[keys[0]].shape[1:] + # Resizing the other volumes if needed + for idx, img in enumerate(keys[1:]): + temp_shape = images_loaded[img].shape[-len(image1_shape) :] + if np.any(np.not_equal(image1_shape, temp_shape)): + # print(f"Volumes do not have the same size - Resizing volume {img}") + resizer = Resized(keys=img, spatial_size=image1_shape, mode="bilinear") + images_loaded = resizer(images_loaded) + timing_checkpoints.append((f"Resizing volume {img}", time.time())) + + # make input Transform chain + main_normalize_mode = config["normalize_mode"] + intensity_bounds = config["intensity_bounds"] + if len(keys) == 1: # only one input image + ts = [ + ConcatItemsd(keys=keys, name="image", dim=0), + EnsureTyped(keys="image", data_type="tensor", dtype=torch.float, allow_missing_keys=True), + ] + _add_normalization_transforms(ts, "image", main_normalize_mode, intensity_bounds) + else: # multiple input images + ts = [] + + extra_modalities = OrderedDict(config["extra_modalities"]) + normalize_modes = [main_normalize_mode] + list(extra_modalities.values()) + for key, normalize_mode in zip(keys, normalize_modes): + _add_normalization_transforms(ts, key, normalize_mode, intensity_bounds) + ts.extend( + [ + ConcatItemsd(keys=keys, name="image", dim=0), + EnsureTyped(keys="image", data_type="tensor", dtype=torch.float, allow_missing_keys=True), + ] + ) + + if config.get("orientation_ras", False): + print("Using orientation_ras") + # we assume LPS physical coordinate system orientation + # This code is only tested with NRRD files that use LPS space + ts.append(Orientationd(keys="image", axcodes="RAS")) # reorient # + if config.get("crop_foreground", True): + print("Using crop_foreground") + ts.append(CropForegroundd(keys="image", source_key="image1", margin=10, allow_smaller=True)) # subcrop + + if config.get("resample_resolution", None) is not None: + pixdim = list(config["resample_resolution"]) + print(f"Using resample with resample_resolution {pixdim}") + + ts.append( + Spacingd( + keys=["image"], + pixdim=list(pixdim), + mode=["bilinear"], + dtype=torch.float, + min_pixdim=np.array(pixdim) * 0.75, + max_pixdim=np.array(pixdim) * 1.25, + allow_missing_keys=True, + ) + ) + + inf_transform = Compose(ts) + + # sliding_inferrer + roi_size = config["roi_size"] + # roi_size = [224, 224, 144] + sliding_inferrer = SlidingWindowInfererAdapt( + roi_size=roi_size, sw_batch_size=1, overlap=0.625, mode="gaussian", cache_roi_weight_map=False, progress=True + ) + + # process DATA + batch_data = inf_transform([images_loaded]) + # original_affine = batch_data[0]['image_meta_dict']['original_affine'] + original_affine = batch_data[0]["image"].meta[MetaKeys.ORIGINAL_AFFINE] + batch_data = list_data_collate([batch_data]) + data = batch_data["image"].as_subclass(torch.Tensor).to(memory_format=torch.channels_last_3d, device=device) + timing_checkpoints.append(("Preprocessing", time.time())) + + # print("Running Inference ...") + with autocast(enabled=True): + logits = sliding_inferrer(inputs=data, network=model) + timing_checkpoints.append(("Inference", time.time())) + + # print(f"Logits {logits.shape}") + # logits -> preds + # print("Converting logits into predictions") + try: + pred = logits2pred(logits, sigmoid=sigmoid) + except RuntimeError as e: + if not logits.is_cuda: + raise e + print(f"logits2pred failed on GPU pred retrying on CPU {logits.shape}") + logits = logits.cpu() + pred = logits2pred(logits, sigmoid=sigmoid) + # print(f"preds {pred.shape}") + timing_checkpoints.append(("Logits", time.time())) + logits = None + + # pred = pred.cpu() # convert to CPU if the next step (reverse interpolation) is OOM on GPU + # invert loading transforms (uncrop, reverse-resample, etc) + post_transforms_list = [Invertd(keys="pred", orig_keys="image", transform=inf_transform, nearest_interp=True)] + ( + post_transforms_list.append(KeepLargestConnectedComponentd(keys="pred", num_components=2)) + if "whole-head" in model_file + else post_transforms_list + ) + post_transforms = Compose(post_transforms_list) + + batch_data["pred"] = convert_to_dst_type(pred, batch_data["image"], dtype=pred.dtype, device=pred.device)[ + 0 + ] # make Meta tensor + pred = [post_transforms(x)["pred"] for x in decollate_batch(batch_data)] + seg = pred[0][0] + + # print(f"preds inverted {seg.shape}") + timing_checkpoints.append(("Preds", time.time())) + + seg = seg.cpu().numpy().astype(np.uint8) + timing_checkpoints.append(("Convert to array", time.time())) + + # save result by copying all image metadata from the input, just replacing the voxel data + nrrd_header = nrrd.read_header(image_file) + nrrd.write(result_file, seg, nrrd_header) + timing_checkpoints.append(("Save", time.time())) + + # print("Computation time log:") + previous_start_time = start_time + for timing_checkpoint in timing_checkpoints: + # print(f" {timing_checkpoint[0]}: {timing_checkpoint[1] - previous_start_time:.2f} seconds") + previous_start_time = timing_checkpoint[1] + + # print(f"ALL DONE, result saved in {result_file}") + + +def _add_normalization_transforms(ts, key, normalize_mode, intensity_bounds): + if normalize_mode == "none": + pass + elif normalize_mode in ["range", "ct"]: + ts.append( + ScaleIntensityRanged( + keys=key, a_min=intensity_bounds[0], a_max=intensity_bounds[1], b_min=-1, b_max=1, clip=False + ) + ) + ts.append(Lambdad(keys=key, func=lambda x: torch.sigmoid(x))) + elif normalize_mode in ["meanstd", "mri"]: + ts.append(NormalizeIntensityd(keys=key, nonzero=True, channel_wise=True)) + elif normalize_mode in ["meanstdtanh"]: + ts.append(NormalizeIntensityd(keys=key, nonzero=True, channel_wise=True)) + ts.append(Lambdad(keys=key, func=lambda x: 3 * torch.tanh(x / 3))) + elif normalize_mode in ["pet"]: + ts.append(Lambdad(keys=key, func=lambda x: torch.sigmoid((x - x.min()) / x.std()))) + else: + raise ValueError("Unsupported normalize_mode" + str(normalize_mode)) + + +if __name__ == "__main__": + fire.Fire(auto3dseg_inference) diff --git a/models/CoronSegmentator/scripts/cardiac_segmentation/cardiac_seg.py b/models/CoronSegmentator/scripts/cardiac_segmentation/cardiac_seg.py new file mode 100644 index 00000000..57c8f52b --- /dev/null +++ b/models/CoronSegmentator/scripts/cardiac_segmentation/cardiac_seg.py @@ -0,0 +1,188 @@ +# -*- coding: utf-8 -*- +""" +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 automatic 3D cardiac segmentation using deep learning models and converts +the results to STL format for anatomical structures. +""" + +import concurrent.futures +import gc +import logging +import os +import shutil +import tempfile +import time +import uuid +from pathlib import Path + +import numpy as np +import SimpleITK as sitk +from scripts.cardiac_segmentation.auto3dseg_segresnet_inference import auto3dseg_inference +from scripts.file_process.file_conversion import FileConversion + +# Configure logging +logger = logging.getLogger("CardiacSeg") + + +class Auto3DSeg: + """ + A class for performing automatic 3D cardiac segmentation and STL conversion. + + Attributes: + input_path (str): Path to input medical image (NIfTI format) + output_path (str): Directory for output STL files + """ + + def __init__(self, input_path, output_path): + """Initialize the Auto3DSeg instance.""" + self.instance_id = uuid.uuid4().hex + self.input_path = input_path + self.output_path = output_path + self._setup_paths() + + def _setup_paths(self): + """Configure internal paths for model, scripts and temporary storage.""" + script_dir = Path(os.path.abspath(__file__)).parent + self.model_path = os.path.join(script_dir.parent.parent, "models/cardiacModel.pt") # Model file path + self.segments = [ + {"label": 1, "name": "heart"}, + {"label": 2, "name": "aorta"}, + {"label": 3, "name": "pulmonary_vein"}, + {"label": 11, "name": "atrial_appendage_left"}, + {"label": 12, "name": "superior_vena_cava"}, + {"label": 13, "name": "inferior_vena_cava"}, + ] + + @staticmethod + def create_directory(path): + """Creates a directory if it does not exist.""" + os.makedirs(path, exist_ok=True) + + @staticmethod + def _convert_to_nrrd(input_path, output_dir): + """Convert input image to NRRD format.""" + try: + base_name = Path(input_path).stem.split(".nii")[0] + nrrd_path = os.path.join(output_dir, f"{base_name}.nrrd") + FileConversion.convert_nii_to_nrrd(input_path, nrrd_path) + + logger.info(f"Conversion completed: {nrrd_path}") + return nrrd_path + except Exception as e: + # logger.error(f"File conversion failed: {str(e)}") + raise RuntimeError(f"File conversion failed: {str(e)}") + + def _run_segmentation(self, input_nrrd, output_dir): + """ "Execute the segmentation model inference.""" + seg_output_nrrd = os.path.join(output_dir, f"{Path(input_nrrd).stem}.nrrd") + + logger.info("Running cardiac segmentation") + try: + auto3dseg_inference(model_file=self.model_path, image_file=input_nrrd, result_file=seg_output_nrrd) + return seg_output_nrrd + except Exception as e: + # logger.error( + # f"Cardiac <{os.path.basename(self.input_path)}> segmentation inference failed with error: {e}." + # ) + raise RuntimeError("auto3dseg process failed") + + def _process_single_segment(self, seg_image, segment, output_dir): + """Process individual anatomical segment and convert to STL.""" + label = segment["label"] + name = segment["name"] + + if name == "pulmonary_vein": + return + + try: + mask = seg_image == label + # Create temporary NRRD + temp_nrrd = os.path.join(output_dir, f"{name}.nrrd") + sitk.WriteImage(mask, temp_nrrd) + del mask + + # Convert to STL + temp_stl = temp_nrrd.replace(".nrrd", ".stl") + FileConversion.convert_nrrd_to_stl(temp_nrrd, temp_stl, gaussian_sigma=1.2) + + # Move to final output + shutil.move(temp_stl, os.path.join(self.output_path, f"{name}.stl")) + + # Cleanup temporary files + os.remove(temp_nrrd) + except Exception as e: + # logger.error(f"Error processing {name}: {str(e)}") + raise e + finally: + gc.collect() + + def _process_segmentation_results(self, seg_nrrd_path, output_dir): + """Process all segments in parallel and generate STL files.""" + try: + seg_image = sitk.ReadImage(seg_nrrd_path) + + seg_array = np.unique(sitk.GetArrayFromImage(seg_image)) + unique_labels = set(seg_array) + segments_to_process = [s for s in self.segments if s["label"] in unique_labels] + logger.info( + f"Processing {len(segments_to_process)} segments out of {len(self.segments)} defined segments for {os.path.basename(seg_nrrd_path)}" + ) + workers = 4 # min(int(os.cpu_count() * 0.75), len(segments_to_process)) + with concurrent.futures.ThreadPoolExecutor( + max_workers=workers + ) as executor: + futures = [ + executor.submit(self._process_single_segment, seg_image, segment, output_dir) + for segment in self.segments + ] + + for future in concurrent.futures.as_completed(futures): + try: + future.result(timeout=300) + except TimeoutError as te: + future.cancel() + except Exception as e: + logger.error(f"processing task for {futures[future]} failed: {str(e)}") + # for segment in self.segments: + # self._process_single_segment(seg_image, segment, output_dir) + + FileConversion.convert_nrrd_to_nii( + seg_nrrd_path, os.path.join(self.output_path, f"{Path(seg_nrrd_path).stem}.nii") + ) + + os.remove(seg_nrrd_path) + del seg_image, seg_array + gc.collect() + except Exception as e: + raise RuntimeError(f"Result processing failed: {str(e)}") + + def run(self): + """Execute the complete processing pipeline.""" + start_time = time.time() + logger.info(f"Starting cardiac segmentation for {os.path.basename(self.input_path)}") + + self.create_directory(self.output_path) + + with ( + tempfile.TemporaryDirectory(prefix=f"CardiacSeg_Input_{self.instance_id}_") as input_tmp_dir, + tempfile.TemporaryDirectory(prefix=f"CardiacSeg_Output_{self.instance_id}_") as output_tmp_dir, + ): + try: + # Step 1: Convert input to NRRD + input_nrrd = self._convert_to_nrrd(self.input_path, input_tmp_dir) + # Step 2: Run segmentation + seg_nrrd = self._run_segmentation(input_nrrd, output_tmp_dir) + # Step 3: Process results + self._process_segmentation_results(seg_nrrd, output_tmp_dir) + except Exception as e: + # logger.error(f"Processing failed: {str(e)}") + raise e + + total_time = time.time() - start_time + logger.info( + f"Successfully completed all cardiac segmentation steps for {os.path.basename(self.input_path)} in {total_time:.2f}s" + ) 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..eb7fa4c0 --- /dev/null +++ b/models/CoronSegmentator/scripts/coronaryArtery_segmentation/coronaryArtery_seg.py @@ -0,0 +1,543 @@ +# -*- 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 concurrent.futures +import gc +import logging +import os +import shutil +import subprocess +import time +import uuid +from collections import defaultdict +from pathlib import Path +from tempfile import TemporaryDirectory +import traceback +import nibabel as nib +import numpy as np +import SimpleITK as sitk +import torch +from scipy.spatial import cKDTree +from scripts.file_process.file_conversion import FileConversion +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)) # Adaptive batch size + + # 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.heart_nii_file = os.path.join(self.output_path, f"{self.base_name}.nii") + self.coronary_nii_file = os.path.join(self.seg_path, f"{self.base_name}.nii.gz") + self.coronary_npz_file = os.path.join(self.seg_path, f"{self.base_name}.npz") + + # 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", + "--save_probabilities", + ] + + try: + subprocess.run( + command, check=True, env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, text=True + ) + logger.info( + f"Coronary artery <{os.path.basename(self.input_path)}> segmentation inference has been completed." + ) + 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, modelWeight): + """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"{modelWeight}"] + + try: + subprocess.run( + command, check=True, env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, text=True + ) + logger.info( + f"Coronary artery Segmentation: nnUnetv2 model weight was extracted successfully from {modelWeight}." + ) + except subprocess.CalledProcessError as e: + logger.error( + f"Coronary artery Segmentation: nnUnetv2 model weight from {modelWeight} failed to extract with code {e.returncode}" + ) + raise RuntimeError("Load the model weight is failed") from e + + def _process_results(self): + """Converts the NIfTI segmentation result to STL format and moves the result to the output directory.""" + + def process_file(nii_path): + """Process individual NIfTI file into split STLs.""" + try: + stl_path = os.path.join(os.path.dirname(nii_path), f"coronary_artery_{self.instance_id}.stl") + + FileConversion.convert_nrrd_to_stl(nii_path, stl_path, gaussian_sigma=0.6) + + split_files = STLSplitter(stl_path, distance_threshold=10, decimals=4).split() + for file in split_files: + # Move the STL file to the output directory + shutil.move(file, os.path.join(self.output_path, os.path.basename(file))) + except Exception as e: + logger.error(f"Error processing {nii_path}: {str(e)}. {traceback.print_exc()}") + raise + + nii_files = [os.path.join(self.seg_path, f) for f in os.listdir(self.seg_path) if f.endswith(".nii.gz")] + if not nii_files: + logger.warning("No NIfTI files found in the segmentation output directory") + return + + # Use thread pool for parallel processing with optimal number of workers + with concurrent.futures.ThreadPoolExecutor( + max_workers=min(int(os.cpu_count() * 0.75), len(nii_files)) + ) as executor: + futures = [executor.submit(process_file, nii_file) for nii_file in nii_files] + # Wait for all tasks to complete and handle exceptions + for future in concurrent.futures.as_completed(futures): + try: + future.result(timeout=300) + except TimeoutError as te: + future.cancel() + except Exception as e: + logger.error(f"processing task for {futures[future]} failed: {str(e)}") + + def run(self): + """Runs the entire pipeline: file handling, nnUNet inference, and result post-processing.""" + start_time = time.time() + try: + if self.model_weight: # get the model weight from + for w in self.model_weight: + self.set_model_weight(w) + + logger.info(f"Starting coronary artery segmentation for {os.path.basename(self.input_path)}") + + # Step 1: Copy input file to nnUNet's expected location + self._copy_input_file() + # Step 2: Run nnUNet inference + self._run_nnunet() + gc.collect() + # Step 3: Process segmentation results and convert them to STL + self._process_results() + + elapsed_time = time.time() - start_time + logger.info( + f"Completed coronary artery segmentation pipeline for {os.path.basename(self.input_path)} in {elapsed_time:.2f} seconds" + ) + 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/download.py b/models/CoronSegmentator/scripts/download.py new file mode 100644 index 00000000..789e0881 --- /dev/null +++ b/models/CoronSegmentator/scripts/download.py @@ -0,0 +1,55 @@ +import yaml +import hashlib +import os +from pathlib import Path +import gdown + +BUNDLE_ROOT = Path(__file__).parent.parent +DOWNLOAD_CONFIG = os.path.join(BUNDLE_ROOT, "large_file.yml") + +def _calculate_md5(filepath: Path, block_size: int = 65536) -> str: + """ + Calculate md5 value of file + """ + md5 = hashlib.md5() + + with open(filepath, 'rb') as f: + for block in iter(lambda: f.read(block_size), b''): + md5.update(block) + return md5.hexdigest() + +def _download(url, destination_path): + try: + gdown.download(url=url, output=str(destination_path), quiet=False, fuzzy=True) + except Exception as e: + raise e + +def download_and_verify(): + """ + Download the files accordding to DOWNLOAD_CONFIG and verify md5 value of every file + """ + with open(DOWNLOAD_CONFIG, 'r') as file: + downloadConfig = yaml.safe_load(file) + + for fileInfo in downloadConfig['large_files']: + rel_path = fileInfo.get("path") + url = fileInfo.get("url") + expected_hash = fileInfo.get("hash_val") + hash_type = fileInfo.get("hash_type") + if hash_type != 'md5': + raise ValueError(f'hash_type must be md5, but got {hash_type}') + + destination_path = BUNDLE_ROOT / rel_path + destination_dir = Path(destination_path).parent + + if destination_path.exists(): + actual_hash = _calculate_md5(destination_path) + if actual_hash == expected_hash: # If md5 correct, don't download again + continue + + destination_dir.mkdir(parents=True, exist_ok=True) + _download(url, destination_path) # download file + + final_hash = _calculate_md5(destination_path) + if final_hash != expected_hash: + raise RuntimeError(f"final_hash donesn't match expected_hash") diff --git a/models/CoronSegmentator/scripts/file_process/file_conversion.py b/models/CoronSegmentator/scripts/file_process/file_conversion.py new file mode 100644 index 00000000..f6a6787d --- /dev/null +++ b/models/CoronSegmentator/scripts/file_process/file_conversion.py @@ -0,0 +1,123 @@ +# -*- coding: utf-8 -*- +""" +File : file_conversion.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 conversion between different medical imaging formats including +NIfTI, NRRD, and STL for 3D visualization and processing. + +""" +import gc +import logging +import os +import numpy as np +import SimpleITK as sitk +import trimesh +from skimage.measure import marching_cubes + +# Configure logging +logger = logging.getLogger("FileConversion") + + +class FileConversion: + """ + Class for handling various medical image format conversions, such as NIfTI to NRRD, + and NIfTI/NRRD to STL format. + """ + + @staticmethod + def convert_nrrd_to_nii(nrrd_file, nii_file): + image = sitk.ReadImage(nrrd_file) + # save as NIfTI + sitk.WriteImage(image, nii_file) + + @staticmethod + def convert_nii_to_nrrd(nii_gz_file, nrrd_file): + """ + Converts a NIfTI (.nii.gz) file to NRRD format. + + Args: + nii_gz_file (str): Path to the NIfTI file. + nrrd_file (str): Path to save the converted NRRD file. + """ + try: + nii_image = sitk.ReadImage(nii_gz_file) + sitk.WriteImage(nii_image, nrrd_file) + logger.debug(f"Conversion successful: {os.path.basename(nrrd_file)}") + return True + except Exception as e: + # logger.error(f"Error converting NIfTI to NRRD: {e}") + raise RuntimeError(f"NIfTI to NRRD conversion failed: {str(e)}") + + @staticmethod + def convert_nrrd_to_stl(nrrd_file_path, stl_file_path, gaussian_sigma=1.0): + """ + Converts a NRRD file to STL format. It first reads the NRRD file, applies smoothing, + and then uses the marching cubes algorithm to extract the mesh and save it as an STL. + + Args: + nrrd_file_path (str): Path to the NRRD file. + stl_file_path (str): Path to save the resulting STL file. + gaussian_sigma (float): Sigma value for Gaussian smoothing (default: 1.0). + """ + try: + try: + logger.debug(f"Reading NRRD file: {nrrd_file_path}") + image = sitk.ReadImage(nrrd_file_path) + except Exception as e: + raise RuntimeError(f"Failed to read NRRD file: {str(e)}") + + # Apply Gaussian smoothing + logger.debug(f"Applying Gaussian smoothing with sigma={gaussian_sigma}") + try: + smoothed_image = sitk.SmoothingRecursiveGaussian(image, sigma=gaussian_sigma) + + metadata = { + "spacing": np.array(smoothed_image.GetSpacing()), + "origin": np.array(smoothed_image.GetOrigin()), + "direction": np.array(smoothed_image.GetDirection()).reshape(3, 3), + } + del image + except Exception as e: + del image # Free memory in case of error + raise RuntimeError(f"Failed during image smoothing: {str(e)}") + + logger.debug("Converting image to numpy array") + + volume_data = sitk.GetArrayFromImage(smoothed_image) + del smoothed_image + logger.debug("Generating mesh using marching cubes algorithm") + + if np.all(volume_data == 0): + + dummy_vertices = [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]] + dummy_faces = [[0, 1, 2]] + mesh_obj = trimesh.Trimesh(vertices=dummy_vertices, faces=dummy_faces) + + else: + verts, faces, _, _ = marching_cubes(volume_data, level=0.5) + del volume_data + + logger.debug("Transforming vertices to physical coordinates") + transform_matrix = np.diag(metadata["spacing"]) @ metadata["direction"].T + physical_verts = verts[:, [2, 1, 0]] @ transform_matrix + metadata["origin"] + del verts, transform_matrix + + logger.debug("Creating and processing mesh") + mesh_obj = trimesh.Trimesh(vertices=physical_verts, faces=faces) + del physical_verts, faces + + mesh_obj.process(validate=True) + logger.debug(f"Exporting mesh to STL: {stl_file_path}") + mesh_obj.export(stl_file_path) + logger.info(f"Successfully converted {os.path.basename(nrrd_file_path)} to STL") + + return True + except Exception as e: + # logger.error(f"Error converting NRRD to STL: {e}") + raise RuntimeError(f"NRRD to STL conversion failed: {str(e)}") from e + finally: + gc.collect() diff --git a/models/CoronSegmentator/scripts/heart_digital_twin.py b/models/CoronSegmentator/scripts/heart_digital_twin.py new file mode 100644 index 00000000..31c19cc4 --- /dev/null +++ b/models/CoronSegmentator/scripts/heart_digital_twin.py @@ -0,0 +1,147 @@ +# -*- 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 json +import logging +import os +import shutil +import time +from pathlib import Path + +from .download import download_and_verify +from scripts.cardiac_segmentation.cardiac_seg import Auto3DSeg +from scripts.coronaryArtery_segmentation.coronaryArtery_seg import NNUnetPredictor +from scripts.usd_design.usd_create import USDCreator + +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 parseArg(): + 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_cardiac_segmentation(nii_file_path, seg_folder): + """Perform cardiac segmentation.""" + try: + Auto3DSeg(nii_file_path, seg_folder).run() + logger.info(f"Cardiac segmentation completed for {os.path.basename(nii_file_path)}") + except Exception as e: + logger.error(f"Cardiac segmentation failed: {str(e)}") + raise + + +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"Coronary artery segmentation completed for {os.path.basename(nii_file_path)}") + except Exception as e: + logger.error(f"Coronary artery segmentation failed: {str(e)}") + raise + + +def convert_stl_to_usd(seg_folder, nii_file): + """ + Convert STL files to USD format and create material properties. + """ + stl_files = [f for f in os.listdir(seg_folder) if f.endswith(STL_EXT)] + if not stl_files: + raise FileNotFoundError("No STL files found for USD conversion") + + usd_path = os.path.join(seg_folder, nii_file.replace(NII_GZ_EXT, USD_EXT)) + if os.path.exists(usd_path): + os.remove(usd_path) + + try: + stl_full_paths = [os.path.join(seg_folder, f) for f in stl_files] + + USDCreator(stl_full_paths, usd_path).create_usd() + logger.info(f"USD file created at {usd_path}") + except Exception as e: + logger.error(f"USD creation failed: {str(e)}") + raise + finally: + # Force garbage collection after heavy processing + gc.collect() + + +class CoroSegmentator_Pipeline: + 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. + """ + start_time = time.time() + # Download the weights of models according to large_file.yml + logger.info(f"Starting downloading weights of models.") + download_and_verify() + + 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: + # Perform cardiac and coronary artery segmentation + run_cardiac_segmentation(nii_path, seg_folder) + run_coronary_artery_segmentation(nii_path, seg_folder) + # Explicit garbage collection after segmentation to free memory before USD conversion + gc.collect() + # Convert STL files to USD format + convert_stl_to_usd(seg_folder, self.nii_file) + # Clean intermediate files + for f in os.listdir(seg_folder): + file_path = os.path.join(seg_folder, f) + if os.path.isfile(file_path) and not file_path.endswith(USD_EXT): + os.remove(file_path) + # Copy Texture files to the output directory + script_dir = Path(os.path.abspath(__file__)).parent + usd_texture_folder = os.path.join(script_dir, "usd_design/textures") + out_texture_folder = os.path.join(seg_folder, "textures") + shutil.copytree(usd_texture_folder, out_texture_folder, dirs_exist_ok=True) + + # Log total processing time + logger.info(f"Total processing time for {self.nii_file}: {time.time() - start_time:.2f} seconds") + 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() diff --git a/models/CoronSegmentator/scripts/usd_design/environment_create.py b/models/CoronSegmentator/scripts/usd_design/environment_create.py new file mode 100644 index 00000000..ad632d8e --- /dev/null +++ b/models/CoronSegmentator/scripts/usd_design/environment_create.py @@ -0,0 +1,175 @@ +# -*- coding: utf-8 -*- +""" +File : environment_create.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 . + +""" +from pxr import Gf, Sdf, UsdGeom, UsdLux, UsdShade + + +class EnvironmentSetup: + def __init__(self, stage): + self.stage = stage + + def create_dome_light(self): + """ + Creates a dome light for the scene to illuminate the meshes. + """ + # Define the light scope + dome_light = UsdLux.DomeLight.Define(self.stage, "/Environment/Sky") + prim = dome_light.GetPrim() + shaping_api = UsdLux.ShapingAPI.Apply(prim) + + dome_light.CreateColorTemperatureAttr(6250) + dome_light.CreateEnableColorTemperatureAttr(True) + dome_light.CreateExposureAttr(9) + dome_light.CreateIntensityAttr(1) + + shaping_api.CreateShapingConeAngleAttr(180) + dome_light.CreateTextureFileAttr( + Sdf.AssetPath( + "https://omniverse-content-production.s3.us-west-2.amazonaws.com/Assets/Scenes/Templates/Default/SubUSDs/textures/CarLight_512x256.hdr" + ) + ) + dome_light.CreateTextureFormatAttr("latlong") + + prim.GetAttribute("visibility").Set("inherited") + + xform = UsdGeom.Xformable(prim) + translate_op = xform.AddTranslateOp() + rotate_op = xform.AddRotateXYZOp() + scale_op = xform.AddScaleOp() + + translate_op.Set(Gf.Vec3d(0, 305, 0)) + rotate_op.Set(Gf.Vec3d(0, -90, -90)) + scale_op.Set(Gf.Vec3d(1, 1, 1)) + + xform.SetXformOpOrder([translate_op, rotate_op, scale_op]) + + def create_distant_light(self): + distant_light = UsdLux.DistantLight.Define(self.stage, "/Environment/DistantLight") + prim = distant_light.GetPrim() + shaping_api = UsdLux.ShapingAPI.Apply(prim) + + # Input parameters + distant_light.CreateColorTemperatureAttr(7250) + distant_light.CreateEnableColorTemperatureAttr(True) + distant_light.CreateExposureAttr(10) + distant_light.CreateIntensityAttr(1) + shaping_api.CreateShapingConeAngleAttr(180) + distant_light.GetVisibilityAttr().Set("inherited") + + xform = UsdGeom.Xformable(prim) + translate_op = xform.AddTranslateOp() + rotate_op = xform.AddRotateXYZOp() + scale_op = xform.AddScaleOp() + + translate_op.Set(Gf.Vec3d(0, 305, 0)) + rotate_op.Set(Gf.Vec3d(-105, 0, 0)) + scale_op.Set(Gf.Vec3d(1, 1, 1)) + + xform.SetXformOpOrder([translate_op, rotate_op, scale_op]) + + def create_look_scope(self): + looks_scope = self.stage.DefinePrim("/Environment/Looks", "Scope") + + material = UsdShade.Material.Define(self.stage, "/Environment/Looks/Grid") + + shader = UsdShade.Shader.Define(self.stage, "/Environment/Looks/Grid/Shader") + shader.CreateIdAttr("Shader") + + shader.CreateImplementationSourceAttr("sourceAsset") + shader.SetSourceAsset("OmniPBR.mdl", "mdl") + shader.SetSourceAssetSubIdentifier("OmniPBR", "mdl") + + inputs = [ + ("albedo_add", Sdf.ValueTypeNames.Float, 0.0), + ("albedo_brightness", Sdf.ValueTypeNames.Float, 0.52), + ("albedo_desaturation", Sdf.ValueTypeNames.Float, 1.0), + ( + "diffuse_texture", + Sdf.ValueTypeNames.Asset, + "https://omniverse-content-production.s3.us-west-2.amazonaws.com/Assets/Scenes/Templates/Default/SubUSDs/textures/ov_uv_grids_basecolor_1024.png", + ), + ("project_uvw", Sdf.ValueTypeNames.Bool, False), + ("reflection_roughness_constant", Sdf.ValueTypeNames.Float, 0.333), + ("texture_rotate", Sdf.ValueTypeNames.Float, 0.0), + ("texture_scale", Sdf.ValueTypeNames.Float2, Gf.Vec2f(0.5, 0.5)), + ("texture_translate", Sdf.ValueTypeNames.Float2, Gf.Vec2f(0, 0)), + ("world_or_object", Sdf.ValueTypeNames.Bool, False), + ] + + for name, type_name, value in inputs: + inp = shader.CreateInput(name, type_name) + inp.Set(value) + if name == "diffuse_texture": + inp.GetAttr().SetColorSpace("sRBG") + + + output = shader.CreateOutput("out", Sdf.ValueTypeNames.Token) + + material.CreateOutput("mdl:displacement", Sdf.ValueTypeNames.Token).ConnectToSource( + shader.ConnectableAPI(), "out" + ) + material.CreateOutput("mdl:surface", Sdf.ValueTypeNames.Token).ConnectToSource(shader.ConnectableAPI(), "out") + material.CreateOutput("mdl:volume", Sdf.ValueTypeNames.Token).ConnectToSource(shader.ConnectableAPI(), "out") + + def cereate_ground(self): + mesh = UsdGeom.Mesh.Define(self.stage, "/Environment/ground") + material_api = UsdShade.MaterialBindingAPI.Apply(mesh.GetPrim()) + + + mesh.CreateExtentAttr([(-1400, -1400, 0), (1400, 1400, 0)]) + mesh.CreateFaceVertexCountsAttr([4]) + mesh.CreateFaceVertexIndicesAttr([0, 1, 3, 2]) + mesh.CreatePointsAttr([(-700, -700, 0), (700, -700, 0), (-700, 700, 0), (700, 700, 0)]) + mesh.CreateNormalsAttr([(0, 0, 1)] * 4) + mesh.SetNormalsInterpolation(UsdGeom.Tokens.faceVarying) + + primvar = UsdGeom.PrimvarsAPI(mesh).CreatePrimvar("st", Sdf.ValueTypeNames.TexCoord2fArray) + primvar.Set([(0, 0), (14, 0), (14, 14), (0, 14)]) + primvar.SetInterpolation(UsdGeom.Tokens.faceVarying) + + UsdGeom.PrimvarsAPI(mesh).CreatePrimvar("isMatteObject", Sdf.ValueTypeNames.Bool).Set(False) + + + material = UsdShade.Material(self.stage.GetPrimAtPath("/Environment/Looks/Grid")) + material_api.Bind(material, bindingStrength=UsdShade.Tokens.weakerThanDescendants) + + mesh.CreateSubdivisionSchemeAttr().Set("none") + mesh.GetVisibilityAttr().Set("inherited") + + xform = UsdGeom.Xformable(mesh.GetPrim()) + translate_op = xform.AddTranslateOp() + rotate_op = xform.AddRotateXYZOp() + scale_op = xform.AddScaleOp() + + translate_op.Set(Gf.Vec3d(0, 0, 0)) + rotate_op.Set(Gf.Vec3d(0, -90, -90)) + scale_op.Set(Gf.Vec3d(1, 1, 1)) + + xform.SetXformOpOrder([translate_op, rotate_op, scale_op]) + + def create_ground_collider(self): + ground_plane = UsdGeom.Plane.Define(self.stage, "/Environment/groundCollider") + + ground_plane.CreateAxisAttr("Y") + ground_plane.CreatePurposeAttr("guide") + + def create_environment(self): + env_xform = UsdGeom.Xform.Define(self.stage, "/Environment") + + env_prim = env_xform.GetPrim() + env_prim.CreateAttribute("ground:size", Sdf.ValueTypeNames.Int).Set(1400) + env_prim.CreateAttribute("ground:type", Sdf.ValueTypeNames.String).Set("On") + + self.create_dome_light() + self.create_distant_light() + self.create_look_scope() + self.cereate_ground() + self.stage.GetRootLayer().Save() diff --git a/models/CoronSegmentator/scripts/usd_design/shader_leather_red.py b/models/CoronSegmentator/scripts/usd_design/shader_leather_red.py new file mode 100644 index 00000000..c298e5a4 --- /dev/null +++ b/models/CoronSegmentator/scripts/usd_design/shader_leather_red.py @@ -0,0 +1,356 @@ +""" +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 +""" + +import os + +from pxr import Gf, Sdf, UsdShade + + +class LeatherRed: + def __init__(self, stage): + self.stage = stage + self.base_path = "/root/materials/Leather_red" + self.baseColor_url = self._get_texture_path("plane_divided_DefaultMaterial_BaseColor.jpg") + self.roughness_url = self._get_texture_path("plane_divided_DefaultMaterial_Roughness.jpg") + self.normal_url = self._get_texture_path("plane_divided_DefaultMaterial_Normal.jpg") + + @staticmethod + def _get_texture_path(filename): + return f"./textures/{filename}" + + def define_shader(self, path, mdl_source=None, sub_identifier=None): + shader = UsdShade.Shader.Define(self.stage, path) + + if mdl_source and sub_identifier: + shader.CreateImplementationSourceAttr(UsdShade.Tokens.sourceAsset) + shader.SetSourceAsset(Sdf.AssetPath(mdl_source), "mdl") + shader.SetSourceAssetSubIdentifier(sub_identifier, "mdl") + return shader + + def _create_shader(self, shader_path, shader_name, mdl_source=None, sub_identifier=None): + shader_path = shader_path.AppendChild(shader_name) + prim = self.stage.GetPrimAtPath(shader_path) + if not prim.IsValid(): + return self.define_shader(shader_path, mdl_source, sub_identifier) + return UsdShade.Shader(prim) + + def _create_node_graph(self, nodeGraph_path): + prim = self.stage.GetPrimAtPath(nodeGraph_path) + if not prim.IsValid(): + return UsdShade.NodeGraph.Define(self.stage, nodeGraph_path) + return UsdShade.NodeGraph(prim) + + def _create_texture_nodegraph(self, nodegraph_name, texture_url): + """Generic method to create texture node graphs.""" + nodegraph_path = Sdf.Path(self.base_path).AppendChild(nodegraph_name) + node_graph = UsdShade.NodeGraph.Define(self.stage, nodegraph_path) + + # Common input configuration + texture = node_graph.CreateInput("texture", Sdf.ValueTypeNames.Asset) + texture.Set(texture_url) + texture.GetAttr().SetColorSpace("raw") + texture.GetAttr().SetCustomData({"default": ""}) + texture.GetAttr().SetMetadata("displayGroup", "Bitmap parameters") + texture.GetAttr().SetMetadata("displayName", "Bitmap file") + + mono_source = node_graph.CreateInput("mono_source", Sdf.ValueTypeNames.Int) + mono_source.Set(2) + mono_source.GetAttr().SetCustomData({"default": 1}) + mono_source.GetAttr().SetMetadata( + "sdrMetadata", + { + "__SDR__enum_value": "mono_average", + "options": "mono_alpha:0|mono_average:1|mono_luminance:2|mono_maximum:3", + }, + ) + mono_source.GetAttr().SetMetadata("displayGroup", "Bitmap parameters") + mono_source.GetAttr().SetMetadata("displayName", "Scalar mode") + + brightness = node_graph.CreateInput("brightness", Sdf.ValueTypeNames.Float) + brightness.Set(1.0) + brightness.GetAttr().SetCustomData({"default": 1.0, "soft_range": {"min": 0.0, "max": 1.0}}) + brightness.GetAttr().SetMetadata("displayGroup", "Bitmap parameters") + brightness.GetAttr().SetMetadata("displayName", "Brightness") + + contrast = node_graph.CreateInput("contrast", Sdf.ValueTypeNames.Float) + contrast.Set(1.0) + contrast.GetAttr().SetCustomData({"default": 1.0, "soft_range": {"min": 0.0, "max": 1.0}}) + contrast.GetAttr().SetMetadata("displayGroup", "Bitmap parameters") + contrast.GetAttr().SetMetadata("displayName", "Contrast") + + scaling = node_graph.CreateInput("scaling", Sdf.ValueTypeNames.Float2) + scaling.Set(Gf.Vec2f(1.0, 1.0)) + scaling.GetAttr().SetCustomData({"default": Gf.Vec2f(1.0, 1.0)}) + scaling.GetAttr().SetMetadata("displayGroup", "Placement") + scaling.GetAttr().SetMetadata("displayName", "Tiling") + + translation = node_graph.CreateInput("translation", Sdf.ValueTypeNames.Float2) + translation.Set(Gf.Vec2f(0.0, 0.0)) + translation.GetAttr().SetCustomData({"default": Gf.Vec2f(0.0, 0.0)}) + translation.GetAttr().SetMetadata("displayGroup", "Placement") + translation.GetAttr().SetMetadata("displayName", "Offset") + + rotation = node_graph.CreateInput("rotation", Sdf.ValueTypeNames.Float) + rotation.Set(0.0) + rotation.GetAttr().SetCustomData({"default": 0.0}) + rotation.GetAttr().SetMetadata("displayGroup", "Placement") + rotation.GetAttr().SetMetadata("displayName", "Rotation") + + clip = node_graph.CreateInput("clip", Sdf.ValueTypeNames.Bool) + clip.Set(False) + clip.GetAttr().SetCustomData({"default": False}) + clip.GetAttr().SetMetadata("displayGroup", "Placement") + clip.GetAttr().SetMetadata("displayName", "Clip") + + texture_space = node_graph.CreateInput("texture_space", Sdf.ValueTypeNames.Int) + texture_space.Set(0) + texture_space.GetAttr().SetCustomData({"default": 0, "range": {"min": 0, "max": 3}}) + texture_space.GetAttr().SetMetadata("displayGroup", "Placement") + texture_space.GetAttr().SetMetadata("displayName", "UV space index") + + invert = node_graph.CreateInput("invert", Sdf.ValueTypeNames.Bool) + invert.Set(False) + invert.GetAttr().SetCustomData({"default": False}) + invert.GetAttr().SetMetadata("displayGroup", "Bitmap parameters") + invert.GetAttr().SetMetadata("displayName", "Invert image") + + # image_texture = { + # "texture": texture, "mono_source": mono_source, "brightness": brightness, "contrast": contrast, "translation": translation, + # "scaling": scaling, "rotation": rotation, "invert": invert, "texture_space": texture_space, "clip": clip, + # } + + file_texture = self._create_shader( + nodegraph_path, + "file_texture", + "nvidia/core_definitions.mdl", + "file_texture(texture_2d,::base::mono_mode,float,float,float2,float2,float,bool,int,bool)", + ) + + _texture = file_texture.CreateInput("texture", Sdf.ValueTypeNames.Asset) + _texture.GetAttr().SetColorSpace("sRGB") + _texture.ConnectToSource(texture) + file_texture.CreateInput("mono_source", Sdf.ValueTypeNames.Int).ConnectToSource(mono_source) + file_texture.CreateInput("brightness", Sdf.ValueTypeNames.Float).ConnectToSource(brightness) + file_texture.CreateInput("contrast", Sdf.ValueTypeNames.Float).ConnectToSource(contrast) + file_texture.CreateInput("translation", Sdf.ValueTypeNames.Float2).ConnectToSource(translation) + file_texture.CreateInput("scaling", Sdf.ValueTypeNames.Float2).ConnectToSource(scaling) + file_texture.CreateInput("rotation", Sdf.ValueTypeNames.Float).ConnectToSource(rotation) + file_texture.CreateInput("clip", Sdf.ValueTypeNames.Bool).ConnectToSource(clip) + file_texture.CreateInput("texture_space", Sdf.ValueTypeNames.Int).ConnectToSource(texture_space) + file_texture.CreateInput("invert", Sdf.ValueTypeNames.Bool).ConnectToSource(invert) + + file_texture_out = file_texture.CreateOutput("out", Sdf.ValueTypeNames.Token) + + # file_texture = self._create_file_texture(nodegraph_path, image_texture) + construct_color = self._create_construct_color(nodegraph_path, file_texture_out) + construct_float = self._create_construct_float(nodegraph_path, file_texture_out) + + # Create output connections + node_graph.CreateOutput("tex", Sdf.ValueTypeNames.Token).ConnectToSource(file_texture_out) + node_graph.CreateOutput("color", Sdf.ValueTypeNames.Color3f).ConnectToSource(construct_color) + node_graph.CreateOutput("mono", Sdf.ValueTypeNames.Float).ConnectToSource(construct_float) + + for channel, axis in [("r", "x"), ("g", "y"), ("b", "z")]: + node_graph.CreateOutput(channel, Sdf.ValueTypeNames.Float).ConnectToSource( + self._create_channel_shader(nodegraph_path, axis, construct_color).ConnectableAPI(), "out" + ) + + return node_graph + + def _create_file_texture(self, parent_path, image_texture=None): + """Creates a file texture shader with standard configuration.""" + file_texture = self._create_shader( + parent_path, + "file_texture", + "nvidia/core_definitions.mdl", + "file_texture(texture_2d,::base::mono_mode,float,float,float2,float2,float,bool,int,bool)", + ) + + for param in [ + "texture", + "mono_source", + "brightness", + "contrast", + "translation", + "scaling", + "rotation", + "invert", + "texture_space", + "clip", + ]: + texture = file_texture.CreateInput(param, image_texture[param].GetTypeName()) + if param == "texture": + texture.GetAttr().SetColorSpace("sRGB") + texture.ConnectToSource(image_texture[param]) + + return file_texture.CreateOutput("out", Sdf.ValueTypeNames.Token) + + def _create_construct_float(self, parent_path, file_texture): + """Creates a float constructor shader.""" + construct_float = self._create_shader( + parent_path, "construct_float", "nvidia/aux_definitions.mdl", "construct_float(::base::texture_return)" + ) + + construct_float.CreateInput("a", Sdf.ValueTypeNames.Token).ConnectToSource(file_texture) + return construct_float.CreateOutput("out", Sdf.ValueTypeNames.Float) + + def _create_construct_color(self, parent_path, file_texture): + """Creates a color constructor shader.""" + construct_color_path = parent_path.AppendChild("construct_color") + construct_color = self._create_shader( + parent_path, "construct_color", "nvidia/aux_definitions.mdl", "construct_color(::base::texture_return)" + ) + + construct_color.CreateInput("a", Sdf.ValueTypeNames.Token).ConnectToSource(file_texture) + return construct_color.CreateOutput("out", Sdf.ValueTypeNames.Color3f) + + def _create_channel_shader(self, parent_path, axis, construct_color): + """Creates a channel extractor shader.""" + axis_shader = self._create_shader(parent_path, axis, "nvidia/aux_definitions.mdl", f"{axis}(color)") + axis_shader.CreateInput("a", Sdf.ValueTypeNames.Color3f).ConnectToSource(construct_color) + return axis_shader + + def _configure_bsdf(self, bsdf, color_tex, rough_tex, normal_map): + """Configures the MDL principled BSDF inputs.""" + params = { + "coat_roughness": 0.03, + "diffuse_reflection_weight": 1.0, + "emission_intensity": 0.0, + "specular_reflection_weight": 0.5, + "specular_reflection_roughness": 0.5, + "specular_retro_reflection_roughness": 0.5, + "specular_retro_reflection_weight": 0.0, + "subsurface_scale": 50.0, + "subsurface_scattering_color": Gf.Vec3f(1, 0.2, 0.1), + "subsurface_transmission_color": Gf.Vec3f(0.8, 0.8, 0.8), + } + for name, value in params.items(): + bsdf.GetInput(name).Set(value) + + # Create type casts + color_cast = self._create_shader( + Sdf.Path(self.base_path), + "MDL_TypeCast1", + "nvidia/aux_definitions.mdl", + "construct_color(::base::texture_return)", + ) + color_cast.CreateInput("a", Sdf.ValueTypeNames.Token).ConnectToSource(color_tex.ConnectableAPI(), "tex") + + float_cast = self._create_shader( + Sdf.Path(self.base_path), "MDL_TypeCast2", "nvidia/aux_definitions.mdl", "construct_float" + ) + float_cast.CreateInput("a", Sdf.ValueTypeNames.Token).ConnectToSource(rough_tex.ConnectableAPI(), "tex") + + # Connect BSDF inputs + bsdf.GetInput("diffuse_reflection_color").ConnectToSource(color_cast.ConnectableAPI(), "out") + bsdf.GetInput("specular_reflection_roughness").ConnectToSource(float_cast.ConnectableAPI(), "out") + bsdf.GetInput("geometry_normal").ConnectToSource(normal_map.ConnectableAPI(), "out") + bsdf.GetInput("specular_transmission_color").ConnectToSource(color_cast.ConnectableAPI(), "out") + + def _create_normal_map(self): + """Creates the normal map shader network.""" + shader = self._create_shader( + Sdf.Path(self.base_path), "MDL_NormalMap", "nvidia/core_definitions.mdl", "normalmap_texture" + ) + inputs = [ + ("clip", Sdf.ValueTypeNames.Bool, {"customData": {"default": False}}), + ( + "factor", + Sdf.ValueTypeNames.Float, + {"customData": {"default": 1.0, "soft_range": {"min": 0.0, "max": 1.0}}}, + ), + ("flip", Sdf.ValueTypeNames.Bool, {"customData": {"default": False}}), + ( + "rotation", + Sdf.ValueTypeNames.Float, + {"customData": {"default": 0.0, "soft_range": {"min": 0.0, "max": 360.0}}}, + ), + ("scaling", Sdf.ValueTypeNames.Float2, {"customData": {"default": Gf.Vec2f(1.0, 1.0)}}), + ("texture", Sdf.ValueTypeNames.Asset, {"customData": {"default": ""}, "colorSpace": "raw"}), + ( + "texture_space", + Sdf.ValueTypeNames.Int, + {"customData": {"default": 0, "soft_range": {"min": 0, "max": 3}}}, + ), + ("translation", Sdf.ValueTypeNames.Float2, {"customData": {"default": Gf.Vec2f(0.0, 0.0)}}), + ] + + for name, type_name, data in inputs: + inp = shader.CreateInput(name, type_name) + if data["customData"]["default"]: + inp.Set(data["customData"]["default"]) + + if "customData" in data: + inp.GetAttr().SetCustomData(data["customData"]) + if "colorSpace" in data: + inp.GetAttr().SetColorSpace(data["colorSpace"]) + + shader.GetInput("texture").Set(self.normal_url) + shader.CreateOutput("out", Sdf.ValueTypeNames.Float3) + + return shader + + def _create_preview_bsdf(self): + """Creates the USD Preview Surface network.""" + # bsdf = self._create_shader(Sdf.Path(self.base_path), "preview_Principled_BSDF") + # bsdf.CreateIdAttr('UsdPreviewSurface') + bsdf = UsdShade.Shader(self.stage.GetPrimAtPath(f"{self.base_path}/preview_Principled_BSDF")) + + # Create texture components + uv_reader = self._create_shader(Sdf.Path(self.base_path), "preview_uvmap") + uv_reader.CreateIdAttr("UsdPrimvarReader_float2") + uv_reader.CreateInput("varname", Sdf.ValueTypeNames.Token).Set("st") + + color_tex = self._create_shader(Sdf.Path(self.base_path), "preview_Image_Texture") + color_tex.CreateIdAttr("UsdUVTexture") + color_tex.CreateInput("file", Sdf.ValueTypeNames.Asset).Set(self.baseColor_url) + color_tex.CreateInput("st", Sdf.ValueTypeNames.Float2).ConnectToSource(uv_reader.ConnectableAPI(), "result") + color_tex.CreateInput("scale", Sdf.ValueTypeNames.Float2).Set(Gf.Vec2f(2.0, 2.0)) + + rough_tex = self._create_shader(Sdf.Path(self.base_path), "preview_Image_Texture_001") + rough_tex.CreateIdAttr("UsdUVTexture") + rough_tex.CreateInput("file", Sdf.ValueTypeNames.Asset).Set(self.roughness_url) + rough_tex.CreateInput("st", Sdf.ValueTypeNames.Float2).ConnectToSource(uv_reader.ConnectableAPI(), "result") + rough_tex.CreateInput("scale", Sdf.ValueTypeNames.Float2).Set(Gf.Vec2f(2.0, 2.0)) + + normal_tex = self._create_shader(Sdf.Path(self.base_path), "preview_Image_Texture_002") + normal_tex.CreateIdAttr("UsdUVTexture") + normal_tex.CreateInput("file", Sdf.ValueTypeNames.Asset).Set(self.normal_url) + normal_tex.CreateInput("st", Sdf.ValueTypeNames.Float2).ConnectToSource(uv_reader.ConnectableAPI(), "result") + + # Configure BSDF inputs + bsdf.CreateInput("diffuseColor", Sdf.ValueTypeNames.Color3f).ConnectToSource(color_tex.ConnectableAPI(), "rgb") + bsdf.CreateInput("roughness", Sdf.ValueTypeNames.Float).ConnectToSource(rough_tex.ConnectableAPI(), "r") + bsdf.CreateInput("normal", Sdf.ValueTypeNames.Float3).ConnectToSource(normal_tex.ConnectableAPI(), "rgb") + + return bsdf + + def create_material(self, material): + """Main method to create the complete material.""" + # Create MDL networks + color_tex = self._create_texture_nodegraph("MDL_ImageTexture", self.baseColor_url) + rough_tex = self._create_texture_nodegraph("MDL_ImageTexture_001", self.roughness_url) + normal_map = self._create_normal_map() + + bsdf = UsdShade.Shader(self.stage.GetPrimAtPath(f"{self.base_path}/MDL_PrincipledBSDF")) + self._configure_bsdf(bsdf, color_tex, rough_tex, normal_map) + + # Create preview surface + preview_bsdf = self._create_preview_bsdf() + + # Connect material outputs + material.CreateOutput("mdl:surface", Sdf.ValueTypeNames.Token).ConnectToSource(bsdf.ConnectableAPI(), "out") + material.CreateOutput("surface", Sdf.ValueTypeNames.Token).ConnectToSource( + preview_bsdf.ConnectableAPI(), "surface" + ) + + self.stage.GetRootLayer().Save() + return material + + @staticmethod + def bind_material(prim, material_path): + """Binds material to a prim.""" + UsdShade.MaterialBindingAPI(prim).Bind(material_path) diff --git a/models/CoronSegmentator/scripts/usd_design/shaders.json b/models/CoronSegmentator/scripts/usd_design/shaders.json new file mode 100644 index 00000000..01b21143 --- /dev/null +++ b/models/CoronSegmentator/scripts/usd_design/shaders.json @@ -0,0 +1,358 @@ +{ + "materials": [ + { + "path": "/root/materials/pulmonary_vein", + "bsdf": { + "mdl_bsdf": { + "path": "/root/materials/pulmonary_vein/MDL_BSDF", + "coat_affect_color": 0, + "coat_roughness": 0.03, + "diffuse_reflection": { + "color": [ + 0.8005601, + 0.10309875, + 0.009150885 + ], + "weight": 1 + }, + "emission_intensity": 0, + "metalness": 0, + "specular_reflection": { + "ior": 1.5, + "roughness": 0.5, + "weight": 0.5, + "retro_reflection_roughness": 0.5, + "transmission_color": [ + 0.8005601, + 0.10309875, + 0.009150885 + ] + }, + "subsurface": { + "scale": 50, + "scattering_color": [ + 1, + 0.2, + 0.1 + ], + "transmission_color": [ + 0.8005601, + 0.10309875, + 0.009150885 + ] + } + }, + "preview_bsdf": { + "path": "/root/materials/pulmonary_vein/preview___________BSDF", + "base_color": [ + 0.8005601, + 0.10309875, + 0.009150885 + ], + "metallic": 0, + "clearcoat": 0, + "clearcoatRoughness": 0.03, + "ior": 1.5, + "opacity": 1, + "roughness": 0.5, + "specular": 0.5 + } + } + }, + { + "path": "/root/materials/inferior_vena_cava", + "bsdf": { + "mdl_bsdf": { + "path": "/root/materials/inferior_vena_cava/MDL_BSDF", + "coat_affect_color": 0, + "coat_roughness": 0.03, + "diffuse_reflection": { + "color": [ + 0.0528892, + 0.23003122, + 0.6850418 + ], + "weight": 1 + }, + "emission_intensity": 0, + "metalness": 0.2067, + "specular_reflection": { + "ior": 1.5, + "roughness": 0.8910614, + "weight": 0.5, + "retro_reflection_roughness": 0.5, + "transmission_color": [ + 0.0528892, + 0.23003122, + 0.6850418 + ] + }, + "subsurface": { + "scale": 50, + "scattering_color": [ + 1, + 0.2, + 0.1 + ], + "transmission_color": [ + 0.0528892, + 0.23003122, + 0.6850418 + ] + } + }, + "preview_bsdf": { + "path": "/root/materials/inferior_vena_cava/preview___________BSDF", + "base_color": [ + 0.0528892, + 0.23003122, + 0.6850418 + ], + "metallic": 0.20670392, + "clearcoat": 0, + "clearcoatRoughness": 0.03, + "ior": 1.5, + "opacity": 1, + "roughness": 0.5, + "specular": 0.5 + } + } + }, + { + "path": "/root/materials/superior_vena_cava", + "bsdf": { + "mdl_bsdf": { + "path": "/root/materials/superior_vena_cava/MDL_BSDF", + "coat_affect_color": 0, + "coat_roughness": 0.03, + "diffuse_reflection": { + "color": [ + 0.02660127, + 0.13505949, + 0.80003154 + ], + "weight": 1 + }, + "emission_intensity": 0, + "metalness": 0, + "specular_reflection": { + "ior": 1.5, + "roughness": 0.5, + "weight": 0.5, + "retro_reflection_roughness": 0.5, + "transmission_color": [ + 0.02660127, + 0.13505949, + 0.80003154 + ] + }, + "subsurface": { + "scale": 50, + "scattering_color": [ + 1, + 0.2, + 0.1 + ], + "transmission_color": [ + 0.02660127, + 0.13505949, + 0.80003154 + ] + } + }, + "preview_bsdf": { + "path": "/root/materials/superior_vena_cava/preview___________BSDF", + "base_color": [ + 0.02660127, + 0.13505949, + 0.80003154 + ], + "metallic": 0, + "clearcoat": 0, + "clearcoatRoughness": 0.03, + "ior": 1.5, + "opacity": 1, + "roughness": 0.5, + "specular": 0.5 + } + } + }, + { + "path": "/root/materials/aorta", + "bsdf": { + "mdl_bsdf": { + "path": "/root/materials/aorta/MDL_BSDF", + "coat_affect_color": 0, + "coat_roughness": 0.03, + "diffuse_reflection": { + "color": [ + 0.35301256, + 0.038471635, + 0.0062521454 + ], + "weight": 1 + }, + "emission_intensity": 0, + "metalness": 0, + "specular_reflection": { + "ior": 1.5, + "roughness": 0.5, + "weight": 0.5, + "retro_reflection_roughness": 0.5, + "transmission_color": [ + 0.35301256, + 0.038471635, + 0.0062521454 + ] + }, + "subsurface": { + "scale": 50, + "scattering_color": [ + 1, + 0.2, + 0.1 + ], + "transmission_color": [ + 0.35301256, + 0.038471635, + 0.0062521454 + ] + } + }, + "preview_bsdf": { + "path": "/root/materials/aorta/preview___________BSDF", + "base_color": [ + 0.35301256, + 0.038471635, + 0.0062521454 + ], + "metallic": 0, + "clearcoat": 0, + "clearcoatRoughness": 0.03, + "ior": 1.5, + "opacity": 1, + "roughness": 0.5, + "specular": 0.5 + } + } + }, + { + "path": "/root/materials/coronary_artery", + "bsdf": { + "mdl_bsdf": { + "path": "/root/materials/coronary_artery/MDL_BSDF", + "coat_affect_color": 0.87, + "coat_roughness": 0.03, + "diffuse_reflection": { + "color": [ + 0.96138996, + 0.9205587, + 0.9224509 + ], + "weight": 1 + }, + "emission_intensity": 0, + "metalness": 0.8155201, + "specular_reflection": { + "ior": 5.1, + "roughness": 0.5, + "weight": 0.5, + "retro_reflection_roughness": 0.5, + "transmission_color": [ + 0.91422546, + 0.009833587, + 0.05174394 + ] + }, + "subsurface": { + "scale": 50, + "scattering_color": [ + 1, + 0.2, + 0.1 + ], + "transmission_color": [ + 0.91422546, + 0.009833587, + 0.05174394 + ] + } + }, + "preview_bsdf": { + "path": "/root/materials/coronary_artery/preview___________BSDF", + "base_color": [ + 0.91422546, + 0.009833587, + 0.05174394 + ], + "metallic": 0.8155201, + "clearcoat": 0, + "clearcoatRoughness": 0.03, + "ior": 5.1, + "opacity": 1, + "roughness": 0.5, + "specular": 0.5 + } + } + }, + { + "path": "/root/materials/Leather_red", + "bsdf": { + "mdl_bsdf": { + "path": "/root/materials/Leather_red/MDL_PrincipledBSDF", + "coat_affect_color": 0, + "coat_roughness": 0, + "diffuse_reflection": { + "color": [ + 0.8, + 0.8, + 0.8 + ], + "weight": 1 + }, + "emission_intensity": 0, + "metalness": 0, + "specular_reflection": { + "ior": 1.5, + "roughness": 0.5, + "weight": 0.5, + "retro_reflection_roughness": 0.5, + "transmission_color": [ + 0.8, + 0.8, + 0.8 + ] + }, + "subsurface": { + "scale": 50, + "scattering_color": [ + 1, + 0.2, + 0.1 + ], + "transmission_color": [ + 0.8, + 0.8, + 0.8 + ] + } + }, + "preview_bsdf": { + "path": "/root/materials/Leather_red/preview_Principled_BSDF", + "base_color": [ + 0, + 0, + 0 + ], + "metallic": 0, + "clearcoat": 0, + "clearcoatRoughness": 0.03, + "ior": 1.5, + "opacity": 1, + "roughness": 0, + "specular": 0.5 + } + } + } + ] +} diff --git a/models/CoronSegmentator/scripts/usd_design/textures/plane_divided_DefaultMaterial_BaseColor.jpg b/models/CoronSegmentator/scripts/usd_design/textures/plane_divided_DefaultMaterial_BaseColor.jpg new file mode 100644 index 00000000..d3d29522 Binary files /dev/null and b/models/CoronSegmentator/scripts/usd_design/textures/plane_divided_DefaultMaterial_BaseColor.jpg differ diff --git a/models/CoronSegmentator/scripts/usd_design/textures/plane_divided_DefaultMaterial_Normal.jpg b/models/CoronSegmentator/scripts/usd_design/textures/plane_divided_DefaultMaterial_Normal.jpg new file mode 100644 index 00000000..10895f3e Binary files /dev/null and b/models/CoronSegmentator/scripts/usd_design/textures/plane_divided_DefaultMaterial_Normal.jpg differ diff --git a/models/CoronSegmentator/scripts/usd_design/textures/plane_divided_DefaultMaterial_Roughness.jpg b/models/CoronSegmentator/scripts/usd_design/textures/plane_divided_DefaultMaterial_Roughness.jpg new file mode 100644 index 00000000..75ff0eea Binary files /dev/null and b/models/CoronSegmentator/scripts/usd_design/textures/plane_divided_DefaultMaterial_Roughness.jpg differ diff --git a/models/CoronSegmentator/scripts/usd_design/usd_create.py b/models/CoronSegmentator/scripts/usd_design/usd_create.py new file mode 100644 index 00000000..a4c26708 --- /dev/null +++ b/models/CoronSegmentator/scripts/usd_design/usd_create.py @@ -0,0 +1,68 @@ +# -*- coding: utf-8 -*- +""" +File : usd_create.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 gc +import logging +import os + +from scripts.usd_design.usd_mesh_creator import USDMeshCreator +from scripts.usd_design.usd_shader_applier import USDShaderApplier + +logger = logging.getLogger("USDCreator") + + +class USDCreator: + """ + A class to handle the creation of USD files from input mesh files and apply materials using a shader file. + """ + + def __init__(self, input_files, output_file): + """nitialize the USDCreator class.""" + self.input_files = input_files + self.output_file = output_file + self.shader_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), "shaders.json") + + def create_usd(self): + """Create a USD file from the input mesh files and apply materials.""" + logger.info(f"Starting <{self.input_files}> USD creation process.") + try: + # Convert the input STL mesh files to USD format. + creator = USDMeshCreator(self.input_files, self.output_file) + mesh_paths = creator.convert_stl_to_usd() + + # Apply materials from a shader file to the generated USD meshes. + applier = USDShaderApplier(self.output_file, self.shader_file) + applier.apply_materials_to_mesh(mesh_paths) + except Exception as e: + logger.error(f"USD creation failed: {str(e)}") + finally: + gc.collect() + + +def main(input_files, output_file): + USDCreator(input_files, output_file).create_usd() + + +if __name__ == "__main__": + in_files = [ + "./../Output/7 Spiral 0.75-0.4 Bv44 2 ALL_0000/heart.stl", + "./../Output/7 Spiral 0.75-0.4 Bv44 2 ALL_0000/aorta.stl", + "./../Output/7 Spiral 0.75-0.4 Bv44 2 ALL_0000/pulmonary_vein.stl", + "./../Output/7 Spiral 0.75-0.4 Bv44 2 ALL_0000/atrial_appendage_left.stl", + "./../Output/7 Spiral 0.75-0.4 Bv44 2 ALL_0000/superior_vena_cava.stl", + "./../Output/7 Spiral 0.75-0.4 Bv44 2 ALL_0000/inferior_vena_cava.stl", + "./../Output/7 Spiral 0.75-0.4 Bv44 2 ALL_0000/coronary_artery_0.stl", + "./../Output/7 Spiral 0.75-0.4 Bv44 2 ALL_0000/coronary_artery_3.stl", + ] + out_file = "./../Output/7 Spiral 0.75-0.4 Bv44 2 ALL_0000/merge_7 Spiral 0.75-0.4 Bv44 2 ALL_0000.usd" + + main(in_files, out_file) diff --git a/models/CoronSegmentator/scripts/usd_design/usd_mesh_creator.py b/models/CoronSegmentator/scripts/usd_design/usd_mesh_creator.py new file mode 100644 index 00000000..09a3e909 --- /dev/null +++ b/models/CoronSegmentator/scripts/usd_design/usd_mesh_creator.py @@ -0,0 +1,164 @@ +# -*- coding: utf-8 -*- +""" +File : usd_mesh_creator.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 conversion of multiple STL files into a single USD file with optimized memory usage and performance. + +""" + +import concurrent.futures +import gc +import logging +import os + +import numpy as np +import trimesh +from pxr import Gf, Usd, UsdGeom, Vt +from scripts.usd_design.environment_create import EnvironmentSetup + +logger = logging.getLogger("UsdMeshCreator") + + +class USDMeshCreator: + """ + A class to convert 3D mesh files (e.g. STL) into USD format, apply materials and lighting, and save the results. + """ + + def __init__(self, input_files, output_file): + """Initialize the converter with input STL files and an output USD file.""" + self.input_files = input_files + self.output_file = output_file + self.stage = None + self.mesh_paths = [] + + @staticmethod + def _get_organ_name(file_path): + """Extract organ name from file path.""" + return os.path.basename(file_path).replace(".stl", "") + + @staticmethod + def load_mesh(input_file): + """Loads a 3D mesh from the specified file.""" + try: + return trimesh.load_mesh(input_file) + except Exception as e: + logger.error(f"Error loading mesh from {input_file}: {e}") + return None + + def get_paths(self, input_file): + """Returns the USD paths for the mesh depending on its file type.""" + organ_mesh = self._get_organ_name(input_file) + if organ_mesh: + return (f"/root/{organ_mesh}", f"/root/{organ_mesh}/_img_segmentation_{organ_mesh}") + return None, None + + def create_usd_mesh(self, mesh, xform_path, mesh_path): + """Creates a USD mesh from a trimesh object and adds it to the USD stage at the specified paths.""" + try: + # Create a root transform for scaling and translating the object + UsdGeom.Xform.Define(self.stage, xform_path) + # Create the mesh + usd_mesh = UsdGeom.Mesh.Define(self.stage, mesh_path) + + # Batch set attributes using numpy conversions + vertices = mesh.vertices.astype(np.float32) + usd_mesh.CreatePointsAttr(Vt.Vec3fArray.FromNumpy(vertices)) + + faces = mesh.faces.flatten().astype(np.int32) + usd_mesh.CreateFaceVertexIndicesAttr(Vt.IntArray.FromNumpy(faces)) + + counts = np.full(len(mesh.faces), 3, dtype=np.int32) + usd_mesh.CreateFaceVertexCountsAttr(Vt.IntArray.FromNumpy(counts)) + + self.mesh_paths.append(mesh_path) + return True + except Exception as e: + logger.error(f"Error creating USD mesh at {mesh_path}: {e}") + return False + + @staticmethod + def calculate_scene_center(meshes): + """Calculate the center of the scene based on mesh bounds.""" + if not meshes: + return Gf.Vec3f(0, 0, 0) + + all_mins = np.array([mesh.bounds[0] for mesh in meshes]) + all_maxs = np.array([mesh.bounds[1] for mesh in meshes]) + min_vals = np.min(all_mins, axis=0) + max_vals = np.max(all_maxs, axis=0) + + return Gf.Vec3f(*(min_vals + max_vals) / 2.0) + + def convert_stl_to_usd(self): + """Converts input STL files to USD format and saves them to the specified output file.""" + try: + self.stage = Usd.Stage.CreateNew(self.output_file) + EnvironmentSetup(self.stage).create_environment() + UsdGeom.SetStageUpAxis(self.stage, UsdGeom.Tokens.y) + + root_prim = UsdGeom.Xform.Define(self.stage, "/root") + root_xform = UsdGeom.Xformable(root_prim) + + anim_rotate_op = root_xform.AddRotateYOp(precision=UsdGeom.XformOp.PrecisionFloat, opSuffix="animation") + translate_op = root_xform.AddTranslateOp(UsdGeom.XformOp.PrecisionFloat, "translate_root") + root_xform.AddXformOp(UsdGeom.XformOp.TypeRotateX, UsdGeom.XformOp.PrecisionFloat, "rotate_root").Set(-90) + + # Load meshes in parallel + with concurrent.futures.ThreadPoolExecutor() as executor: + meshes = list(executor.map(self.load_mesh, self.input_files)) + # meshes = [self.load_mesh(file) for file in self.input_files] + + mesh_paths = [] + for input_file, mesh in zip(self.input_files, meshes): + xform_path, mesh_path = self.get_paths(input_file) + if self.create_usd_mesh(mesh, xform_path, mesh_path): + mesh_paths.append(mesh_path) + + if mesh_paths: + bbox_cache = UsdGeom.BBoxCache(Usd.TimeCode.Default(), includedPurposes=[UsdGeom.Tokens.default_]) + total_range = None + for mesh_path in mesh_paths: + mesh_prim = self.stage.GetPrimAtPath(mesh_path) + if not mesh_prim or not mesh_prim.IsValid(): + continue + bbox = bbox_cache.ComputeWorldBound(mesh_prim) + current_range = bbox.ComputeAlignedRange() + if total_range is None: + total_range = current_range + else: + total_range.UnionWith(current_range) + if total_range and not total_range.IsEmpty(): + bbox_min = total_range.GetMin() + bbox_max = total_range.GetMax() + + base_center = Gf.Vec3d( + (bbox_min[0] + bbox_max[0]) / 2, bbox_min[1], (bbox_min[2] + bbox_max[2]) / 2 + ) + + translation = -base_center + translate_op.Set(Gf.Vec3f(translation)) + + time_codes = [0, 96] + anim_rotate_op.Set(0.0, time_codes[0]) + anim_rotate_op.Set(360.0, time_codes[1]) + + + self.stage.SetStartTimeCode(time_codes[0]) + self.stage.SetEndTimeCode(time_codes[1]) + + # Save final USD file + self.stage.GetRootLayer().Save() + # Clean up references to help garbage collection + meshes.clear() + + return self.mesh_paths + except Exception as e: + logger.error(f"Error converting STL to USD: {e}") + self.stage = None + return [] + finally: + gc.collect() diff --git a/models/CoronSegmentator/scripts/usd_design/usd_shader_applier.py b/models/CoronSegmentator/scripts/usd_design/usd_shader_applier.py new file mode 100644 index 00000000..91b585ac --- /dev/null +++ b/models/CoronSegmentator/scripts/usd_design/usd_shader_applier.py @@ -0,0 +1,536 @@ +# -*- coding: utf-8 -*- +""" +File : usd_shader_applier.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 USD Material Rendering + +""" + +import gc +import json +import logging +import os + +from pxr import Gf, Sdf, Usd, UsdGeom, UsdShade +from scripts.usd_design.shader_leather_red import LeatherRed + +logger = logging.getLogger("USDShaderApplier") + + +class USDShaderApplier: + def __init__(self, usd_file, shader_file): + self.usd_file = usd_file + self.shader_file = shader_file + self.stage = None + self._shader_info_cache = None + + def _load_shader_info(self): + if self._shader_info_cache is not None: + return self._shader_info_cache + + try: + with open(self.shader_file, "r") as f: + self._shader_info_cache = json.load(f) + return self._shader_info_cache + except Exception as e: + logger.error(f"Error reading shader file {os.path.basename(self.shader_file)}: {e}") + return {"materials": []} + + def _set_shader_default_attributes(self, shader): + IOR_PRESET_OPTIONS = ( + "ior_acrylic_glass:0|ior_air:1|ior_crystal:2|ior_diamond:3|ior_emerald:4|" + "ior_ethanol:5|ior_flint_glass:6|ior_glass:7|ior_honey_21p_water:8|" + "ior_human_eye_aqueous_humor:9|ior_human_eye_cornea:10|" + "ior_human_eye_lens:11|ior_human_eye_vitreous_humor:12|" + "ior_human_skin:13|ior_human_hair:14|ior_human_wet_hair:15|" + "ior_ice:16|ior_milk:17|ior_olive_oil:18|ior_pearl:19|" + "ior_plastic:20|ior_sapphire:21|ior_soap_bubble:22|" + "ior_vacuum:23|ior_water_0c:24|ior_water_35c:25|" + "ior_water_100c:26|ior_custom:99" + ) + SCATTERING_COLORS_OPTIONS = ( + "scattering_colors_apple:0|scattering_colors_chicken:1|scattering_colors_cream:2|" + "scattering_colors_ketchup:3|scattering_colors_marble:4|scattering_colors_potato:5|" + "scattering_colors_skim_milk:6|scattering_colors_whole_milk:7|scattering_colors_skin_1:8|" + "scattering_colors_skin_2:9|scattering_colors_skin_3:10|scattering_colors_skin_4:11|" + "scattering_colors_custom:12" + ) + EMISSION_MODE_OPTIONS = "emission_lx:0|emission_nt:1" + + shader.CreateImplementationSourceAttr("sourceAsset") + shader.SetSourceAsset(Sdf.AssetPath("OmniSurface/OmniSurfaceBase.mdl"), "mdl") + shader.SetSourceAssetSubIdentifier("OmniSurfaceBase", "mdl") + + inputs = [ + ( + "coat_affect_color", + Sdf.ValueTypeNames.Float, + {"customData": {"default": 0.0, "range": {"min": 0.0, "max": 1.0}}}, + ), + ( + "coat_affect_roughness", + Sdf.ValueTypeNames.Float, + {"customData": {"default": 0.0, "range": {"min": 0.0, "max": 1.0}}}, + ), + ( + "coat_anisotropy", + Sdf.ValueTypeNames.Float, + {"customData": {"default": 0.0, "range": {"min": 0.0, "max": 1.0}}}, + ), + ( + "coat_anisotropy_rotation", + Sdf.ValueTypeNames.Float, + {"customData": {"default": 0.0, "soft_range": {"min": 0.0, "max": 1.0}}}, + ), + ("coat_color", Sdf.ValueTypeNames.Color3f, {"customData": {"default": Gf.Vec3f(1, 1, 1)}}), + ( + "coat_ior", + Sdf.ValueTypeNames.Float, + { + "customData": { + "default": 1.5, + "range": {"min": 0.0, "max": 3.4028235e38}, + "soft_range": {"min": 1.0, "max": 5.0}, + } + }, + ), + ( + "coat_ior_preset", + Sdf.ValueTypeNames.Int, + { + "customData": {"default": 99}, + "sdrMetadata": {"__SDR__enum_value": "ior_custom", "options": IOR_PRESET_OPTIONS}, + }, + ), + ("coat_normal", Sdf.ValueTypeNames.Float3, {"customData": {"default": Gf.Vec3f(0, 0, 0)}}), + ( + "coat_roughness", + Sdf.ValueTypeNames.Float, + {"customData": {"default": 0.1, "range": {"min": 0.0, "max": 1.0}}}, + ), + ( + "coat_weight", + Sdf.ValueTypeNames.Float, + {"customData": {"default": 0.0, "range": {"min": 0.0, "max": 1.0}}}, + ), + ("diffuse_reflection_color", Sdf.ValueTypeNames.Color3f, {"customData": {"default": Gf.Vec3f(1, 1, 1)}}), + ( + "diffuse_reflection_roughness", + Sdf.ValueTypeNames.Float, + {"customData": {"default": 0.0, "range": {"min": 0.0, "max": 1.0}}}, + ), + ( + "diffuse_reflection_weight", + Sdf.ValueTypeNames.Float, + {"customData": {"default": 0.8, "range": {"min": 0.0, "max": 1.0}}}, + ), + ("emission_color", Sdf.ValueTypeNames.Color3f, {"customData": {"default": Gf.Vec3f(1, 1, 1)}}), + ( + "emission_intensity", + Sdf.ValueTypeNames.Float, + {"customData": {"default": 1.0, "soft_range": {"min": 0.0, "max": 1000.0}}}, + ), + ( + "emission_mode", + Sdf.ValueTypeNames.Int, + { + "customData": {"default": 0}, + "sdrMetadata": {"__SDR__enum_value": "emission_lx", "options": EMISSION_MODE_OPTIONS}, + }, + ), + ( + "emission_temperature", + Sdf.ValueTypeNames.Float, + {"customData": {"default": 6500.0, "soft_range": {"min": 0.0, "max": 10000.0}}}, + ), + ("emission_use_temperature", Sdf.ValueTypeNames.Bool, {"customData": {"default": False}}), + ( + "emission_weight", + Sdf.ValueTypeNames.Float, + {"customData": {"default": 0.0, "range": {"min": 0.0, "max": 1.0}}}, + ), + ("enable_diffuse_transmission", Sdf.ValueTypeNames.Bool, {"customData": {"default": False}}), + ("enable_opacity", Sdf.ValueTypeNames.Bool, {"customData": {"default": False}}), + ("enable_specular_transmission", Sdf.ValueTypeNames.Bool, {"customData": {"default": False}}), + ("enable_thin_film", Sdf.ValueTypeNames.Bool, {"customData": {"default": False}}), + ("excludeFromWhiteMode", Sdf.ValueTypeNames.Bool, {"customData": {"default": False}}), + ("geometry_displacement", Sdf.ValueTypeNames.Float3, {"customData": {"default": Gf.Vec3f(0, 0, 0)}}), + ("geometry_normal", Sdf.ValueTypeNames.Float3, {"customData": {"default": Gf.Vec3f(0, 0, 0)}}), + ( + "geometry_opacity", + Sdf.ValueTypeNames.Float, + {"customData": {"default": 1.0, "range": {"min": 0.0, "max": 1.0}}}, + ), + ( + "geometry_opacity_threshold", + Sdf.ValueTypeNames.Float, + {"customData": {"default": 0.0, "range": {"min": 0.0, "max": 1.0}}}, + ), + ( + "metalness", + Sdf.ValueTypeNames.Float, + {"customData": {"default": 0.0, "range": {"min": 0.0, "max": 1.0}}}, + ), + ( + "specular_reflection_anisotropy", + Sdf.ValueTypeNames.Float, + {"customData": {"default": 0.0, "range": {"min": 0.0, "max": 1.0}}}, + ), + ( + "specular_reflection_anisotropy_rotation", + Sdf.ValueTypeNames.Float, + {"customData": {"default": 0.0, "soft_range": {"min": 0.0, "max": 1.0}}}, + ), + ("specular_reflection_color", Sdf.ValueTypeNames.Color3f, {"customData": {"default": Gf.Vec3f(1, 1, 1)}}), + ( + "specular_reflection_ior_preset", + Sdf.ValueTypeNames.Int, + { + "customData": {"default": 99}, + "sdrMetadata": {"__SDR__enum_value": "ior_custom", "options": IOR_PRESET_OPTIONS}, + }, + ), + ( + "specular_reflection_ior", + Sdf.ValueTypeNames.Float, + {"customData": {"default": 1.5, "soft_range": {"min": 1.0, "max": 5.0}}}, + ), + ( + "specular_reflection_roughness", + Sdf.ValueTypeNames.Float, + {"customData": {"default": 0.2, "range": {"min": 0.0, "max": 1.0}}}, + ), + ( + "specular_reflection_weight", + Sdf.ValueTypeNames.Float, + {"customData": {"default": 1.0, "range": {"min": 0.0, "max": 1.0}}}, + ), + ( + "specular_retro_reflection_color", + Sdf.ValueTypeNames.Color3f, + {"customData": {"default": Gf.Vec3f(1, 1, 1)}}, + ), + ( + "specular_retro_reflection_roughness", + Sdf.ValueTypeNames.Float, + {"customData": {"default": 0.3, "range": {"min": 0.0, "max": 1.0}}}, + ), + ( + "specular_retro_reflection_weight", + Sdf.ValueTypeNames.Float, + {"customData": {"default": 0.0, "range": {"min": 0.0, "max": 1.0}}}, + ), + ("specular_transmission_color", Sdf.ValueTypeNames.Color3f, {"customData": {"default": Gf.Vec3f(1, 1, 1)}}), + ( + "specular_transmission_dispersion_abbe", + Sdf.ValueTypeNames.Float, + { + "customData": { + "default": 0.0, + "range": {"min": 0.0, "max": 3.4028235e38}, + "soft_range": {"min": 0.0, "max": 100.0}, + } + }, + ), + ( + "specular_transmission_scatter_anisotropy", + Sdf.ValueTypeNames.Float, + {"customData": {"default": 0.0, "range": {"min": -1.0, "max": 1.0}}}, + ), + ( + "specular_transmission_scattering_color", + Sdf.ValueTypeNames.Color3f, + {"customData": {"default": Gf.Vec3f(0, 0, 0)}}, + ), + ( + "specular_transmission_scattering_depth", + Sdf.ValueTypeNames.Float, + { + "customData": { + "default": 0.0, + "range": {"min": 0.0, "max": 3.4028235e38}, + "soft_range": {"min": 0.0, "max": 100.0}, + } + }, + ), + ( + "specular_transmission_weight", + Sdf.ValueTypeNames.Float, + {"customData": {"default": 0.0, "range": {"min": 0.0, "max": 1.0}}}, + ), + ( + "subsurface_anisotropy", + Sdf.ValueTypeNames.Float, + {"customData": {"default": 0.0, "range": {"min": -1.0, "max": 1.0}}}, + ), + ( + "subsurface_scale", + Sdf.ValueTypeNames.Float, + { + "customData": { + "default": 1.0, + "omi": {"kit": {"property": {"usd": {"soft_range_ui": {"min": 0.0, "max": 50.0}}}}}, + "range": {"min": 0.0, "max": 3.4028235e38}, + "soft_range": {"min": 0.0, "max": 10.0}, + } + }, + ), + ("subsurface_scattering_color", Sdf.ValueTypeNames.Color3f, {"customData": {"default": Gf.Vec3f(1, 1, 1)}}), + ( + "subsurface_scattering_colors_preset", + Sdf.ValueTypeNames.Int, + { + "customData": {"default": 12}, + "sdrMetadata": { + "__SDR__enum_value": "scattering_colors_custom", + "options": SCATTERING_COLORS_OPTIONS, + }, + }, + ), + ( + "subsurface_transmission_color", + Sdf.ValueTypeNames.Color3f, + {"customData": {"default": Gf.Vec3f(1, 1, 1)}}, + ), + ( + "subsurface_weight", + Sdf.ValueTypeNames.Float, + {"customData": {"default": 0.0, "range": {"min": 0.0, "max": 1.0}}}, + ), + ( + "thin_film_ior", + Sdf.ValueTypeNames.Float, + { + "customData": { + "default": 1.52, + "range": {"min": 0.0, "max": 3.4028235e38}, + "soft_range": {"min": 1.0, "max": 3.0}, + } + }, + ), + ( + "thin_film_ior_preset", + Sdf.ValueTypeNames.Int, + { + "customData": {"default": 99}, + "sdrMetadata": {"__SDR__enum_value": "ior_custom", "options": IOR_PRESET_OPTIONS}, + }, + ), + ( + "thin_film_thickness", + Sdf.ValueTypeNames.Float, + { + "customData": { + "default": 400.0, + "range": {"min": 0.0, "max": 3.4028235e38}, + "soft_range": {"min": 0.0, "max": 2000.0}, + } + }, + ), + ("thin_walled", Sdf.ValueTypeNames.Bool, {"customData": {"default": False}}), + ] + + for name, type_name, data in inputs: + inp = shader.CreateInput(name, type_name) + attr = inp.GetAttr() + if "customData" in data: + if data["customData"]["default"] is not None: + inp.Set(data["customData"]["default"]) + + attr.SetCustomData(data["customData"]) + if "sdrMetadata" in data: + attr.SetMetadata("sdrMetadata", data["sdrMetadata"]) + + if "geometry_normal" == name: + attr.SetMetadata("hidden", True) + + self.stage.GetRootLayer().Save() + + def mdl_bsdf_shader_creater(self, material, shader_data): + try: + shader = UsdShade.Shader.Define(self.stage, shader_data["path"]) + + self._set_shader_default_attributes(shader) + + input_specs = [ + # (enter name, value type, datapath, conversion function) + ("coat_affect_color", Sdf.ValueTypeNames.Float, ["coat_affect_color"]), + ("coat_roughness", Sdf.ValueTypeNames.Float, ["coat_roughness"]), + ("diffuse_reflection_color", Sdf.ValueTypeNames.Color3f, ["diffuse_reflection", "color"]), + ("diffuse_reflection_weight", Sdf.ValueTypeNames.Float, ["diffuse_reflection", "weight"]), + ("emission_intensity", Sdf.ValueTypeNames.Float, ["emission_intensity"]), + ("metalness", Sdf.ValueTypeNames.Float, ["metalness"]), + ("specular_reflection_ior", Sdf.ValueTypeNames.Int, ["specular_reflection", "ior"]), + ("specular_reflection_roughness", Sdf.ValueTypeNames.Float, ["specular_reflection", "roughness"]), + ("specular_reflection_weight", Sdf.ValueTypeNames.Float, ["specular_reflection", "weight"]), + ( + "specular_retro_reflection_roughness", + Sdf.ValueTypeNames.Float, + ["specular_reflection", "retro_reflection_roughness"], + ), + ( + "specular_transmission_color", + Sdf.ValueTypeNames.Color3f, + ["specular_reflection", "transmission_color"], + ), + ("subsurface_scale", Sdf.ValueTypeNames.Float, ["subsurface", "scale"]), + ("subsurface_scattering_color", Sdf.ValueTypeNames.Color3f, ["subsurface", "scattering_color"]), + ("subsurface_transmission_color", Sdf.ValueTypeNames.Color3f, ["subsurface", "transmission_color"]), + ] + + for input_name, data_type, data_keys in input_specs: + try: + value = shader_data + for key in data_keys: + if key not in value: + logger.warning(f"Warning: Missing key '{key}' in shader data for input '{input_name}'") + continue + value = value[key] + + if data_type == Sdf.ValueTypeNames.Color3f: + value = Gf.Vec3f(*value) + + shader.GetInput(input_name).Set(value) + except Exception as e: + logger.error(f"Error setting input '{input_name}': {e}") + + material.CreateOutput("mdl:surface", Sdf.ValueTypeNames.Token).ConnectToSource( + shader.CreateOutput("out", Sdf.ValueTypeNames.Token) + ) + + return material + except Exception as e: + logger.error(f"Error creating MDL BSDF shader: {e}") + return material + + def preview_bsdf_shader_creater(self, material, shader_data): + try: + shader = UsdShade.Shader.Define(self.stage, shader_data["path"]) + shader.CreateIdAttr("UsdPreviewSurface") + + input_specs = [ + # (Enter name, value type, shader_data key,) + ("clearcoat", Sdf.ValueTypeNames.Float, "clearcoat"), + ("clearcoatRoughness", Sdf.ValueTypeNames.Float, "clearcoatRoughness"), + ("diffuseColor", Sdf.ValueTypeNames.Color3f, "base_color"), + ("ior", Sdf.ValueTypeNames.Float, "ior"), + ("metallic", Sdf.ValueTypeNames.Float, "metallic"), + ("opacity", Sdf.ValueTypeNames.Float, "opacity"), + ("roughness", Sdf.ValueTypeNames.Float, "roughness"), + ("specular", Sdf.ValueTypeNames.Float, "specular"), + ] + + for input_name, value_type, data_key in input_specs: + try: + if data_key not in shader_data: + logger.warning(f"Warning: Missing key '{data_key}' in preview shader data") + continue + + value = shader_data[data_key] + if value_type == Sdf.ValueTypeNames.Color3f: + value = Gf.Vec3f(*value) + + shader.CreateInput(input_name, value_type).Set(value) + except Exception as e: + logger.error(f"Error setting preview input '{input_name}': {e}") + + # Connect shader to material outputs + material.CreateOutput("surface", Sdf.ValueTypeNames.Token).ConnectToSource( + shader.CreateOutput("surface", Sdf.ValueTypeNames.Token) + ) + + return material + except Exception as e: + logger.error(f"Error creating preview BSDF shader: {e}") + return material + + def create_material(self, material_path, shader_data): + """Creates and returns a USD material with the specified properties.""" + try: + # Define material and shader + prim = self.stage.GetPrimAtPath(Sdf.Path(material_path)) + material = ( + UsdShade.Material.Define(self.stage, material_path) if not prim.IsValid() else UsdShade.Material(prim) + ) + + if "mdl_bsdf" in shader_data: + material = self.mdl_bsdf_shader_creater(material, shader_data["mdl_bsdf"]) + + if "preview_bsdf" in shader_data: + material = self.preview_bsdf_shader_creater(material, shader_data["preview_bsdf"]) + + return material + except Exception as e: + logger.error(f"Error creating material at {material_path}: {e}") + return None + + def _create_material_with_override(self, shader_data, leather_red): + try: + material = self.create_material(shader_data["path"], shader_data["bsdf"]) + if material and os.path.basename(shader_data["path"]) == "Leather_red": + return leather_red.create_material(material) + return material + except Exception as e: + logger.error(f"Error creating material with override: {e}") + return None + + def apply_materials_to_mesh(self, mesh_paths): + """Applies material properties to the USD file by creating materials and binding them to prims.""" + try: + self.stage = Usd.Stage.Open(self.usd_file) + if not self.stage: + logger.error(f"Error: Could not open USD file {self.usd_file}") + return False + + leather_red = LeatherRed(self.stage) + + materials_root = "/root/materials" + if not self.stage.GetPrimAtPath(materials_root): + UsdGeom.Scope.Define(self.stage, materials_root) + + material_bindings = { + os.path.basename(shader_data["path"]): self._create_material_with_override(shader_data, leather_red) + for shader_data in self._load_shader_info()["materials"] + } + + coronary_material = material_bindings.get("coronary_artery") + leather_red_material = material_bindings.get("Leather_red") + + for mesh_path in mesh_paths: + prim = self.stage.GetPrimAtPath(mesh_path) + if not prim.IsValid(): + continue + + organ_name = mesh_path.split("/")[2] + material = ( + material_bindings.get(organ_name) + or (coronary_material if "coronary_artery" in organ_name else None) + or (leather_red_material if organ_name in ["heart", "atrial_appendage_left"] else None) + ) + + if material: + binding_api = UsdShade.MaterialBindingAPI.Apply(prim) + if organ_name in ["heart", "atrial_appendage_left"] and material == leather_red_material: + leather_red.bind_material(prim, material) + else: + binding_api.Bind(material) + + # Memory management cleanup + self._shader_info_cache = None + material_bindings.clear() + del leather_red + + # Save the modified USD file + self.stage.GetRootLayer().Save() + logger.info(f"Successfully applied materials to {os.path.basename(self.usd_file)}") + except Exception as e: + logger.error(f"Error applying materials: {e}") + return False + finally: + if self.stage: + self.stage = None + gc.collect()