pyRadPlan 0.0.1__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.
- examples/carbon_pencilbeam.py +87 -0
- examples/helium_pencilbeam.py +80 -0
- examples/import_matrad_patient.py +102 -0
- examples/photon_pencilbeam.py +66 -0
- examples/proton_pencilbeam.py +80 -0
- pyRadPlan/GUI.py +5 -0
- pyRadPlan/__init__.py +34 -0
- pyRadPlan/core/__init__.py +15 -0
- pyRadPlan/core/_exceptions.py +9 -0
- pyRadPlan/core/_grids.py +231 -0
- pyRadPlan/core/datamodel.py +68 -0
- pyRadPlan/core/np2sitk.py +147 -0
- pyRadPlan/core/resample.py +130 -0
- pyRadPlan/cst/__init__.py +15 -0
- pyRadPlan/cst/_cst.py +307 -0
- pyRadPlan/cst/_voi.py +603 -0
- pyRadPlan/ct/__init__.py +4 -0
- pyRadPlan/ct/_ct.py +525 -0
- pyRadPlan/ct/_hlut.py +27 -0
- pyRadPlan/data/machines/carbon_Generic.mat +0 -0
- pyRadPlan/data/machines/helium_Generic.mat +0 -0
- pyRadPlan/data/machines/photons_Generic.mat +0 -0
- pyRadPlan/data/machines/protons_Generic.mat +0 -0
- pyRadPlan/data/phantoms/TG119.mat +0 -0
- pyRadPlan/data/stf/matRad_stf.mat +0 -0
- pyRadPlan/data/stf/matrad_stf_onebeam.mat +0 -0
- pyRadPlan/dij/__init__.py +4 -0
- pyRadPlan/dij/_dij.py +410 -0
- pyRadPlan/dose/__init__.py +6 -0
- pyRadPlan/dose/_calc_dose.py +64 -0
- pyRadPlan/dose/engines/__init__.py +17 -0
- pyRadPlan/dose/engines/_base.py +591 -0
- pyRadPlan/dose/engines/_base_pencilbeam.py +806 -0
- pyRadPlan/dose/engines/_base_pencilbeam_particle.py +1015 -0
- pyRadPlan/dose/engines/_factory.py +108 -0
- pyRadPlan/dose/engines/_hongpb.py +75 -0
- pyRadPlan/dose/engines/_svdpb.py +275 -0
- pyRadPlan/geometry/__init__.py +7 -0
- pyRadPlan/geometry/lps.py +122 -0
- pyRadPlan/io/.gitkeep +0 -0
- pyRadPlan/io/__init__.py +3 -0
- pyRadPlan/io/matLabFileHandler.py +25 -0
- pyRadPlan/io/matRad.py +22 -0
- pyRadPlan/io/readHLUT.py +17 -0
- pyRadPlan/io/temp_files/cst.mat +0 -0
- pyRadPlan/io/temp_files/ct.mat +0 -0
- pyRadPlan/io/temp_files/pln.mat +0 -0
- pyRadPlan/io/temp_files/stf_with_separate_rays.mat +0 -0
- pyRadPlan/machines/__init__.py +19 -0
- pyRadPlan/machines/_base.py +164 -0
- pyRadPlan/machines/_ions.py +528 -0
- pyRadPlan/machines/_load.py +48 -0
- pyRadPlan/machines/_photons.py +220 -0
- pyRadPlan/machines/_validate.py +61 -0
- pyRadPlan/matRad/.gitkeep +0 -0
- pyRadPlan/matRad/__init__.py +18 -0
- pyRadPlan/matRad/_engine.py +36 -0
- pyRadPlan/matRad/_matlab.py +26 -0
- pyRadPlan/matRad/_octave.py +51 -0
- pyRadPlan/optimization/__init__.py +12 -0
- pyRadPlan/optimization/_fluenceOptimizer.py +312 -0
- pyRadPlan/optimization/_fluence_optimization.py +57 -0
- pyRadPlan/optimization/components/__init__.py +3 -0
- pyRadPlan/optimization/components/_optimizationProblem.py +162 -0
- pyRadPlan/optimization/components/objectives/_EUD.py +93 -0
- pyRadPlan/optimization/components/objectives/__init__.py +19 -0
- pyRadPlan/optimization/components/objectives/_doseUniformity.py +81 -0
- pyRadPlan/optimization/components/objectives/_maxDVH.py +92 -0
- pyRadPlan/optimization/components/objectives/_meanDose.py +80 -0
- pyRadPlan/optimization/components/objectives/_minDVH.py +92 -0
- pyRadPlan/optimization/components/objectives/_objectiveClass.py +98 -0
- pyRadPlan/optimization/components/objectives/_squaredDeviation.py +82 -0
- pyRadPlan/optimization/components/objectives/_squaredOverdosing.py +84 -0
- pyRadPlan/optimization/components/objectives/_squaredUnderdosing.py +84 -0
- pyRadPlan/optimization/projections/__init__.py +5 -0
- pyRadPlan/optimization/projections/_backProjection.py +59 -0
- pyRadPlan/optimization/projections/_constantRBEProjection.py +26 -0
- pyRadPlan/optimization/projections/_doseProjection.py +25 -0
- pyRadPlan/optimization/solvers/__init__.py +18 -0
- pyRadPlan/optimization/solvers/_ipopt.py +89 -0
- pyRadPlan/optimization/solvers/_scipy_solver.py +120 -0
- pyRadPlan/plan/__init__.py +3 -0
- pyRadPlan/plan/_plans.py +360 -0
- pyRadPlan/raytracer/__init__.py +4 -0
- pyRadPlan/raytracer/_base.py +289 -0
- pyRadPlan/raytracer/_perf.py +227 -0
- pyRadPlan/raytracer/_siddon.py +428 -0
- pyRadPlan/scenarios/__init__.py +102 -0
- pyRadPlan/scenarios/_base.py +374 -0
- pyRadPlan/scenarios/_nominal.py +126 -0
- pyRadPlan/stf/__init__.py +29 -0
- pyRadPlan/stf/_base.py +226 -0
- pyRadPlan/stf/_beam.py +195 -0
- pyRadPlan/stf/_beamlet.py +106 -0
- pyRadPlan/stf/_exceptions.py +14 -0
- pyRadPlan/stf/_externalbeam.py +162 -0
- pyRadPlan/stf/_generate_stf.py +23 -0
- pyRadPlan/stf/_ions.py +255 -0
- pyRadPlan/stf/_photons.py +125 -0
- pyRadPlan/stf/_rangeshifter.py +40 -0
- pyRadPlan/stf/_ray.py +201 -0
- pyRadPlan/stf/_steeringinformation.py +181 -0
- pyRadPlan/stf/base_matrad.py +6 -0
- pyRadPlan/stf/hlutLibrary/matRad_default.hlut +10 -0
- pyRadPlan/stf/loadHLUT.py +63 -0
- pyRadPlan/util/__init__.py +0 -0
- pyRadPlan/util/helpers.py +209 -0
- pyRadPlan-0.0.1.dist-info/LICENSE +28 -0
- pyRadPlan-0.0.1.dist-info/METADATA +70 -0
- pyRadPlan-0.0.1.dist-info/RECORD +137 -0
- pyRadPlan-0.0.1.dist-info/WHEEL +5 -0
- pyRadPlan-0.0.1.dist-info/top_level.txt +3 -0
- test/core/test_coordinates.py +46 -0
- test/core/test_np2sitk.py +178 -0
- test/core/test_resample.py +45 -0
- test/cst/conftest.py +57 -0
- test/cst/test_VOI.py +422 -0
- test/cst/test_cst.py +144 -0
- test/ct/test_ct.py +218 -0
- test/ct/test_hlut.py +10 -0
- test/dose/test_dose_particle.py +234 -0
- test/dose/test_dose_photon.py +22 -0
- test/geometry/test_lps.py +96 -0
- test/stf/test_beamlet.py +53 -0
- test/stf/test_stf.py +205 -0
- test/stf/test_stf_gen.py +295 -0
- test/test_dij.py +238 -0
- test/test_fileHandling.py +37 -0
- test/test_grid.py +148 -0
- test/test_helpers.py +65 -0
- test/test_machine_model.py +155 -0
- test/test_matlabEngine.py +30 -0
- test/test_objectives.py +371 -0
- test/test_octaveEngine.py +30 -0
- test/test_plan.py +158 -0
- test/test_raytracersiddon.py +104 -0
- test/test_scenarios.py +198 -0
pyRadPlan/core/_grids.py
ADDED
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
from typing import Any, Union
|
|
2
|
+
from typing_extensions import Self
|
|
3
|
+
from pydantic import (
|
|
4
|
+
Field,
|
|
5
|
+
field_validator,
|
|
6
|
+
computed_field,
|
|
7
|
+
)
|
|
8
|
+
from numpydantic import NDArray, Shape
|
|
9
|
+
import numpy as np
|
|
10
|
+
import SimpleITK as sitk
|
|
11
|
+
|
|
12
|
+
from .datamodel import PyRadPlanBaseModel
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class Grid(PyRadPlanBaseModel):
|
|
16
|
+
"""
|
|
17
|
+
Class representing image grids in the LPS world system.
|
|
18
|
+
|
|
19
|
+
Attributes
|
|
20
|
+
----------
|
|
21
|
+
resolution : dict[str, float]
|
|
22
|
+
The resolution of the grid in the x, y, and z directions.
|
|
23
|
+
dimensions : tuple[int, int, int]
|
|
24
|
+
The dimensions of the grid in the x, y, and z directions.
|
|
25
|
+
origin : np.ndarray
|
|
26
|
+
The origin of the grid in the LPS world system.
|
|
27
|
+
direction : np.ndarray
|
|
28
|
+
The direction cosines of the grid in the LPS world system.
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
resolution: dict[str, float]
|
|
32
|
+
dimensions: tuple[int, int, int]
|
|
33
|
+
origin: NDArray[Shape["3"], np.floating] = Field(
|
|
34
|
+
default=np.array([0.0, 0.0, 0.0], dtype=np.float64), alias="cubeCoordOffset"
|
|
35
|
+
)
|
|
36
|
+
direction: NDArray[Shape["3,3"], np.floating] = Field(default=np.eye(3, dtype=np.float64))
|
|
37
|
+
|
|
38
|
+
@computed_field(alias="numOfVoxels")
|
|
39
|
+
@property
|
|
40
|
+
def num_voxels(self) -> int:
|
|
41
|
+
"""Number of voxels in the grid."""
|
|
42
|
+
return int(np.prod(self.dimensions))
|
|
43
|
+
|
|
44
|
+
@computed_field
|
|
45
|
+
@property
|
|
46
|
+
def x(self) -> float:
|
|
47
|
+
"""Return the x coordinates in the LPS world system."""
|
|
48
|
+
x = np.arange(self.dimensions[0]) * self.resolution["x"] + self.origin[0]
|
|
49
|
+
return x
|
|
50
|
+
|
|
51
|
+
@computed_field
|
|
52
|
+
@property
|
|
53
|
+
def y(self) -> float:
|
|
54
|
+
"""Return the y coordinates in the LPS world system."""
|
|
55
|
+
y = np.arange(self.dimensions[1]) * self.resolution["y"] + self.origin[1]
|
|
56
|
+
return y
|
|
57
|
+
|
|
58
|
+
@computed_field
|
|
59
|
+
@property
|
|
60
|
+
def z(self) -> float:
|
|
61
|
+
"""Return the z coordinates in the LPS world system."""
|
|
62
|
+
z = np.arange(self.dimensions[2]) * self.resolution["z"] + self.origin[2]
|
|
63
|
+
return z
|
|
64
|
+
|
|
65
|
+
@property
|
|
66
|
+
def resolution_vector(self) -> np.ndarray:
|
|
67
|
+
"""Return the resolution as a vector."""
|
|
68
|
+
return np.array([self.resolution["x"], self.resolution["y"], self.resolution["z"]])
|
|
69
|
+
|
|
70
|
+
@field_validator("resolution", mode="after")
|
|
71
|
+
@classmethod
|
|
72
|
+
def _check_resolution(cls, value: dict[str, float]) -> dict[str, float]:
|
|
73
|
+
"""Check if resolution has the correct structure and values."""
|
|
74
|
+
# Check if resolution has the correct structure (dict with keys 'x', 'y', 'z')
|
|
75
|
+
if not all(key in value for key in ["x", "y", "z"]):
|
|
76
|
+
raise ValueError("resolution must have keys 'x', 'y', 'z'")
|
|
77
|
+
|
|
78
|
+
# Check if all resolution values are positive floats. If not, try to cast them to float
|
|
79
|
+
for key in value:
|
|
80
|
+
if value[key] <= 0:
|
|
81
|
+
raise ValueError(f"resolution values must be positive floats, got {value[key]}")
|
|
82
|
+
|
|
83
|
+
return value
|
|
84
|
+
|
|
85
|
+
@field_validator("dimensions")
|
|
86
|
+
@classmethod
|
|
87
|
+
def _check_dimensions(cls, value: tuple[int, int, int]) -> tuple[int, int, int]:
|
|
88
|
+
"""Check if dimensions has the correct structure and values."""
|
|
89
|
+
# Check if dimensions has exactly 3 elements
|
|
90
|
+
if len(value) != 3:
|
|
91
|
+
raise ValueError("dimensions must have exactly 3 elements")
|
|
92
|
+
|
|
93
|
+
# Check if all dimensions values are positive integers. If not, try to cast them to int
|
|
94
|
+
for dim in value:
|
|
95
|
+
try:
|
|
96
|
+
dim = int(dim)
|
|
97
|
+
except ValueError:
|
|
98
|
+
raise ValueError(f"dimension value could not be casted into int, got {dim}")
|
|
99
|
+
if dim <= 0:
|
|
100
|
+
raise ValueError(f"dimension values must be positive integers, got {dim}")
|
|
101
|
+
|
|
102
|
+
return value
|
|
103
|
+
|
|
104
|
+
@field_validator("origin", mode="before")
|
|
105
|
+
@classmethod
|
|
106
|
+
def _check_origin(cls, value: Any) -> Any:
|
|
107
|
+
"""Check if origin has the correct shape (3,) and values."""
|
|
108
|
+
# Check if origin has the correct shape (3,)
|
|
109
|
+
try:
|
|
110
|
+
value = np.asarray(value, dtype=np.float64).reshape((3,))
|
|
111
|
+
except ValueError as exc:
|
|
112
|
+
raise ValueError("origin must be convertible to a 1D numpy array of length 3") from exc
|
|
113
|
+
return value
|
|
114
|
+
|
|
115
|
+
@field_validator("direction", mode="before")
|
|
116
|
+
@classmethod
|
|
117
|
+
def _check_direction(cls, value: Any) -> Any:
|
|
118
|
+
"""Check if direction has the correct shape (3x3)."""
|
|
119
|
+
|
|
120
|
+
try:
|
|
121
|
+
value = np.asarray(value, dtype=np.float64).reshape((3, 3))
|
|
122
|
+
except ValueError as exc:
|
|
123
|
+
raise ValueError("direction must be convertible to a 3x3 numpy matrix") from exc
|
|
124
|
+
return value
|
|
125
|
+
|
|
126
|
+
# TODO: validate for additional fields if, e.g., loaded from matRad
|
|
127
|
+
|
|
128
|
+
def to_matrad(self, context: str = "mat-file") -> Any:
|
|
129
|
+
grid_dict4matrad = super().to_matrad(context=context)
|
|
130
|
+
grid_dict4matrad["dimensions"] = tuple(map(float, grid_dict4matrad["dimensions"]))
|
|
131
|
+
grid_dict4matrad["numOfVoxels"] = float(grid_dict4matrad["numOfVoxels"])
|
|
132
|
+
return grid_dict4matrad
|
|
133
|
+
|
|
134
|
+
@classmethod
|
|
135
|
+
def from_sitk_image(cls, sitk_image: sitk.Image) -> Self:
|
|
136
|
+
"""
|
|
137
|
+
Create a Grid object from a SimpleITK image.
|
|
138
|
+
|
|
139
|
+
Parameters
|
|
140
|
+
----------
|
|
141
|
+
sitk_image : sitk.Image
|
|
142
|
+
The SimpleITK image to create the Grid object from.
|
|
143
|
+
|
|
144
|
+
Returns
|
|
145
|
+
-------
|
|
146
|
+
Grid
|
|
147
|
+
The Grid object created from the SimpleITK image.
|
|
148
|
+
"""
|
|
149
|
+
keys = ["x", "y", "z"]
|
|
150
|
+
resolution = {key: value for key, value in zip(keys, sitk_image.GetSpacing())}
|
|
151
|
+
dimensions = sitk_image.GetSize()
|
|
152
|
+
origin = sitk_image.GetOrigin()
|
|
153
|
+
direction = sitk_image.GetDirection()
|
|
154
|
+
return cls(
|
|
155
|
+
resolution=resolution, dimensions=dimensions, origin=origin, direction=direction
|
|
156
|
+
)
|
|
157
|
+
|
|
158
|
+
def resample(
|
|
159
|
+
self,
|
|
160
|
+
target_resolution: Union[
|
|
161
|
+
dict[str, float], np.ndarray, tuple[float, float, float], list[float]
|
|
162
|
+
],
|
|
163
|
+
) -> Self:
|
|
164
|
+
"""
|
|
165
|
+
Create a resampled grid covering the original grid in a new
|
|
166
|
+
resolution.
|
|
167
|
+
|
|
168
|
+
Parameters
|
|
169
|
+
----------
|
|
170
|
+
target_resolution : Union[dict[str,float], np.ndarray]
|
|
171
|
+
The target resolution of the resampled grid.
|
|
172
|
+
|
|
173
|
+
Returns
|
|
174
|
+
-------
|
|
175
|
+
Grid
|
|
176
|
+
The resampled grid object.
|
|
177
|
+
"""
|
|
178
|
+
|
|
179
|
+
if isinstance(target_resolution, dict):
|
|
180
|
+
target_resolution = np.array(
|
|
181
|
+
[target_resolution["x"], target_resolution["y"], target_resolution["z"]]
|
|
182
|
+
)
|
|
183
|
+
else:
|
|
184
|
+
try:
|
|
185
|
+
target_resolution = np.asarray(target_resolution).reshape(
|
|
186
|
+
3,
|
|
187
|
+
)
|
|
188
|
+
except ValueError as exc:
|
|
189
|
+
raise ValueError(
|
|
190
|
+
"target_resolution must be convertible to an ndarray of shape (3,)"
|
|
191
|
+
) from exc
|
|
192
|
+
|
|
193
|
+
# Calculate the new dimensions
|
|
194
|
+
new_dimensions = np.ceil(
|
|
195
|
+
np.array(self.dimensions) * self.resolution_vector / target_resolution
|
|
196
|
+
).astype(int)
|
|
197
|
+
|
|
198
|
+
# Now calculate the width of the grid in the new resolution
|
|
199
|
+
old_grid_size = np.array(self.dimensions) * self.resolution_vector
|
|
200
|
+
new_grid_size = new_dimensions * target_resolution
|
|
201
|
+
diff_size = new_grid_size - old_grid_size
|
|
202
|
+
|
|
203
|
+
# find the origin of the new image such that it is centered above the old image. The origin
|
|
204
|
+
# is in the center of the first voxel
|
|
205
|
+
origin_shift = diff_size / 2.0
|
|
206
|
+
|
|
207
|
+
# now we need to respect the origin and direction to correctly shift the new grid into
|
|
208
|
+
# position
|
|
209
|
+
origin_shift = np.matmul(self.direction, origin_shift)
|
|
210
|
+
new_origin = self.origin - origin_shift
|
|
211
|
+
|
|
212
|
+
return Grid(
|
|
213
|
+
resolution=dict(zip(["x", "y", "z"], target_resolution)),
|
|
214
|
+
dimensions=tuple(new_dimensions),
|
|
215
|
+
origin=new_origin,
|
|
216
|
+
direction=self.direction,
|
|
217
|
+
)
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
if __name__ == "__main__":
|
|
221
|
+
# Example usage
|
|
222
|
+
try:
|
|
223
|
+
grid_dict = {
|
|
224
|
+
"resolution": {"x": 1, "y": 1, "z": 1},
|
|
225
|
+
"dimensions": (10, 10, 10),
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
grid_information = Grid.model_validate(grid_dict)
|
|
229
|
+
print(grid_information.to_matrad())
|
|
230
|
+
except Exception as e:
|
|
231
|
+
print("Error creating grid from dose_information:", e)
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
"""Module datamodel.py
|
|
2
|
+
Basic Model for all pyRadPlan Datastructures.
|
|
3
|
+
"""
|
|
4
|
+
from typing import Any, Union
|
|
5
|
+
from pydantic import (
|
|
6
|
+
AliasGenerator,
|
|
7
|
+
BaseModel,
|
|
8
|
+
ConfigDict,
|
|
9
|
+
)
|
|
10
|
+
from pydantic.alias_generators import to_camel
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class PyRadPlanBaseModel(BaseModel):
|
|
14
|
+
"""
|
|
15
|
+
Base class for all pyRadPlan data structures, especially the ones that
|
|
16
|
+
should be matRad
|
|
17
|
+
compatible
|
|
18
|
+
This class extends Pydantic's BaseModel.
|
|
19
|
+
|
|
20
|
+
Attributes
|
|
21
|
+
----------
|
|
22
|
+
model_config : ConfigDict
|
|
23
|
+
Configuration for the model, including alias generation, population by name, arbitrary
|
|
24
|
+
types allowed, assignment validation, and attribute creation from dictionary.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
model_config = ConfigDict(
|
|
28
|
+
alias_generator=AliasGenerator(alias=to_camel),
|
|
29
|
+
populate_by_name=True, # Allows both snake_case and camelCase attributes
|
|
30
|
+
arbitrary_types_allowed=True, # Allows arbitrary types in the model (will be casted)
|
|
31
|
+
validate_assignment=True, # Validate assignment of values to fields
|
|
32
|
+
# (not only during construction)
|
|
33
|
+
from_attributes=True, # Allows to create a model from a dictionary
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
def to_matrad(self, context: Union[str, dict] = "mat-file") -> Any:
|
|
37
|
+
"""
|
|
38
|
+
Interface method to serialize a pyradplan datastructure to be matRad
|
|
39
|
+
compatible.
|
|
40
|
+
|
|
41
|
+
Parameters
|
|
42
|
+
----------
|
|
43
|
+
context : str, optional
|
|
44
|
+
The context in which the datastructure should be serialized, by default 'mat-file'.
|
|
45
|
+
|
|
46
|
+
Returns
|
|
47
|
+
-------
|
|
48
|
+
Any
|
|
49
|
+
A datastructre compatible with matRad in the given context
|
|
50
|
+
|
|
51
|
+
Notes
|
|
52
|
+
-----
|
|
53
|
+
Currently, the only supported context is 'mat-file'. In the future, this could be
|
|
54
|
+
extended to support other contexts, such as direct calling via the matlab engine or
|
|
55
|
+
oct2py.
|
|
56
|
+
"""
|
|
57
|
+
|
|
58
|
+
if isinstance(context, dict):
|
|
59
|
+
if "matRad" not in context:
|
|
60
|
+
context.update({"matRad": "mat-file"})
|
|
61
|
+
else:
|
|
62
|
+
context = {"matRad": context}
|
|
63
|
+
|
|
64
|
+
if context["matRad"] != "mat-file":
|
|
65
|
+
raise ValueError(f"Context {context} not supported")
|
|
66
|
+
|
|
67
|
+
# Standard is a model_dump using above alias and context information
|
|
68
|
+
return self.model_dump(by_alias=True, context=context)
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
"""Helper Functions relating to conversion between numpy and SimpleITK data
|
|
2
|
+
types.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from typing import Literal
|
|
6
|
+
import SimpleITK as sitk
|
|
7
|
+
import numpy as np
|
|
8
|
+
from ._grids import Grid
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def sitk_mask_to_linear_indices(mask: sitk.Image, order="sitk") -> np.ndarray:
|
|
12
|
+
"""
|
|
13
|
+
Convert a SimpleITK mask to linear indices.
|
|
14
|
+
|
|
15
|
+
Parameters
|
|
16
|
+
----------
|
|
17
|
+
mask : sitk.Image
|
|
18
|
+
The SimpleITK image mask to be converted.
|
|
19
|
+
order : str, optional
|
|
20
|
+
The ordering of the indices. Can be 'sitk' for Fortran-like index
|
|
21
|
+
ordering or 'numpy' for C-like index ordering. Default is 'sitk'.
|
|
22
|
+
|
|
23
|
+
Returns
|
|
24
|
+
-------
|
|
25
|
+
np.ndarray
|
|
26
|
+
A 1D numpy array of linear indices where the mask is non-zero.
|
|
27
|
+
|
|
28
|
+
Raises
|
|
29
|
+
------
|
|
30
|
+
ValueError
|
|
31
|
+
If the ordering is not 'sitk' or 'numpy'.
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
arr = sitk.GetArrayViewFromImage(mask)
|
|
35
|
+
if order == "sitk":
|
|
36
|
+
return np.nonzero(arr.ravel(order="F"))[0]
|
|
37
|
+
elif order == "numpy":
|
|
38
|
+
return np.flatnonzero(arr)
|
|
39
|
+
else:
|
|
40
|
+
raise ValueError("Invalid ordering. Must be 'sitk' or 'numpy'.")
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def linear_indices_to_sitk_mask(
|
|
44
|
+
indices: np.ndarray, ref_image: sitk.Image, order="sitk"
|
|
45
|
+
) -> sitk.Image:
|
|
46
|
+
"""
|
|
47
|
+
Convert linear indices to a SimpleITK mask.
|
|
48
|
+
|
|
49
|
+
Parameters
|
|
50
|
+
----------
|
|
51
|
+
indices : np.ndarray
|
|
52
|
+
A 1D numpy array of linear indices where the mask is non-zero.
|
|
53
|
+
ref_image : sitk.Image
|
|
54
|
+
The reference image on which the mask is defined.
|
|
55
|
+
order : str, optional
|
|
56
|
+
The ordering of the indices. Can be 'sitk' for Fortran-like index
|
|
57
|
+
ordering or 'numpy' for C-like index ordering. Default is 'sitk'.
|
|
58
|
+
|
|
59
|
+
Returns
|
|
60
|
+
-------
|
|
61
|
+
sitk.Image
|
|
62
|
+
A SimpleITK image mask with the indices set to non-zero.
|
|
63
|
+
|
|
64
|
+
Raises
|
|
65
|
+
------
|
|
66
|
+
ValueError
|
|
67
|
+
If the ordering is not 'sitk' or 'numpy'.
|
|
68
|
+
"""
|
|
69
|
+
|
|
70
|
+
arr = np.zeros_like(sitk.GetArrayViewFromImage(ref_image), dtype=np.uint8)
|
|
71
|
+
|
|
72
|
+
if order == "sitk":
|
|
73
|
+
arr.T.flat[indices] = 1
|
|
74
|
+
elif order == "numpy":
|
|
75
|
+
arr.flat[indices] = 1
|
|
76
|
+
else:
|
|
77
|
+
raise ValueError("Invalid ordering. Must be 'sitk' or 'numpy'.")
|
|
78
|
+
|
|
79
|
+
mask = sitk.GetImageFromArray(arr)
|
|
80
|
+
mask.CopyInformation(ref_image)
|
|
81
|
+
|
|
82
|
+
return mask
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def linear_indices_to_grid_coordinates(
|
|
86
|
+
indices: np.ndarray, grid: Grid, index_type: Literal["numpy", "sitk"] = "numpy"
|
|
87
|
+
) -> np.ndarray:
|
|
88
|
+
"""
|
|
89
|
+
Convert linear indices to gridcoordinates.
|
|
90
|
+
|
|
91
|
+
Parameters
|
|
92
|
+
----------
|
|
93
|
+
indices : np.ndarray
|
|
94
|
+
A 1D numpy array of linear indices where the mask is non-zero.
|
|
95
|
+
grid : Grid
|
|
96
|
+
The image grid on which the indices lie.
|
|
97
|
+
index_type : Literal["numpy", "sitk"], optional
|
|
98
|
+
The ordering of the indices. Can be 'sitk' for Fortran-like index
|
|
99
|
+
ordering or 'numpy' for C-like index ordering. Default is 'numpy'.
|
|
100
|
+
|
|
101
|
+
Returns
|
|
102
|
+
-------
|
|
103
|
+
np.ndarray
|
|
104
|
+
A 2D numpy array of image coordinates.
|
|
105
|
+
"""
|
|
106
|
+
|
|
107
|
+
if index_type == "numpy":
|
|
108
|
+
z, y, x = np.unravel_index(indices, grid.dimensions[::-1])
|
|
109
|
+
elif index_type == "sitk":
|
|
110
|
+
x, y, z = np.unravel_index(indices, grid.dimensions)
|
|
111
|
+
else:
|
|
112
|
+
raise ValueError("Invalid index type. Must be 'numpy' or 'sitk'.")
|
|
113
|
+
|
|
114
|
+
v = np.array([x, y, z])
|
|
115
|
+
|
|
116
|
+
spacing_diag = np.diag([grid.resolution["x"], grid.resolution["y"], grid.resolution["z"]])
|
|
117
|
+
origin = grid.origin
|
|
118
|
+
|
|
119
|
+
physical_point = origin + np.matmul(np.matmul(grid.direction, spacing_diag), v).T
|
|
120
|
+
|
|
121
|
+
return physical_point
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def linear_indices_to_image_coordinates(
|
|
125
|
+
indices: np.ndarray, image: sitk.Image, index_type: Literal["numpy", "sitk"] = "numpy"
|
|
126
|
+
) -> np.ndarray:
|
|
127
|
+
"""
|
|
128
|
+
Convert linear indices to image coordinates.
|
|
129
|
+
|
|
130
|
+
Parameters
|
|
131
|
+
----------
|
|
132
|
+
indices : np.ndarray
|
|
133
|
+
A 1D numpy array of linear indices where the mask is non-zero.
|
|
134
|
+
image : sitk.Image
|
|
135
|
+
The reference image on which the mask is defined.
|
|
136
|
+
index_type : Literal["numpy", "sitk"], optional
|
|
137
|
+
The ordering of the indices. Can be 'sitk' for Fortran-like index
|
|
138
|
+
ordering or 'numpy' for C-like index ordering. Default is 'numpy'.
|
|
139
|
+
|
|
140
|
+
Returns
|
|
141
|
+
-------
|
|
142
|
+
np.ndarray
|
|
143
|
+
A 2D numpy array of image coordinates.
|
|
144
|
+
"""
|
|
145
|
+
|
|
146
|
+
grid = Grid.from_sitk_image(image)
|
|
147
|
+
return linear_indices_to_grid_coordinates(indices, grid, index_type)
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
import SimpleITK as sitk
|
|
3
|
+
from ._grids import Grid
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def resample_image(
|
|
7
|
+
input_image: sitk.Image,
|
|
8
|
+
interpolator=sitk.sitkBSpline,
|
|
9
|
+
target_image: sitk.Image = None,
|
|
10
|
+
target_grid_spacing: tuple[float, float, float] = None,
|
|
11
|
+
target_grid: Grid = None,
|
|
12
|
+
) -> sitk.Image: # also accept sitk images and grid points. Can be dealt with with kwargs
|
|
13
|
+
"""
|
|
14
|
+
Resamples an sitk Image to a target resolution, reference image
|
|
15
|
+
dimensions, or Grid.
|
|
16
|
+
|
|
17
|
+
Parameters
|
|
18
|
+
----------
|
|
19
|
+
input_image : sitk.Image
|
|
20
|
+
The input image to be resampled.
|
|
21
|
+
interpolator : sitk.InterpolatorEnum, optional
|
|
22
|
+
The interpolator to use for resampling. Default is sitk.sitkBSpline.
|
|
23
|
+
target_image : sitk.Image, optional
|
|
24
|
+
The reference image to resample to. Default is None.
|
|
25
|
+
target_grid_spacing : tuple[float,float,float], optional
|
|
26
|
+
The target grid spacing to resample to. Default is None.
|
|
27
|
+
target_grid : Grid, optional
|
|
28
|
+
The target grid to resample to. Default is None.
|
|
29
|
+
|
|
30
|
+
Returns
|
|
31
|
+
-------
|
|
32
|
+
sitk.Image
|
|
33
|
+
The resampled image.
|
|
34
|
+
|
|
35
|
+
Notes
|
|
36
|
+
-----
|
|
37
|
+
Exactly one of target_image, target_grid_spacing, or target_grid must be provided.
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
if [target_image, target_grid_spacing, target_grid].count(None) != 2:
|
|
41
|
+
raise TypeError(
|
|
42
|
+
"Only one of target_image, target_grid_spacing, or target_grid must be provided."
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
image_grid = Grid.from_sitk_image(input_image)
|
|
46
|
+
|
|
47
|
+
if target_image is not None:
|
|
48
|
+
target_grid = Grid.from_sitk_image(target_image)
|
|
49
|
+
elif target_grid_spacing is not None:
|
|
50
|
+
target_grid = image_grid.resample(target_grid_spacing)
|
|
51
|
+
|
|
52
|
+
resample = sitk.ResampleImageFilter()
|
|
53
|
+
resample.SetOutputSpacing(target_grid.resolution_vector)
|
|
54
|
+
resample.SetSize(target_grid.dimensions)
|
|
55
|
+
resample.SetOutputDirection(target_grid.direction.ravel())
|
|
56
|
+
resample.SetOutputOrigin(target_grid.origin)
|
|
57
|
+
resample.SetInterpolator(interpolator)
|
|
58
|
+
resampled_image = resample.Execute(input_image)
|
|
59
|
+
|
|
60
|
+
return resampled_image
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def resample_numpy_array(
|
|
64
|
+
input_array: np.ndarray,
|
|
65
|
+
reference_image: sitk.Image = None,
|
|
66
|
+
reference_grid: Grid = None,
|
|
67
|
+
interpolator=sitk.sitkBSpline,
|
|
68
|
+
target_image: sitk.Image = None,
|
|
69
|
+
target_grid_spacing: tuple[float, float, float] = None,
|
|
70
|
+
target_grid: Grid = None,
|
|
71
|
+
) -> np.ndarray:
|
|
72
|
+
"""
|
|
73
|
+
Resamples a numpy grid to a target resolution, reference image
|
|
74
|
+
dimensions, or Grid.
|
|
75
|
+
We convert the numpy array to an sitk.Image, so the dimensions will be
|
|
76
|
+
switched. More exactly,
|
|
77
|
+
the numpy array will be index i,j,k <-> z,y,x, which will converted to
|
|
78
|
+
j,i,k <-> y,x,z in sitk.
|
|
79
|
+
This is to be considered when supplying the reference grid or image.
|
|
80
|
+
|
|
81
|
+
Parameters
|
|
82
|
+
----------
|
|
83
|
+
input_image : sitk.Image
|
|
84
|
+
The input image to be resampled.
|
|
85
|
+
reference_image : sitk.Image, optional
|
|
86
|
+
The reference image providing spatial information of the array. Default is None.
|
|
87
|
+
Be wary of sitk <-> numpy indexing conventions.
|
|
88
|
+
reference_grid : Grid, optional
|
|
89
|
+
The reference grid of the resampled array. Default is None.
|
|
90
|
+
Be wary of sitk <-> numpy indexing conventions.
|
|
91
|
+
interpolator : sitk.InterpolatorEnum, optional
|
|
92
|
+
The interpolator to use for resampling. Default is sitk.sitkBSpline.
|
|
93
|
+
target_image : sitk.Image, optional
|
|
94
|
+
The reference image to resample to. Default is None.
|
|
95
|
+
target_grid_spacing : tuple[float,float,float], optional
|
|
96
|
+
The target grid spacing to resample to. Default is None.
|
|
97
|
+
target_grid : Grid, optional
|
|
98
|
+
The target grid to resample to. Default is None.
|
|
99
|
+
|
|
100
|
+
Returns
|
|
101
|
+
-------
|
|
102
|
+
sitk.Image
|
|
103
|
+
The resampled image.
|
|
104
|
+
|
|
105
|
+
Notes
|
|
106
|
+
-----
|
|
107
|
+
Exactly one of target_image, target_grid_spacing, or target_grid must be provided.
|
|
108
|
+
"""
|
|
109
|
+
|
|
110
|
+
if [reference_image, reference_grid].count(None) != 1:
|
|
111
|
+
raise TypeError("Only one of reference_image or reference_grid must be provided.")
|
|
112
|
+
|
|
113
|
+
if reference_image is not None:
|
|
114
|
+
reference_grid = Grid.from_sitk_image(reference_image)
|
|
115
|
+
|
|
116
|
+
# I think there is an issue here. The axes are flipped with GetImageFromArray
|
|
117
|
+
array_sitk = sitk.GetImageFromArray(input_array)
|
|
118
|
+
array_sitk.SetOrigin(reference_grid.origin)
|
|
119
|
+
array_sitk.SetSpacing(reference_grid.resolution_vector)
|
|
120
|
+
array_sitk.SetDirection(reference_grid.direction.ravel())
|
|
121
|
+
|
|
122
|
+
resampled_array_sitk = resample_image(
|
|
123
|
+
input_image=array_sitk,
|
|
124
|
+
interpolator=interpolator,
|
|
125
|
+
target_image=target_image,
|
|
126
|
+
target_grid_spacing=target_grid_spacing,
|
|
127
|
+
target_grid=target_grid,
|
|
128
|
+
)
|
|
129
|
+
|
|
130
|
+
return sitk.GetArrayFromImage(resampled_array_sitk)
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
from ._voi import VOI, OAR, Target, HelperVOI, ExternalVOI, create_voi, validate_voi
|
|
2
|
+
from ._cst import StructureSet, create_cst, validate_cst
|
|
3
|
+
|
|
4
|
+
__all__ = [
|
|
5
|
+
"StructureSet",
|
|
6
|
+
"create_cst",
|
|
7
|
+
"validate_cst",
|
|
8
|
+
"VOI",
|
|
9
|
+
"OAR",
|
|
10
|
+
"Target",
|
|
11
|
+
"HelperVOI",
|
|
12
|
+
"ExternalVOI",
|
|
13
|
+
"create_voi",
|
|
14
|
+
"validate_voi",
|
|
15
|
+
]
|