meniscus2brep 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,202 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
202
+
@@ -0,0 +1,79 @@
1
+ Metadata-Version: 2.4
2
+ Name: meniscus2brep
3
+ Version: 0.1.0
4
+ Summary: Convert meniscus images to B-rep geometry
5
+ Author: Scott Sibole
6
+ Author-email: Scott Sibole <scott.sibole@gmail.com>
7
+ License-Expression: Apache-2.0
8
+ License-File: LICENSE
9
+ Requires-Dist: gmsh>=4.15.2
10
+ Requires-Dist: loguru>=0.7.3
11
+ Requires-Dist: numpy>=2.5.4
12
+ Requires-Dist: pydantic>=2.14.3
13
+ Requires-Dist: scipy>=1.18.1
14
+ Requires-Dist: simpleitk>=2.5.7
15
+ Requires-Dist: vtk>=9.7.2
16
+ Requires-Python: >=3.13
17
+ Description-Content-Type: text/markdown
18
+
19
+ # meniscus2brep
20
+
21
+ [![PyPI](https://img.shields.io/pypi/v/meniscus2brep)](https://pypi.org/project/meniscus2brep/)
22
+ [![Coverage](https://img.shields.io/endpoint?url=https://comporthobiomech.github.io/meniscus2brep/coverage.json)](https://github.com/CompOrthoBiomech/meniscus2brep/actions/workflows/release.yml)
23
+ [![Docs](https://img.shields.io/badge/docs-gh--pages-blue)](https://comporthobiomech.github.io/meniscus2brep/)
24
+
25
+ Generate B-rep geometry of a meniscus from a segmentation LabelMap, and mesh it with high-quality elements:
26
+
27
+ - **B-rep from segmentation labels.** Reads a LabelMap (`.nii`, `.nrrd`, or `.mhd`), fits a centerline through the labeled meniscus, slices its smoothed surface into cross-section contours, and lofts them into a solid B-spline B-rep (`.brep`) with planar or smooth end caps.
28
+ - **Tetrahedral meshing** with linear 4-node or quadratic 10-node tetrahedra.
29
+ - **Hexahedral meshing** with block-structured 8-node, 20-node, or 27-node hexahedra. The solid is split into a butterfly (O-grid) of five blocks, so elements stay well shaped at the meniscus's sharp corners.
30
+
31
+ Meshes are written in any format gmsh infers from the file extension, such as `.msh`, `.vtk`, or `.inp`.
32
+
33
+ **Documentation:** <https://comporthobiomech.github.io/meniscus2brep/>
34
+
35
+ ## Installation
36
+
37
+ ```sh
38
+ pip install meniscus2brep
39
+ ```
40
+
41
+ ## Usage
42
+
43
+ Two command-line pipelines take a JSON configuration, `--option value` overrides, or both. Run either with `--help` to list every option and its default.
44
+
45
+ ```sh
46
+ meniscus2brep-brep --label-map knee.nii --output meniscus.brep --cap planar
47
+ meniscus2brep-mesh --brep meniscus.brep --output meniscus.msh --max-size 1.0
48
+ ```
49
+
50
+ Each run saves the configuration it used, so it can be repeated with `--config`. Without `--config` it is saved as `settings<timestamp>.json` in the working directory. With `--config` and overrides, the changed configuration is saved beside the original as `<name>_modified.json`.
51
+
52
+ ### Element types
53
+
54
+ | Elements | B-rep options | Mesh options |
55
+ |---|---|---|
56
+ | 4-node tetrahedra | | `--element tetrahedral` (the default) |
57
+ | 10-node tetrahedra | | `--element tetrahedral --element-order 2` |
58
+ | 8-node hexahedra | `--hex-blocks true --points-per-slice 10` | `--element hexahedral` |
59
+ | 20-node hexahedra | `--hex-blocks true --points-per-slice 10` | `--element hexahedral --element-order 2 --second-order-incomplete true` |
60
+ | 27-node hexahedra | `--hex-blocks true --points-per-slice 10` | `--element hexahedral --element-order 2` |
61
+
62
+ ## Development
63
+
64
+ Requires [uv](https://docs.astral.sh/uv/).
65
+
66
+ ```sh
67
+ uv sync
68
+ uv run pytest
69
+ ```
70
+
71
+ Build the documentation into `docs/_build/html`:
72
+
73
+ ```sh
74
+ uv run --group docs sphinx-build -W -b html docs docs/_build/html
75
+ ```
76
+
77
+ ## License
78
+
79
+ Licensed under the [Apache License 2.0](LICENSE).
@@ -0,0 +1,61 @@
1
+ # meniscus2brep
2
+
3
+ [![PyPI](https://img.shields.io/pypi/v/meniscus2brep)](https://pypi.org/project/meniscus2brep/)
4
+ [![Coverage](https://img.shields.io/endpoint?url=https://comporthobiomech.github.io/meniscus2brep/coverage.json)](https://github.com/CompOrthoBiomech/meniscus2brep/actions/workflows/release.yml)
5
+ [![Docs](https://img.shields.io/badge/docs-gh--pages-blue)](https://comporthobiomech.github.io/meniscus2brep/)
6
+
7
+ Generate B-rep geometry of a meniscus from a segmentation LabelMap, and mesh it with high-quality elements:
8
+
9
+ - **B-rep from segmentation labels.** Reads a LabelMap (`.nii`, `.nrrd`, or `.mhd`), fits a centerline through the labeled meniscus, slices its smoothed surface into cross-section contours, and lofts them into a solid B-spline B-rep (`.brep`) with planar or smooth end caps.
10
+ - **Tetrahedral meshing** with linear 4-node or quadratic 10-node tetrahedra.
11
+ - **Hexahedral meshing** with block-structured 8-node, 20-node, or 27-node hexahedra. The solid is split into a butterfly (O-grid) of five blocks, so elements stay well shaped at the meniscus's sharp corners.
12
+
13
+ Meshes are written in any format gmsh infers from the file extension, such as `.msh`, `.vtk`, or `.inp`.
14
+
15
+ **Documentation:** <https://comporthobiomech.github.io/meniscus2brep/>
16
+
17
+ ## Installation
18
+
19
+ ```sh
20
+ pip install meniscus2brep
21
+ ```
22
+
23
+ ## Usage
24
+
25
+ Two command-line pipelines take a JSON configuration, `--option value` overrides, or both. Run either with `--help` to list every option and its default.
26
+
27
+ ```sh
28
+ meniscus2brep-brep --label-map knee.nii --output meniscus.brep --cap planar
29
+ meniscus2brep-mesh --brep meniscus.brep --output meniscus.msh --max-size 1.0
30
+ ```
31
+
32
+ Each run saves the configuration it used, so it can be repeated with `--config`. Without `--config` it is saved as `settings<timestamp>.json` in the working directory. With `--config` and overrides, the changed configuration is saved beside the original as `<name>_modified.json`.
33
+
34
+ ### Element types
35
+
36
+ | Elements | B-rep options | Mesh options |
37
+ |---|---|---|
38
+ | 4-node tetrahedra | | `--element tetrahedral` (the default) |
39
+ | 10-node tetrahedra | | `--element tetrahedral --element-order 2` |
40
+ | 8-node hexahedra | `--hex-blocks true --points-per-slice 10` | `--element hexahedral` |
41
+ | 20-node hexahedra | `--hex-blocks true --points-per-slice 10` | `--element hexahedral --element-order 2 --second-order-incomplete true` |
42
+ | 27-node hexahedra | `--hex-blocks true --points-per-slice 10` | `--element hexahedral --element-order 2` |
43
+
44
+ ## Development
45
+
46
+ Requires [uv](https://docs.astral.sh/uv/).
47
+
48
+ ```sh
49
+ uv sync
50
+ uv run pytest
51
+ ```
52
+
53
+ Build the documentation into `docs/_build/html`:
54
+
55
+ ```sh
56
+ uv run --group docs sphinx-build -W -b html docs docs/_build/html
57
+ ```
58
+
59
+ ## License
60
+
61
+ Licensed under the [Apache License 2.0](LICENSE).
@@ -0,0 +1,44 @@
1
+ [project]
2
+ name = "meniscus2brep"
3
+ version = "0.1.0"
4
+ description = "Convert meniscus images to B-rep geometry"
5
+ readme = "README.md"
6
+ license = "Apache-2.0"
7
+ license-files = ["LICENSE"]
8
+ authors = [
9
+ { name = "Scott Sibole", email = "scott.sibole@gmail.com" }
10
+ ]
11
+ requires-python = ">=3.13"
12
+ dependencies = [
13
+ "gmsh>=4.15.2",
14
+ "loguru>=0.7.3",
15
+ "numpy>=2.5.4",
16
+ "pydantic>=2.14.3",
17
+ "scipy>=1.18.1",
18
+ "simpleitk>=2.5.7",
19
+ "vtk>=9.7.2",
20
+ ]
21
+
22
+ [project.scripts]
23
+ meniscus2brep-brep = "meniscus2brep.pipeline:brep_main"
24
+ meniscus2brep-mesh = "meniscus2brep.pipeline:mesh_main"
25
+
26
+ [build-system]
27
+ requires = ["uv_build>=0.8.13,<0.9.0"]
28
+ build-backend = "uv_build"
29
+
30
+ [dependency-groups]
31
+ dev = [
32
+ "pytest>=9.2.0",
33
+ "pytest-cov>=7.1.0",
34
+ ]
35
+ docs = [
36
+ "autodoc-pydantic>=2.2.0",
37
+ "furo>=2025.12.19",
38
+ "myst-parser>=5.2.0",
39
+ "sphinx>=9.2.0",
40
+ ]
41
+
42
+ [tool.pytest.ini_options]
43
+ testpaths = ["tests"]
44
+ addopts = ["--import-mode=importlib"]
@@ -0,0 +1,10 @@
1
+ """meniscus2brep."""
2
+
3
+ from importlib.metadata import version
4
+
5
+ from loguru import logger
6
+
7
+ __version__ = version("meniscus2brep")
8
+
9
+ # A library stays silent unless its user opts in with logger.enable("meniscus2brep").
10
+ logger.disable("meniscus2brep")
@@ -0,0 +1,79 @@
1
+ """Configuration models and parsing them from JSON."""
2
+
3
+ from os import PathLike
4
+ from pathlib import Path
5
+ from typing import Annotated, Any, Literal, Self
6
+
7
+ from pydantic import BaseModel, BeforeValidator, ConfigDict, Field
8
+
9
+ from meniscus2brep.mesh import Algorithm2D, Algorithm3D
10
+ from meniscus2brep.vol import DEFAULT_SMOOTHING_ITERATIONS, DEFAULT_SMOOTHING_PASS_BAND
11
+
12
+
13
+ class BaseConfig(BaseModel):
14
+ """Base class for configuration models.
15
+
16
+ Unknown fields are rejected so that misspelled options fail at load time
17
+ instead of being silently ignored.
18
+ """
19
+
20
+ model_config = ConfigDict(extra="forbid")
21
+
22
+ @classmethod
23
+ def from_json(cls, path: str | PathLike[str]) -> Self:
24
+ """Parse and validate a configuration from a JSON file."""
25
+ return cls.model_validate_json(Path(path).read_bytes())
26
+
27
+
28
+ def _none_from_text(value: Any) -> Any:
29
+ """Read "none" or "null" as None, so command-line overrides can clear optional values."""
30
+ return None if isinstance(value, str) and value.strip().lower() in ("none", "null") else value
31
+
32
+
33
+ OptionalFloat = Annotated[float | None, BeforeValidator(_none_from_text)]
34
+
35
+
36
+ class BrepConfig(BaseConfig):
37
+ """Settings for building a B-rep from a segmented LabelMap, with the defaults of each step."""
38
+
39
+ label_map: Path = Field(default=Path("label_map.nii"), description="LabelMap to read: .nii, .nrrd, or .mhd")
40
+ output: Path = Field(default=Path("meniscus.brep"), description="B-rep file to write")
41
+ label: int = Field(default=1, description="Value of the meniscus in the LabelMap")
42
+ sigma: OptionalFloat = Field(
43
+ default=None,
44
+ description="Gaussian smoothing of the distance field in physical units. None spans 3 voxel edges per axis, 0 disables",
45
+ )
46
+ level: float = Field(default=0.0, description="Distance of the surface from the label boundary; positive is outside")
47
+ smoothing_iterations: int = Field(
48
+ default=DEFAULT_SMOOTHING_ITERATIONS, ge=0, description="Windowed sinc smoothing iterations on the surface before slicing; 0 disables"
49
+ )
50
+ smoothing_pass_band: float = Field(
51
+ default=DEFAULT_SMOOTHING_PASS_BAND, gt=0, le=2, description="Windowed sinc pass band in (0, 2]; lower smooths and shrinks more"
52
+ )
53
+ spacing: float = Field(default=5.0, description="Arc-length distance between slices along the centerline, in physical units")
54
+ points_per_slice: int = Field(default=32, description="Points on each slice contour. Use about 10 for hexahedral blocks")
55
+ spline_order: int = Field(default=3, description="Polynomial degree of the B-spline geometry")
56
+ cap: Literal["none", "planar", "smooth"] = Field(default="planar", description="How to close the ends; ignored for hexahedral blocks")
57
+ cap_offset: OptionalFloat = Field(
58
+ default=None, description="Apex offset of smooth caps in physical units. None is a quarter of the equivalent radius"
59
+ )
60
+ hex_blocks: bool = Field(default=False, description="Build the five-block butterfly solid with planar caps that hexahedral meshing needs")
61
+
62
+
63
+ class MeshConfig(BaseConfig):
64
+ """Settings for meshing a B-rep, with the defaults of each meshing function."""
65
+
66
+ brep: Path = Field(default=Path("meniscus.brep"), description="B-rep file to read")
67
+ output: Path = Field(default=Path("meniscus.msh"), description="Mesh file to write; gmsh infers the format from the extension")
68
+ element: Literal["tetrahedral", "hexahedral"] = Field(
69
+ default="tetrahedral", description="Element shape. Hexahedral needs a B-rep built with hex_blocks"
70
+ )
71
+ element_order: int = Field(default=1, description="Polynomial order of the elements")
72
+ second_order_incomplete: bool = Field(default=False, description="Omit face and interior nodes from high-order elements")
73
+ min_size: float = Field(default=0.0, description="Smallest tetrahedron size in physical units")
74
+ max_size: OptionalFloat = Field(default=None, description="Largest tetrahedron size in physical units. None lets gmsh choose")
75
+ elements_per_circle: int = Field(default=0, description="Tetrahedra per circle of surface curvature; 0 disables curvature sizing")
76
+ algorithm_2d: Algorithm2D = Field(default=Algorithm2D.FRONTAL_DELAUNAY, description="gmsh surface algorithm for tetrahedral meshing")
77
+ algorithm_3d: Algorithm3D = Field(default=Algorithm3D.DELAUNAY, description="gmsh volume algorithm for tetrahedral meshing")
78
+ elements_per_edge: int = Field(default=4, description="Hexahedra along each edge of a cap")
79
+ elements_along: int = Field(default=20, description="Hexahedra along the solid between the caps")
@@ -0,0 +1,160 @@
1
+ """Reading and writing LabelMaps as .nii, .nrrd, or .mhd + .raw, poly data as .vtp, and B-reps as .brep, and writing meshes."""
2
+
3
+ from os import PathLike
4
+ from pathlib import Path
5
+
6
+ import gmsh
7
+ import numpy as np
8
+ import SimpleITK as sitk
9
+ from loguru import logger
10
+ from vtkmodules.vtkCommonDataModel import vtkPolyData
11
+ from vtkmodules.vtkIOXML import vtkXMLPolyDataReader, vtkXMLPolyDataWriter
12
+
13
+ from meniscus2brep.geo import BRep, gmsh_session
14
+ from meniscus2brep.mesh import Mesh
15
+ from meniscus2brep.vol import LABEL_MAP_PIXEL_IDS
16
+
17
+ SUPPORTED_SUFFIXES = frozenset({".nii", ".nrrd", ".mhd"})
18
+ POLY_DATA_SUFFIXES = frozenset({".vtp"})
19
+ BREP_SUFFIXES = frozenset({".brep"})
20
+
21
+
22
+ def read_label_map(path: str | PathLike[str]) -> sitk.Image:
23
+ """Read a segmented LabelMap from disk.
24
+
25
+ For a .mhd file, the .raw file it references must also exist.
26
+
27
+ Raises:
28
+ ValueError: If the file format is unsupported or the image is not
29
+ sitkUInt8, sitkUInt16, or sitkInt16.
30
+ """
31
+ path = _validated_path(path)
32
+ image = sitk.ReadImage(str(path))
33
+ _require_label_map(image)
34
+ logger.debug("Read {} LabelMap of size {} and spacing {} from {}", image.GetPixelIDTypeAsString(), image.GetSize(), image.GetSpacing(), path)
35
+ return image
36
+
37
+
38
+ def write_label_map(image: sitk.Image, path: str | PathLike[str]) -> None:
39
+ """Write a segmented LabelMap to disk, overwriting any existing file.
40
+
41
+ A .mhd path also writes a .raw file alongside it.
42
+
43
+ Raises:
44
+ ValueError: If the file format is unsupported or the image is not
45
+ sitkUInt8, sitkUInt16, or sitkInt16.
46
+ """
47
+ path = _validated_path(path)
48
+ _require_label_map(image)
49
+ sitk.WriteImage(image, str(path), useCompression=False)
50
+
51
+
52
+ def read_poly_data(path: str | PathLike[str]) -> vtkPolyData:
53
+ """Read poly data from a VTK XML .vtp file.
54
+
55
+ Raises:
56
+ ValueError: If the suffix is not .vtp or the file is not VTK XML poly data.
57
+ FileNotFoundError: If the file does not exist.
58
+ """
59
+ path = _validated_path(path, POLY_DATA_SUFFIXES)
60
+ if not path.is_file():
61
+ raise FileNotFoundError(f"No such file: {path}")
62
+
63
+ # The reader logs failures and returns empty output without any error state.
64
+ reader = vtkXMLPolyDataReader()
65
+ if not reader.CanReadFile(str(path)):
66
+ raise ValueError(f"Not a VTK XML poly data file: {path}")
67
+ reader.SetFileName(str(path))
68
+ reader.Update()
69
+ return reader.GetOutput()
70
+
71
+
72
+ def write_poly_data(poly_data: vtkPolyData, path: str | PathLike[str]) -> None:
73
+ """Write poly data to a VTK XML .vtp file, overwriting any existing file.
74
+
75
+ Raises:
76
+ ValueError: If the suffix is not .vtp.
77
+ OSError: If the file cannot be written.
78
+ """
79
+ path = _validated_path(path, POLY_DATA_SUFFIXES)
80
+
81
+ writer = vtkXMLPolyDataWriter()
82
+ writer.SetFileName(str(path))
83
+ writer.SetInputData(poly_data)
84
+ if not writer.Write():
85
+ raise OSError(f"Could not write poly data to {path}")
86
+
87
+
88
+ def read_brep(path: str | PathLike[str]) -> BRep:
89
+ """Read a B-rep from an Open Cascade .brep file.
90
+
91
+ Raises:
92
+ ValueError: If the suffix is not .brep or the file holds no valid shape.
93
+ FileNotFoundError: If the file does not exist.
94
+ """
95
+ path = _validated_path(path, BREP_SUFFIXES)
96
+ if not path.is_file():
97
+ raise FileNotFoundError(f"No such file: {path}")
98
+
99
+ with gmsh_session():
100
+ try:
101
+ shapes = gmsh.model.occ.importShapes(str(path))
102
+ except Exception as error: # gmsh raises only the bare Exception type.
103
+ raise ValueError(f"Not a valid B-rep file: {path}") from error
104
+ if not shapes:
105
+ raise ValueError(f"Not a valid B-rep file: {path}")
106
+ return BRep(path.read_text(encoding="utf-8"))
107
+
108
+
109
+ def write_brep(brep: BRep, path: str | PathLike[str]) -> None:
110
+ """Write a B-rep to an Open Cascade .brep file, overwriting any existing file.
111
+
112
+ Raises:
113
+ ValueError: If the suffix is not .brep.
114
+ OSError: If the file cannot be written.
115
+ """
116
+ path = _validated_path(path, BREP_SUFFIXES)
117
+ path.write_text(brep.text, encoding="utf-8")
118
+ logger.debug("Wrote B-rep to {}", path)
119
+
120
+
121
+ def write_mesh(mesh: Mesh, path: str | PathLike[str]) -> None:
122
+ """Write a mesh in the format gmsh infers from the extension, overwriting any existing file.
123
+
124
+ Volume formats include .msh, .vtk, .inp, .unv, .bdf, .med, .mesh, and
125
+ .su2. The mesh has only volume elements, so surface formats such as .stl
126
+ hold no elements.
127
+
128
+ Raises:
129
+ ValueError: If gmsh does not recognize the extension.
130
+ OSError: If the file cannot be written.
131
+ """
132
+ path = Path(path)
133
+ with gmsh_session():
134
+ volume = gmsh.model.addDiscreteEntity(3)
135
+ gmsh.model.mesh.addNodes(3, volume, np.arange(1, len(mesh.nodes) + 1).tolist(), mesh.nodes.ravel().tolist())
136
+ first_tag = 1
137
+ for name, connectivity in mesh.elements.items():
138
+ element_tags = np.arange(first_tag, first_tag + len(connectivity))
139
+ gmsh.model.mesh.addElementsByType(volume, mesh.element_types[name], element_tags.tolist(), (connectivity + 1).ravel().tolist())
140
+ first_tag += len(connectivity)
141
+ try:
142
+ gmsh.write(str(path))
143
+ except Exception as error: # gmsh raises only the bare Exception type.
144
+ if "Unknown output file format" in str(error):
145
+ raise ValueError(f"gmsh cannot write meshes in the format of {path.name!r}") from error
146
+ raise OSError(f"Could not write mesh to {path}") from error
147
+ logger.debug("Wrote mesh to {}", path)
148
+
149
+
150
+ def _validated_path(path: str | PathLike[str], suffixes: frozenset[str] = SUPPORTED_SUFFIXES) -> Path:
151
+ path = Path(path)
152
+ if path.suffix.lower() not in suffixes:
153
+ supported = ", ".join(sorted(suffixes))
154
+ raise ValueError(f"Unsupported file format {path.name!r}; expected one of: {supported}")
155
+ return path
156
+
157
+
158
+ def _require_label_map(image: sitk.Image) -> None:
159
+ if image.GetPixelID() not in LABEL_MAP_PIXEL_IDS:
160
+ raise ValueError(f"LabelMap must be sitkUInt8, sitkUInt16, or sitkInt16, got {image.GetPixelIDTypeAsString()}")