meniscus2brep 0.1.0__py3-none-any.whl
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.
- meniscus2brep/__init__.py +10 -0
- meniscus2brep/config.py +79 -0
- meniscus2brep/disk.py +160 -0
- meniscus2brep/geo.py +463 -0
- meniscus2brep/mesh.py +243 -0
- meniscus2brep/pipeline.py +175 -0
- meniscus2brep/py.typed +0 -0
- meniscus2brep/vol.py +552 -0
- meniscus2brep-0.1.0.dist-info/METADATA +79 -0
- meniscus2brep-0.1.0.dist-info/RECORD +13 -0
- meniscus2brep-0.1.0.dist-info/WHEEL +4 -0
- meniscus2brep-0.1.0.dist-info/entry_points.txt +4 -0
- meniscus2brep-0.1.0.dist-info/licenses/LICENSE +202 -0
|
@@ -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")
|
meniscus2brep/config.py
ADDED
|
@@ -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")
|
meniscus2brep/disk.py
ADDED
|
@@ -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()}")
|