aortamesh 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.
- aortamesh-0.1.0/PKG-INFO +33 -0
- aortamesh-0.1.0/README.md +18 -0
- aortamesh-0.1.0/pyproject.toml +35 -0
- aortamesh-0.1.0/pyproject.toml.orig +34 -0
- aortamesh-0.1.0/src/aortamesh/__init__.py +0 -0
- aortamesh-0.1.0/src/aortamesh/__main__.py +3 -0
- aortamesh-0.1.0/src/aortamesh/cheart.py +120 -0
- aortamesh-0.1.0/src/aortamesh/cli.py +85 -0
- aortamesh-0.1.0/src/aortamesh/clip.py +227 -0
- aortamesh-0.1.0/src/aortamesh/config.py +75 -0
- aortamesh-0.1.0/src/aortamesh/cut.py +303 -0
- aortamesh-0.1.0/src/aortamesh/geometry.py +31 -0
- aortamesh-0.1.0/src/aortamesh/io.py +179 -0
- aortamesh-0.1.0/src/aortamesh/mesh.py +330 -0
- aortamesh-0.1.0/src/aortamesh/volume.py +154 -0
aortamesh-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
Metadata-Version: 2.3
|
|
2
|
+
Name: aortamesh
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Package to create patient-specific fluid meshes for healthy aortas using exports from 3D Slicer. Note that anything topologically homeomorphic to a healthy aorta is supported (coarctation, aneurysm, etc.), but not something like TBAD.
|
|
5
|
+
Author: Brandon Hardy
|
|
6
|
+
Author-email: Brandon Hardy <59355744+b-k-hardy@users.noreply.github.com>
|
|
7
|
+
Requires-Dist: gmsh>=4.15.2
|
|
8
|
+
Requires-Dist: h5py>=3.16.0
|
|
9
|
+
Requires-Dist: meshio>=5.3.5
|
|
10
|
+
Requires-Dist: numpy>=2.5.5
|
|
11
|
+
Requires-Dist: pyvista>=0.49.2
|
|
12
|
+
Requires-Dist: scipy>=1.18.1
|
|
13
|
+
Requires-Python: >=3.14
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
|
|
16
|
+
# README
|
|
17
|
+
|
|
18
|
+
This repository is designed to automate (as much as possible) the construction of a non-dissected aorta FEM mesh for fluid and simple FSI simulations.
|
|
19
|
+
You'll see the files `CLAUDE.md` and `docs/design.md`; these are markdown files Claude Code use to track design choices and implementation progress, etc.
|
|
20
|
+
With AI improving at a frankly unbelievable rate, I decided to try my hand at delegating work to Claude more than usual (it did about 90% of the actual implementation) while focusing on higher-level design choices and packaging details.
|
|
21
|
+
These were my goals:
|
|
22
|
+
|
|
23
|
+
- Learn Python packaging and other tooling skills (ruff, uv, etc.)
|
|
24
|
+
- Observe Claude Code's capacity to write proficient code as of November 2026
|
|
25
|
+
- Reflect on how this new design process *feels*. Do I know what's been written? Kinda? Does that matter? I'm not sure...
|
|
26
|
+
|
|
27
|
+
## Using this code
|
|
28
|
+
|
|
29
|
+
Here I will write how to install and run this code. If everything goes according to plan, you can just use `pip`!
|
|
30
|
+
|
|
31
|
+
## Reflections
|
|
32
|
+
|
|
33
|
+
As per my goals, I wanted to make sure to write about how this process felt.
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
# README
|
|
2
|
+
|
|
3
|
+
This repository is designed to automate (as much as possible) the construction of a non-dissected aorta FEM mesh for fluid and simple FSI simulations.
|
|
4
|
+
You'll see the files `CLAUDE.md` and `docs/design.md`; these are markdown files Claude Code use to track design choices and implementation progress, etc.
|
|
5
|
+
With AI improving at a frankly unbelievable rate, I decided to try my hand at delegating work to Claude more than usual (it did about 90% of the actual implementation) while focusing on higher-level design choices and packaging details.
|
|
6
|
+
These were my goals:
|
|
7
|
+
|
|
8
|
+
- Learn Python packaging and other tooling skills (ruff, uv, etc.)
|
|
9
|
+
- Observe Claude Code's capacity to write proficient code as of November 2026
|
|
10
|
+
- Reflect on how this new design process *feels*. Do I know what's been written? Kinda? Does that matter? I'm not sure...
|
|
11
|
+
|
|
12
|
+
## Using this code
|
|
13
|
+
|
|
14
|
+
Here I will write how to install and run this code. If everything goes according to plan, you can just use `pip`!
|
|
15
|
+
|
|
16
|
+
## Reflections
|
|
17
|
+
|
|
18
|
+
As per my goals, I wanted to make sure to write about how this process felt.
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "aortamesh"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Package to create patient-specific fluid meshes for healthy aortas using exports from 3D Slicer. Note that anything topologically homeomorphic to a healthy aorta is supported (coarctation, aneurysm, etc.), but not something like TBAD."
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
requires-python = ">=3.14"
|
|
7
|
+
dependencies = [
|
|
8
|
+
"gmsh>=4.15.2",
|
|
9
|
+
"h5py>=3.16.0",
|
|
10
|
+
"meshio>=5.3.5",
|
|
11
|
+
"numpy>=2.5.5",
|
|
12
|
+
"pyvista>=0.49.2",
|
|
13
|
+
"scipy>=1.18.1",
|
|
14
|
+
]
|
|
15
|
+
|
|
16
|
+
[[project.authors]]
|
|
17
|
+
name = "Brandon Hardy"
|
|
18
|
+
email = "59355744+b-k-hardy@users.noreply.github.com"
|
|
19
|
+
|
|
20
|
+
[project.scripts]
|
|
21
|
+
aortamesh = "aortamesh.cli:main"
|
|
22
|
+
|
|
23
|
+
[build-system]
|
|
24
|
+
requires = ["uv_build>=0.13.9,<0.14.0"]
|
|
25
|
+
build-backend = "uv_build"
|
|
26
|
+
|
|
27
|
+
[dependency-groups]
|
|
28
|
+
dev = [
|
|
29
|
+
"build>=1.6.1",
|
|
30
|
+
"jupyter>=1.1.1",
|
|
31
|
+
"pre-commit>=4.7.0",
|
|
32
|
+
"pytest>=9.2.0",
|
|
33
|
+
"ruff>=0.17.6",
|
|
34
|
+
"twine>=7.0.0",
|
|
35
|
+
]
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "aortamesh"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Package to create patient-specific fluid meshes for healthy aortas using exports from 3D Slicer. Note that anything topologically homeomorphic to a healthy aorta is supported (coarctation, aneurysm, etc.), but not something like TBAD."
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
authors = [
|
|
7
|
+
{ name = "Brandon Hardy", email = "59355744+b-k-hardy@users.noreply.github.com" },
|
|
8
|
+
]
|
|
9
|
+
requires-python = ">=3.14"
|
|
10
|
+
dependencies = [
|
|
11
|
+
"gmsh>=4.15.2",
|
|
12
|
+
"h5py>=3.16.0",
|
|
13
|
+
"meshio>=5.3.5",
|
|
14
|
+
"numpy>=2.5.5",
|
|
15
|
+
"pyvista>=0.49.2",
|
|
16
|
+
"scipy>=1.18.1",
|
|
17
|
+
]
|
|
18
|
+
|
|
19
|
+
[project.scripts]
|
|
20
|
+
aortamesh = "aortamesh.cli:main"
|
|
21
|
+
|
|
22
|
+
[build-system]
|
|
23
|
+
requires = ["uv_build>=0.13.9,<0.14.0"]
|
|
24
|
+
build-backend = "uv_build"
|
|
25
|
+
|
|
26
|
+
[dependency-groups]
|
|
27
|
+
dev = [
|
|
28
|
+
"build>=1.6.1",
|
|
29
|
+
"jupyter>=1.1.1",
|
|
30
|
+
"pre-commit>=4.7.0",
|
|
31
|
+
"pytest>=9.2.0",
|
|
32
|
+
"ruff>=0.17.6",
|
|
33
|
+
"twine>=7.0.0",
|
|
34
|
+
]
|
|
File without changes
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
"""CHeart mesh files: ``.X`` nodes, ``.T`` linear tets, ``.B`` labeled boundary triangles.
|
|
2
|
+
|
|
3
|
+
All three are whitespace-separated text with a one-line header, and every index is 1-based:
|
|
4
|
+
|
|
5
|
+
.X N 3 then N rows: x y z
|
|
6
|
+
.T M N then M rows: n1 n2 n3 n4 (rows of .X)
|
|
7
|
+
.B K then K rows: tet n1 n2 n3 label (tet = row of .T, n = rows of .X)
|
|
8
|
+
.D N 3 then N rows: nx ny nz (optional normals.D, row i = node i)
|
|
9
|
+
|
|
10
|
+
Each ``.B`` triangle is a face of the tet in its first column. Nodes are written in
|
|
11
|
+
``VolumeMesh`` order and tets in ``VolumeMesh`` order, so the indices in all three files agree
|
|
12
|
+
by construction. This is the only place indices become 1-based.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
from dataclasses import dataclass
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
|
|
20
|
+
import numpy as np
|
|
21
|
+
|
|
22
|
+
from aortamesh.volume import VolumeMesh
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass(frozen=True)
|
|
26
|
+
class CheartOptions:
|
|
27
|
+
name: str = "mesh" # files are <output>/<name>.X, .T, .B
|
|
28
|
+
# Multiplies coordinates on output: 1.0 keeps mm, 1e-3 gives m. The density and viscosity
|
|
29
|
+
# entered in CHeart must match (design.md §9).
|
|
30
|
+
scale: float = 1.0
|
|
31
|
+
# Also write <output>/normals.D: each node's outward unit surface normal, zero at interior
|
|
32
|
+
# nodes, one row per .X row. Not scaled.
|
|
33
|
+
normals: bool = False
|
|
34
|
+
|
|
35
|
+
def __post_init__(self) -> None:
|
|
36
|
+
if not self.name or "/" in self.name:
|
|
37
|
+
raise ValueError(f"invalid CHeart file name: {self.name!r}")
|
|
38
|
+
if self.scale <= 0:
|
|
39
|
+
raise ValueError(f"scale must be positive, got {self.scale}")
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def write_cheart(
|
|
43
|
+
vm: VolumeMesh,
|
|
44
|
+
directory: str | Path,
|
|
45
|
+
options: CheartOptions | None = None,
|
|
46
|
+
) -> list[Path]:
|
|
47
|
+
"""Write ``<directory>/<name>.X/.T/.B`` (and ``normals.D`` if asked). Validates the mesh
|
|
48
|
+
first. Returns the paths written."""
|
|
49
|
+
options = options or CheartOptions()
|
|
50
|
+
vm.validate()
|
|
51
|
+
stem = Path(directory) / options.name
|
|
52
|
+
x_path, t_path, b_path = (Path(f"{stem}{s}") for s in (".X", ".T", ".B"))
|
|
53
|
+
|
|
54
|
+
n, m, k = len(vm.points), len(vm.tets), len(vm.bnd_tris)
|
|
55
|
+
# %.17g round-trips float64 exactly.
|
|
56
|
+
np.savetxt(x_path, vm.points * options.scale, fmt="%.17g", header=f"{n} 3", comments="")
|
|
57
|
+
np.savetxt(t_path, vm.tets + 1, fmt="%d", header=f"{m} {n}", comments="")
|
|
58
|
+
rows = np.c_[vm.bnd_tet + 1, vm.bnd_tris + 1, vm.bnd_labels]
|
|
59
|
+
np.savetxt(b_path, rows, fmt="%d", header=f"{k}", comments="")
|
|
60
|
+
paths = [x_path, t_path, b_path]
|
|
61
|
+
|
|
62
|
+
if options.normals:
|
|
63
|
+
d_path = Path(directory) / "normals.D"
|
|
64
|
+
np.savetxt(d_path, vm.node_normals(), fmt="%.17g", header=f"{n} 3", comments="")
|
|
65
|
+
paths.append(d_path)
|
|
66
|
+
return paths
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def read_cheart(
|
|
70
|
+
directory: str | Path,
|
|
71
|
+
name: str = "mesh",
|
|
72
|
+
scale: float = 1.0,
|
|
73
|
+
) -> VolumeMesh:
|
|
74
|
+
"""Read ``<directory>/<name>.X/.T/.B`` back into a VolumeMesh (0-based; coords / scale).
|
|
75
|
+
|
|
76
|
+
Checks each header against its file. Label names aren't stored in CHeart files, so they
|
|
77
|
+
come back as ``"label<k>"``.
|
|
78
|
+
"""
|
|
79
|
+
stem = Path(directory) / name
|
|
80
|
+
x_head, x = _read(Path(f"{stem}.X"), float)
|
|
81
|
+
t_head, t = _read(Path(f"{stem}.T"), np.int64)
|
|
82
|
+
b_head, b = _read(Path(f"{stem}.B"), np.int64)
|
|
83
|
+
x, t, b = x.reshape(-1, 3), t.reshape(-1, 4), b.reshape(-1, 5)
|
|
84
|
+
|
|
85
|
+
problems = []
|
|
86
|
+
if x_head != [len(x), 3]:
|
|
87
|
+
problems.append(f".X header {x_head}, expected [{len(x)}, 3]")
|
|
88
|
+
if t_head != [len(t), len(x)]:
|
|
89
|
+
problems.append(f".T header {t_head}, expected [{len(t)}, {len(x)}]")
|
|
90
|
+
if b_head != [len(b)]:
|
|
91
|
+
problems.append(f".B header {b_head}, expected [{len(b)}]")
|
|
92
|
+
if t.min() < 1 or t.max() > len(x):
|
|
93
|
+
problems.append(f".T node indices span {t.min()}..{t.max()}, expected 1..{len(x)}")
|
|
94
|
+
if b[:, 0].min() < 1 or b[:, 0].max() > len(t):
|
|
95
|
+
problems.append(
|
|
96
|
+
f".B tet indices span {b[:, 0].min()}..{b[:, 0].max()}, expected 1..{len(t)}"
|
|
97
|
+
)
|
|
98
|
+
if b[:, 1:4].min() < 1 or b[:, 1:4].max() > len(x):
|
|
99
|
+
problems.append(
|
|
100
|
+
f".B node indices span {b[:, 1:4].min()}..{b[:, 1:4].max()}, expected 1..{len(x)}"
|
|
101
|
+
)
|
|
102
|
+
if problems:
|
|
103
|
+
raise ValueError(f"{stem}: " + "; ".join(problems))
|
|
104
|
+
|
|
105
|
+
labels = b[:, 4].astype(np.int32)
|
|
106
|
+
return VolumeMesh(
|
|
107
|
+
points=x / scale,
|
|
108
|
+
tets=t - 1,
|
|
109
|
+
bnd_tris=b[:, 1:4] - 1,
|
|
110
|
+
bnd_labels=labels,
|
|
111
|
+
bnd_tet=b[:, 0] - 1,
|
|
112
|
+
label_names={int(lab): f"label{lab}" for lab in np.unique(labels)},
|
|
113
|
+
)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _read(path: Path, dtype: type) -> tuple[list[int], np.ndarray]:
|
|
117
|
+
with path.open() as f:
|
|
118
|
+
header = [int(v) for v in f.readline().split()]
|
|
119
|
+
data = np.loadtxt(f, dtype=dtype, ndmin=2)
|
|
120
|
+
return header, data
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
"""Cut and mesh one case, writing intermediate and final results for ParaView.
|
|
2
|
+
|
|
3
|
+
uv run aortamesh -c sample_config.toml
|
|
4
|
+
uv run aortamesh -cd examples/with_arch_branches # all defaults
|
|
5
|
+
|
|
6
|
+
Writes <case>/preview/: the surface, one clip_<name>.vtp and outline_<name>.vtp per plane, and
|
|
7
|
+
the cut wall.vtp. Writes the output folder (default <case>/mesh/): mesh.vtu (tets) and
|
|
8
|
+
boundary.vtp (boundary triangles with cell_data["label"]), plus the CHeart mesh <name>.X/.T/.B
|
|
9
|
+
(see [cheart] in the config).
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
import argparse
|
|
13
|
+
import dataclasses
|
|
14
|
+
import time
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
from aortamesh.cheart import write_cheart
|
|
18
|
+
from aortamesh.clip import (
|
|
19
|
+
RayCaster,
|
|
20
|
+
clipping_surface,
|
|
21
|
+
fit_cross_section,
|
|
22
|
+
section_outline,
|
|
23
|
+
)
|
|
24
|
+
from aortamesh.config import Config, load_config
|
|
25
|
+
from aortamesh.cut import cut_surface
|
|
26
|
+
from aortamesh.io import load_case
|
|
27
|
+
from aortamesh.mesh import mesh_volume
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def main(argv: list[str] | None = None) -> None:
|
|
31
|
+
p = argparse.ArgumentParser(description="Create a non-dissected thoracic aorta fluid mesh")
|
|
32
|
+
p.add_argument("-c", "--config", type=Path, help="TOML config file (see sample_config.toml)")
|
|
33
|
+
p.add_argument(
|
|
34
|
+
"-cd", "--case_dir", type=Path, help="Directory with 3D Slicer exports (overrides config)"
|
|
35
|
+
)
|
|
36
|
+
p.add_argument("-o", "--output", type=Path, help="Output directory (overrides config)")
|
|
37
|
+
|
|
38
|
+
args = p.parse_args(argv)
|
|
39
|
+
|
|
40
|
+
config = load_config(args.config) if args.config else Config()
|
|
41
|
+
if args.case_dir:
|
|
42
|
+
config = dataclasses.replace(config, directory=args.case_dir)
|
|
43
|
+
if args.output:
|
|
44
|
+
config = dataclasses.replace(config, output=args.output)
|
|
45
|
+
if config.directory is None:
|
|
46
|
+
p.error("give a case directory with -cd or in the config file")
|
|
47
|
+
|
|
48
|
+
case_dir = config.directory
|
|
49
|
+
print(case_dir)
|
|
50
|
+
case = load_case(case_dir)
|
|
51
|
+
caster = RayCaster(case.surface)
|
|
52
|
+
|
|
53
|
+
out = case_dir / "preview"
|
|
54
|
+
out.mkdir(exist_ok=True)
|
|
55
|
+
case.surface.save(out / "surface.vtp")
|
|
56
|
+
|
|
57
|
+
sections = []
|
|
58
|
+
for cut in case.cuts:
|
|
59
|
+
section = fit_cross_section(caster, cut)
|
|
60
|
+
print(section.summary())
|
|
61
|
+
clipping_surface(section).save(out / f"clip_{cut.name}.vtp")
|
|
62
|
+
section_outline(section).save(out / f"outline_{cut.name}.vtp")
|
|
63
|
+
sections.append(section)
|
|
64
|
+
|
|
65
|
+
wall, openings = cut_surface(case.surface, sections)
|
|
66
|
+
for o in openings:
|
|
67
|
+
print(o.summary())
|
|
68
|
+
wall.save(out / "wall.vtp")
|
|
69
|
+
|
|
70
|
+
print(f"wrote {out}")
|
|
71
|
+
|
|
72
|
+
t0 = time.perf_counter()
|
|
73
|
+
vm = mesh_volume(wall, openings, config.mesh, case.centerline)
|
|
74
|
+
print(f"meshed in {time.perf_counter() - t0:.1f} s: {vm.summary()}")
|
|
75
|
+
|
|
76
|
+
mesh_out = config.output_dir
|
|
77
|
+
mesh_out.mkdir(parents=True, exist_ok=True)
|
|
78
|
+
vm.to_pyvista().save(mesh_out / "mesh.vtu")
|
|
79
|
+
vm.boundary_pyvista().save(mesh_out / "boundary.vtp")
|
|
80
|
+
write_cheart(vm, mesh_out, config.cheart)
|
|
81
|
+
print(f"wrote {mesh_out} (CHeart: {config.cheart.name}.X/.T/.B, scale {config.cheart.scale})")
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
if __name__ == "__main__":
|
|
85
|
+
main()
|
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
"""Ray-cast cross-sections at each cut plane and build local clipping surfaces from them.
|
|
2
|
+
|
|
3
|
+
For each plane we cast rays outward from the plane center, *within* the plane (perpendicular
|
|
4
|
+
to the normal), and keep the first wall hit on each. Those hits trace the lumen boundary in
|
|
5
|
+
that plane, wherever the user happened to click. Then:
|
|
6
|
+
|
|
7
|
+
1. Re-center: the area centroid of the hit polygon becomes the new center, and the rays are
|
|
8
|
+
recast from there, repeated until the center stops moving. The center Slicer gives us is
|
|
9
|
+
only "somewhere inside the lumen".
|
|
10
|
+
2. Clipping surface: a star-shaped polygon through the hits, pushed outward by a margin. It
|
|
11
|
+
spans the lumen and slightly beyond it, but (unlike an infinite plane) not the rest of the
|
|
12
|
+
aorta, so a cut at one vessel can't slice through a neighbouring one.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import warnings
|
|
18
|
+
from dataclasses import dataclass
|
|
19
|
+
|
|
20
|
+
import numpy as np
|
|
21
|
+
import pyvista as pv
|
|
22
|
+
|
|
23
|
+
from aortamesh.geometry import plane_basis, polygon_centroid_2d
|
|
24
|
+
from aortamesh.io import Cut
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
# =============================================================================
|
|
28
|
+
# Ray casting
|
|
29
|
+
# =============================================================================
|
|
30
|
+
class RayCaster:
|
|
31
|
+
"""Ray queries against a fixed surface.
|
|
32
|
+
|
|
33
|
+
Uses ``PolyData.intersect_with_line``, which caches a cell locator on the mesh, so
|
|
34
|
+
only the first query pays to build it. Deliberately not
|
|
35
|
+
``ray_trace(first_point=True)``: its de-duplication sorts hits by coordinate rather
|
|
36
|
+
than by distance, so the "first" point it returns can be the farthest one. Here hits
|
|
37
|
+
are sorted by distance along the ray.
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
def __init__(self, surface: pv.PolyData, merge_tol: float = 1e-6) -> None:
|
|
41
|
+
self.surface = surface
|
|
42
|
+
# Bounding-box diagonal: no ray needs to be longer.
|
|
43
|
+
self.max_length = float(surface.length)
|
|
44
|
+
# A ray through a shared edge or vertex reports the same hit once per cell;
|
|
45
|
+
# hits closer than this (relative to the surface size) count as one.
|
|
46
|
+
self._merge = merge_tol * self.max_length
|
|
47
|
+
|
|
48
|
+
def distances(self, origin: np.ndarray, direction: np.ndarray) -> np.ndarray:
|
|
49
|
+
"""Sorted, de-duplicated distances to every surface crossing along one ray."""
|
|
50
|
+
end = origin + self.max_length * direction
|
|
51
|
+
pts, _ = self.surface.intersect_with_line(origin, end, deduplicate_points=False)
|
|
52
|
+
if pts.size == 0:
|
|
53
|
+
return np.empty(0)
|
|
54
|
+
t = np.sort((np.asarray(pts, dtype=np.float64) - origin) @ direction)
|
|
55
|
+
t = t[t > self._merge]
|
|
56
|
+
if t.size > 1:
|
|
57
|
+
t = t[np.r_[True, np.diff(t) > self._merge]]
|
|
58
|
+
return t
|
|
59
|
+
|
|
60
|
+
def hits(self, origin: np.ndarray, directions: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
|
|
61
|
+
"""Distances to the first and second surface hits along each unit direction.
|
|
62
|
+
|
|
63
|
+
From inside the lumen, the first hit is the wall of this vessel and the second
|
|
64
|
+
(if any) is where the ray enters a neighbouring one. NaN where there is no hit.
|
|
65
|
+
"""
|
|
66
|
+
first = np.full(len(directions), np.nan)
|
|
67
|
+
second = np.full(len(directions), np.nan)
|
|
68
|
+
for i, d in enumerate(directions):
|
|
69
|
+
t = self.distances(origin, d)
|
|
70
|
+
if t.size:
|
|
71
|
+
first[i] = t[0]
|
|
72
|
+
if t.size > 1:
|
|
73
|
+
second[i] = t[1]
|
|
74
|
+
return first, second
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
# =============================================================================
|
|
78
|
+
# Cross-sections
|
|
79
|
+
# =============================================================================
|
|
80
|
+
@dataclass(frozen=True)
|
|
81
|
+
class CrossSection:
|
|
82
|
+
"""The lumen boundary in one cut plane, as seen from a re-centered origin."""
|
|
83
|
+
|
|
84
|
+
cut: Cut
|
|
85
|
+
center: np.ndarray # (3,) area centroid of the hit polygon (refined)
|
|
86
|
+
normal: np.ndarray # (3,) unit normal (same line as cut.normal; sign not yet fixed)
|
|
87
|
+
directions: np.ndarray # (n, 3) in-plane unit ray directions
|
|
88
|
+
radii: np.ndarray # (n,) distance from center to the wall along each ray
|
|
89
|
+
clearance: np.ndarray # (n,) distance to the next surface beyond the wall (inf if none)
|
|
90
|
+
area: float # area of the hit polygon, mm^2
|
|
91
|
+
shift: float # how far the center moved from the user's click, mm
|
|
92
|
+
iterations: int
|
|
93
|
+
|
|
94
|
+
@property
|
|
95
|
+
def hits(self) -> np.ndarray:
|
|
96
|
+
"""(n, 3) wall points, in ray order around the normal."""
|
|
97
|
+
return self.center + self.radii[:, None] * self.directions
|
|
98
|
+
|
|
99
|
+
@property
|
|
100
|
+
def equivalent_radius(self) -> float:
|
|
101
|
+
"""Radius of the circle with the same area."""
|
|
102
|
+
return float(np.sqrt(self.area / np.pi))
|
|
103
|
+
|
|
104
|
+
def summary(self) -> str:
|
|
105
|
+
r = self.radii
|
|
106
|
+
gap = self.clearance.min()
|
|
107
|
+
gap_s = "none in plane" if np.isinf(gap) else f"{gap:.2f} mm"
|
|
108
|
+
return (
|
|
109
|
+
f"{self.cut.name:>8}: r_eq {self.equivalent_radius:5.2f} mm "
|
|
110
|
+
f"r [{r.min():5.2f}, {r.max():5.2f}] area {self.area:7.1f} mm^2 "
|
|
111
|
+
f"center moved {self.shift:5.2f} mm in {self.iterations} it "
|
|
112
|
+
f"nearest other vessel: {gap_s}"
|
|
113
|
+
)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def fit_cross_section(
|
|
117
|
+
caster: RayCaster,
|
|
118
|
+
cut: Cut,
|
|
119
|
+
n_rays: int = 72,
|
|
120
|
+
max_iter: int = 20,
|
|
121
|
+
tol: float = 1e-3,
|
|
122
|
+
outlier_factor: float = 2.0,
|
|
123
|
+
) -> CrossSection:
|
|
124
|
+
"""Cast ``n_rays`` in-plane rays from the cut center and iteratively re-center them.
|
|
125
|
+
|
|
126
|
+
``tol`` is relative to the equivalent radius. Raises if any ray misses the wall (the
|
|
127
|
+
center is outside the lumen or the plane leaves the vessel). Warns if a ray is more than
|
|
128
|
+
``outlier_factor`` times the median radius, which usually means it escaped through a branch
|
|
129
|
+
ostium or the plane is badly oblique: move the plane rather than trusting the section.
|
|
130
|
+
"""
|
|
131
|
+
n = cut.normal / np.linalg.norm(cut.normal)
|
|
132
|
+
u, v = plane_basis(n)
|
|
133
|
+
theta = np.linspace(0.0, 2 * np.pi, n_rays, endpoint=False)
|
|
134
|
+
dirs = np.cos(theta)[:, None] * u + np.sin(theta)[:, None] * v
|
|
135
|
+
|
|
136
|
+
center = cut.center.copy()
|
|
137
|
+
for it in range(1, max_iter + 1):
|
|
138
|
+
radii, _ = caster.hits(center, dirs)
|
|
139
|
+
if np.isnan(radii).any():
|
|
140
|
+
raise RuntimeError(
|
|
141
|
+
f"{cut.name}: {np.isnan(radii).sum()}/{n_rays} rays missed the wall; "
|
|
142
|
+
"is the plane center inside the lumen?",
|
|
143
|
+
)
|
|
144
|
+
xy = radii[:, None] * np.c_[np.cos(theta), np.sin(theta)] # hits in (u, v) coords
|
|
145
|
+
c2, area = polygon_centroid_2d(xy)
|
|
146
|
+
step = float(np.linalg.norm(c2))
|
|
147
|
+
center = center + c2[0] * u + c2[1] * v
|
|
148
|
+
if step < tol * np.sqrt(area / np.pi):
|
|
149
|
+
break
|
|
150
|
+
else:
|
|
151
|
+
warnings.warn(
|
|
152
|
+
f"{cut.name}: re-centering did not converge in {max_iter} iterations",
|
|
153
|
+
)
|
|
154
|
+
|
|
155
|
+
# Final rays from the converged center, so radii and center agree exactly.
|
|
156
|
+
radii, beyond = caster.hits(center, dirs)
|
|
157
|
+
clearance = np.where(np.isnan(beyond), np.inf, beyond - radii)
|
|
158
|
+
xy = radii[:, None] * np.c_[np.cos(theta), np.sin(theta)]
|
|
159
|
+
_, area = polygon_centroid_2d(xy)
|
|
160
|
+
|
|
161
|
+
med = np.median(radii)
|
|
162
|
+
if (radii > outlier_factor * med).any():
|
|
163
|
+
k = int((radii > outlier_factor * med).sum())
|
|
164
|
+
warnings.warn(
|
|
165
|
+
f"{cut.name}: {k} ray(s) exceed {outlier_factor}x the median radius "
|
|
166
|
+
f"({radii.max():.1f} vs {med:.1f} mm); the plane may cut into a branch ostium",
|
|
167
|
+
)
|
|
168
|
+
|
|
169
|
+
return CrossSection(
|
|
170
|
+
cut=cut,
|
|
171
|
+
center=center,
|
|
172
|
+
normal=n,
|
|
173
|
+
directions=dirs,
|
|
174
|
+
radii=radii,
|
|
175
|
+
clearance=clearance,
|
|
176
|
+
area=float(area),
|
|
177
|
+
shift=float(np.linalg.norm(center - cut.center)),
|
|
178
|
+
iterations=it,
|
|
179
|
+
)
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
# =============================================================================
|
|
183
|
+
# Clipping surfaces
|
|
184
|
+
# =============================================================================
|
|
185
|
+
def clip_polygon(
|
|
186
|
+
section: CrossSection,
|
|
187
|
+
margin: float = 0.25,
|
|
188
|
+
pad: float = 1.0,
|
|
189
|
+
) -> np.ndarray:
|
|
190
|
+
"""(n, 3) vertices of the star-shaped clipping polygon, one per ray, in ray order.
|
|
191
|
+
|
|
192
|
+
Each vertex sits at ``r * (1 + margin) + pad`` along its ray (a relative margin plus an
|
|
193
|
+
absolute one in mm), but never more than halfway across the gap to the next surface the
|
|
194
|
+
ray meets. So it always reaches past this vessel's wall and never into a neighbour's.
|
|
195
|
+
"""
|
|
196
|
+
r = section.radii * (1.0 + margin) + pad
|
|
197
|
+
r = np.minimum(r, section.radii + 0.5 * section.clearance)
|
|
198
|
+
return section.center + r[:, None] * section.directions
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def clipping_surface(
|
|
202
|
+
section: CrossSection,
|
|
203
|
+
margin: float = 0.25,
|
|
204
|
+
pad: float = 1.0,
|
|
205
|
+
) -> pv.PolyData:
|
|
206
|
+
"""The clipping polygon as a surface, for ParaView.
|
|
207
|
+
|
|
208
|
+
Triangulated as a fan from the center, which is valid because the polygon is star-shaped
|
|
209
|
+
about it by construction.
|
|
210
|
+
"""
|
|
211
|
+
rim = clip_polygon(section, margin, pad)
|
|
212
|
+
pts = np.vstack([section.center, rim])
|
|
213
|
+
n = len(rim)
|
|
214
|
+
i = np.arange(n)
|
|
215
|
+
faces = np.c_[np.full(n, 3), np.zeros(n, int), 1 + i, 1 + (i + 1) % n].ravel()
|
|
216
|
+
disc = pv.PolyData(pts, faces)
|
|
217
|
+
disc.field_data["name"] = [section.cut.name]
|
|
218
|
+
return disc
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def section_outline(section: CrossSection) -> pv.PolyData:
|
|
222
|
+
"""Closed polyline through the wall hits, for checking a section in ParaView."""
|
|
223
|
+
hits = section.hits
|
|
224
|
+
n = len(hits)
|
|
225
|
+
line = pv.PolyData(hits, lines=np.r_[n + 1, np.arange(n), 0])
|
|
226
|
+
line.field_data["name"] = [section.cut.name]
|
|
227
|
+
return line
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"""Run configuration from a TOML file. Missing keys take the defaults in the option classes."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import dataclasses
|
|
6
|
+
import tomllib
|
|
7
|
+
from dataclasses import dataclass, field
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
from aortamesh.cheart import CheartOptions
|
|
12
|
+
from aortamesh.mesh import BoundaryLayer, MeshOptions
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass(frozen=True)
|
|
16
|
+
class Config:
|
|
17
|
+
directory: Path | None = None # case folder: surface.vtp and *.mrk.json
|
|
18
|
+
output: Path | None = None # where mesh files go; default <directory>/mesh
|
|
19
|
+
mesh: MeshOptions = field(default_factory=MeshOptions)
|
|
20
|
+
cheart: CheartOptions = field(default_factory=CheartOptions)
|
|
21
|
+
|
|
22
|
+
@property
|
|
23
|
+
def output_dir(self) -> Path:
|
|
24
|
+
if self.output is not None:
|
|
25
|
+
return self.output
|
|
26
|
+
if self.directory is None:
|
|
27
|
+
raise ValueError("no case directory given")
|
|
28
|
+
return self.directory / "mesh"
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def load_config(path: str | Path) -> Config:
|
|
32
|
+
"""Read a config file. Relative paths in it are relative to the file, not the shell."""
|
|
33
|
+
path = Path(path)
|
|
34
|
+
with path.open("rb") as f:
|
|
35
|
+
doc = tomllib.load(f)
|
|
36
|
+
base = path.parent
|
|
37
|
+
|
|
38
|
+
mesh_tbl = dict(doc.pop("mesh", {}))
|
|
39
|
+
bl_tbl = dict(doc.pop("boundary_layer", {}))
|
|
40
|
+
cheart_tbl = dict(doc.pop("cheart", {}))
|
|
41
|
+
top = _take(doc, Config, "top level", exclude={"mesh", "cheart"})
|
|
42
|
+
|
|
43
|
+
bl = None
|
|
44
|
+
if bl_tbl.pop("enabled", True):
|
|
45
|
+
bl = BoundaryLayer(**_take(bl_tbl, BoundaryLayer, "[boundary_layer]"))
|
|
46
|
+
mesh = MeshOptions(
|
|
47
|
+
**_take(mesh_tbl, MeshOptions, "[mesh]", exclude={"boundary_layer"}),
|
|
48
|
+
boundary_layer=bl,
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
def resolve(p: str | None) -> Path | None:
|
|
52
|
+
return base / p if p else None # "" means unset
|
|
53
|
+
|
|
54
|
+
return Config(
|
|
55
|
+
directory=resolve(top.get("directory")),
|
|
56
|
+
output=resolve(top.get("output")),
|
|
57
|
+
mesh=mesh,
|
|
58
|
+
cheart=CheartOptions(**_take(cheart_tbl, CheartOptions, "[cheart]")),
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _take(
|
|
63
|
+
table: dict[str, Any],
|
|
64
|
+
cls: type,
|
|
65
|
+
where: str,
|
|
66
|
+
exclude: frozenset[str] | set[str] = frozenset(),
|
|
67
|
+
) -> dict[str, Any]:
|
|
68
|
+
"""The entries of ``table`` that are fields of ``cls``; anything else is an error."""
|
|
69
|
+
allowed = {f.name for f in dataclasses.fields(cls)} - set(exclude)
|
|
70
|
+
unknown = set(table) - allowed
|
|
71
|
+
if unknown:
|
|
72
|
+
raise ValueError(
|
|
73
|
+
f"unknown key(s) {sorted(unknown)} in {where}; expected some of {sorted(allowed)}",
|
|
74
|
+
)
|
|
75
|
+
return dict(table)
|