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.
Files changed (137) hide show
  1. examples/carbon_pencilbeam.py +87 -0
  2. examples/helium_pencilbeam.py +80 -0
  3. examples/import_matrad_patient.py +102 -0
  4. examples/photon_pencilbeam.py +66 -0
  5. examples/proton_pencilbeam.py +80 -0
  6. pyRadPlan/GUI.py +5 -0
  7. pyRadPlan/__init__.py +34 -0
  8. pyRadPlan/core/__init__.py +15 -0
  9. pyRadPlan/core/_exceptions.py +9 -0
  10. pyRadPlan/core/_grids.py +231 -0
  11. pyRadPlan/core/datamodel.py +68 -0
  12. pyRadPlan/core/np2sitk.py +147 -0
  13. pyRadPlan/core/resample.py +130 -0
  14. pyRadPlan/cst/__init__.py +15 -0
  15. pyRadPlan/cst/_cst.py +307 -0
  16. pyRadPlan/cst/_voi.py +603 -0
  17. pyRadPlan/ct/__init__.py +4 -0
  18. pyRadPlan/ct/_ct.py +525 -0
  19. pyRadPlan/ct/_hlut.py +27 -0
  20. pyRadPlan/data/machines/carbon_Generic.mat +0 -0
  21. pyRadPlan/data/machines/helium_Generic.mat +0 -0
  22. pyRadPlan/data/machines/photons_Generic.mat +0 -0
  23. pyRadPlan/data/machines/protons_Generic.mat +0 -0
  24. pyRadPlan/data/phantoms/TG119.mat +0 -0
  25. pyRadPlan/data/stf/matRad_stf.mat +0 -0
  26. pyRadPlan/data/stf/matrad_stf_onebeam.mat +0 -0
  27. pyRadPlan/dij/__init__.py +4 -0
  28. pyRadPlan/dij/_dij.py +410 -0
  29. pyRadPlan/dose/__init__.py +6 -0
  30. pyRadPlan/dose/_calc_dose.py +64 -0
  31. pyRadPlan/dose/engines/__init__.py +17 -0
  32. pyRadPlan/dose/engines/_base.py +591 -0
  33. pyRadPlan/dose/engines/_base_pencilbeam.py +806 -0
  34. pyRadPlan/dose/engines/_base_pencilbeam_particle.py +1015 -0
  35. pyRadPlan/dose/engines/_factory.py +108 -0
  36. pyRadPlan/dose/engines/_hongpb.py +75 -0
  37. pyRadPlan/dose/engines/_svdpb.py +275 -0
  38. pyRadPlan/geometry/__init__.py +7 -0
  39. pyRadPlan/geometry/lps.py +122 -0
  40. pyRadPlan/io/.gitkeep +0 -0
  41. pyRadPlan/io/__init__.py +3 -0
  42. pyRadPlan/io/matLabFileHandler.py +25 -0
  43. pyRadPlan/io/matRad.py +22 -0
  44. pyRadPlan/io/readHLUT.py +17 -0
  45. pyRadPlan/io/temp_files/cst.mat +0 -0
  46. pyRadPlan/io/temp_files/ct.mat +0 -0
  47. pyRadPlan/io/temp_files/pln.mat +0 -0
  48. pyRadPlan/io/temp_files/stf_with_separate_rays.mat +0 -0
  49. pyRadPlan/machines/__init__.py +19 -0
  50. pyRadPlan/machines/_base.py +164 -0
  51. pyRadPlan/machines/_ions.py +528 -0
  52. pyRadPlan/machines/_load.py +48 -0
  53. pyRadPlan/machines/_photons.py +220 -0
  54. pyRadPlan/machines/_validate.py +61 -0
  55. pyRadPlan/matRad/.gitkeep +0 -0
  56. pyRadPlan/matRad/__init__.py +18 -0
  57. pyRadPlan/matRad/_engine.py +36 -0
  58. pyRadPlan/matRad/_matlab.py +26 -0
  59. pyRadPlan/matRad/_octave.py +51 -0
  60. pyRadPlan/optimization/__init__.py +12 -0
  61. pyRadPlan/optimization/_fluenceOptimizer.py +312 -0
  62. pyRadPlan/optimization/_fluence_optimization.py +57 -0
  63. pyRadPlan/optimization/components/__init__.py +3 -0
  64. pyRadPlan/optimization/components/_optimizationProblem.py +162 -0
  65. pyRadPlan/optimization/components/objectives/_EUD.py +93 -0
  66. pyRadPlan/optimization/components/objectives/__init__.py +19 -0
  67. pyRadPlan/optimization/components/objectives/_doseUniformity.py +81 -0
  68. pyRadPlan/optimization/components/objectives/_maxDVH.py +92 -0
  69. pyRadPlan/optimization/components/objectives/_meanDose.py +80 -0
  70. pyRadPlan/optimization/components/objectives/_minDVH.py +92 -0
  71. pyRadPlan/optimization/components/objectives/_objectiveClass.py +98 -0
  72. pyRadPlan/optimization/components/objectives/_squaredDeviation.py +82 -0
  73. pyRadPlan/optimization/components/objectives/_squaredOverdosing.py +84 -0
  74. pyRadPlan/optimization/components/objectives/_squaredUnderdosing.py +84 -0
  75. pyRadPlan/optimization/projections/__init__.py +5 -0
  76. pyRadPlan/optimization/projections/_backProjection.py +59 -0
  77. pyRadPlan/optimization/projections/_constantRBEProjection.py +26 -0
  78. pyRadPlan/optimization/projections/_doseProjection.py +25 -0
  79. pyRadPlan/optimization/solvers/__init__.py +18 -0
  80. pyRadPlan/optimization/solvers/_ipopt.py +89 -0
  81. pyRadPlan/optimization/solvers/_scipy_solver.py +120 -0
  82. pyRadPlan/plan/__init__.py +3 -0
  83. pyRadPlan/plan/_plans.py +360 -0
  84. pyRadPlan/raytracer/__init__.py +4 -0
  85. pyRadPlan/raytracer/_base.py +289 -0
  86. pyRadPlan/raytracer/_perf.py +227 -0
  87. pyRadPlan/raytracer/_siddon.py +428 -0
  88. pyRadPlan/scenarios/__init__.py +102 -0
  89. pyRadPlan/scenarios/_base.py +374 -0
  90. pyRadPlan/scenarios/_nominal.py +126 -0
  91. pyRadPlan/stf/__init__.py +29 -0
  92. pyRadPlan/stf/_base.py +226 -0
  93. pyRadPlan/stf/_beam.py +195 -0
  94. pyRadPlan/stf/_beamlet.py +106 -0
  95. pyRadPlan/stf/_exceptions.py +14 -0
  96. pyRadPlan/stf/_externalbeam.py +162 -0
  97. pyRadPlan/stf/_generate_stf.py +23 -0
  98. pyRadPlan/stf/_ions.py +255 -0
  99. pyRadPlan/stf/_photons.py +125 -0
  100. pyRadPlan/stf/_rangeshifter.py +40 -0
  101. pyRadPlan/stf/_ray.py +201 -0
  102. pyRadPlan/stf/_steeringinformation.py +181 -0
  103. pyRadPlan/stf/base_matrad.py +6 -0
  104. pyRadPlan/stf/hlutLibrary/matRad_default.hlut +10 -0
  105. pyRadPlan/stf/loadHLUT.py +63 -0
  106. pyRadPlan/util/__init__.py +0 -0
  107. pyRadPlan/util/helpers.py +209 -0
  108. pyRadPlan-0.0.1.dist-info/LICENSE +28 -0
  109. pyRadPlan-0.0.1.dist-info/METADATA +70 -0
  110. pyRadPlan-0.0.1.dist-info/RECORD +137 -0
  111. pyRadPlan-0.0.1.dist-info/WHEEL +5 -0
  112. pyRadPlan-0.0.1.dist-info/top_level.txt +3 -0
  113. test/core/test_coordinates.py +46 -0
  114. test/core/test_np2sitk.py +178 -0
  115. test/core/test_resample.py +45 -0
  116. test/cst/conftest.py +57 -0
  117. test/cst/test_VOI.py +422 -0
  118. test/cst/test_cst.py +144 -0
  119. test/ct/test_ct.py +218 -0
  120. test/ct/test_hlut.py +10 -0
  121. test/dose/test_dose_particle.py +234 -0
  122. test/dose/test_dose_photon.py +22 -0
  123. test/geometry/test_lps.py +96 -0
  124. test/stf/test_beamlet.py +53 -0
  125. test/stf/test_stf.py +205 -0
  126. test/stf/test_stf_gen.py +295 -0
  127. test/test_dij.py +238 -0
  128. test/test_fileHandling.py +37 -0
  129. test/test_grid.py +148 -0
  130. test/test_helpers.py +65 -0
  131. test/test_machine_model.py +155 -0
  132. test/test_matlabEngine.py +30 -0
  133. test/test_objectives.py +371 -0
  134. test/test_octaveEngine.py +30 -0
  135. test/test_plan.py +158 -0
  136. test/test_raytracersiddon.py +104 -0
  137. test/test_scenarios.py +198 -0
pyRadPlan/cst/_cst.py ADDED
@@ -0,0 +1,307 @@
1
+ """Structure Set Implementation."""
2
+
3
+ from typing import Any, Union
4
+ from typing_extensions import Self
5
+ from pydantic import Field, model_validator
6
+
7
+ import numpy as np
8
+ from scipy import ndimage
9
+ import SimpleITK as sitk
10
+
11
+ from pyRadPlan.core import PyRadPlanBaseModel
12
+ from pyRadPlan.cst import VOI, ExternalVOI, validate_voi
13
+ from pyRadPlan.ct import CT, validate_ct
14
+
15
+
16
+ class StructureSet(PyRadPlanBaseModel):
17
+ """Represents a Structure Set for a Patient."""
18
+
19
+ vois: list[VOI] = Field(init=False, description="List of VOIs in the Structure Set")
20
+ ct_image: CT = Field(init=False, description="Reference to the CT Image")
21
+
22
+ @model_validator(mode="after")
23
+ def check_cst(self) -> Self:
24
+ """Check if the VOIs are valid and reference the same CT."""
25
+
26
+ if isinstance(self.vois, list):
27
+ for voi in self.vois:
28
+ if voi.ct_image != self.ct_image:
29
+ raise ValueError("All VOIs must reference the same CT image.")
30
+
31
+ return self
32
+
33
+ def to_matrad(self, context: str = "mat-file") -> Any:
34
+ """Convert the StructureSet to a matRad writeable format."""
35
+
36
+ if context != "mat-file":
37
+ raise ValueError(f"Context {context} not supported")
38
+
39
+ export_cell_list = []
40
+ for i, voi in enumerate(self.vois):
41
+ voi_list = voi.to_matrad(context=context)
42
+ voi_list[0] = i
43
+ # TODO: set objectives here
44
+ voi_list[5] = {}
45
+
46
+ export_cell_list.append(voi_list)
47
+
48
+ return export_cell_list
49
+
50
+ # Additional Properties
51
+ @property
52
+ def voi_types(self) -> list:
53
+ """Return the unique VOI types in the Structure Set."""
54
+ return list(set([voi.voi_type for voi in self.vois]))
55
+
56
+ def target_union_voxels(self, order="sitk") -> np.ndarray:
57
+ """Return the union of all target indices."""
58
+ target_indices = []
59
+ for voi in self.vois:
60
+ if voi.voi_type == "TARGET":
61
+ target_indices.append(voi.get_indices(order=order))
62
+
63
+ return np.unique(np.concatenate(target_indices))
64
+
65
+ def target_union_mask(self) -> sitk.Image:
66
+ """Return the union mask of all target indices."""
67
+
68
+ target_indices = self.target_union_voxels(order="numpy")
69
+
70
+ # Creates a copy of the CT image with all zeros
71
+
72
+ if self.ct_image.cube_hu.GetDimension() == 4:
73
+ sz = np.array(self.ct_image.cube_hu.GetSize())
74
+ sz[3] = 0
75
+ tmpmask3d = sitk.Extract(
76
+ self.ct_image.cube_hu,
77
+ size=sz.tolist(),
78
+ index=[0, 0, 0, 0],
79
+ directionCollapseToStrategy=sitk.ExtractImageFilter.DIRECTIONCOLLAPSETOSUBMATRIX,
80
+ )
81
+
82
+ else:
83
+ tmpmask3d = self.ct_image.cube_hu
84
+
85
+ mask = sitk.GetArrayViewFromImage(tmpmask3d).astype(np.uint8)
86
+ mask.fill(0)
87
+ mask.ravel()[target_indices] = 1
88
+
89
+ mask_image = sitk.GetImageFromArray(mask)
90
+ mask_image.CopyInformation(tmpmask3d)
91
+
92
+ return mask_image
93
+
94
+ def patient_voxels(self, order="sitk") -> np.ndarray:
95
+ """Return the union of all patient indices."""
96
+
97
+ # First check if we have an "EXTERNAL" VOI designating the outer contour
98
+ for voi in self.vois:
99
+ if isinstance(voi, ExternalVOI):
100
+ return voi.get_indices(order=order)
101
+
102
+ patient_indices = []
103
+ for voi in self.vois:
104
+ patient_indices.append(voi.get_indices(order=order))
105
+
106
+ return np.unique(np.concatenate(patient_indices))
107
+
108
+ def patient_mask(self) -> sitk.Image:
109
+ """Return the union mask of all patient contours (or the EXTERNAL
110
+ contour if provided).
111
+ """
112
+
113
+ patient_indices = self.patient_voxels(order="numpy")
114
+
115
+ # Creates a copy of the CT image with all zeros
116
+ mask = sitk.GetArrayFromImage(self.ct_image.cube_hu).astype(np.uint8)
117
+ mask.fill(0)
118
+ mask.ravel()[patient_indices] = 1
119
+
120
+ mask_image = sitk.GetImageFromArray(mask)
121
+ mask_image.CopyInformation(self.ct_image.cube_hu)
122
+
123
+ return mask_image
124
+
125
+ def target_center_of_mass(self) -> np.ndarray:
126
+ """Return the center of mass of the target."""
127
+ mask_image = self.target_union_mask()
128
+ mask = sitk.GetArrayViewFromImage(
129
+ mask_image
130
+ ).T # Transpose allows use to use sitk indexing
131
+
132
+ if mask.ndim == 4:
133
+ mask = mask[:, :, :, 0]
134
+
135
+ cm_index = ndimage.center_of_mass(mask)
136
+
137
+ cm = mask_image.TransformContinuousIndexToPhysicalPoint(cm_index)
138
+
139
+ return np.array(cm)
140
+
141
+ def resample_on_new_ct(self, new_ct: CT) -> Self:
142
+ """
143
+ Resample the StructureSet on a new CT.
144
+
145
+ Parameters
146
+ ----------
147
+ new_ct : CT
148
+ The new CT to resample the StructureSet on.
149
+
150
+ Returns
151
+ -------
152
+ StructureSet
153
+ The resampled StructureSet.
154
+ """
155
+
156
+ new_model = self.model_dump()
157
+
158
+ if new_model["ct_image"] != new_ct:
159
+ new_model["ct_image"] = new_ct
160
+ new_model["vois"] = [voi.resample_on_new_ct(new_ct) for voi in self.vois]
161
+ return self.model_validate(new_model)
162
+
163
+
164
+ def create_cst(
165
+ cst_data: Union[dict[str, Any], StructureSet, None] = None,
166
+ ct: Union[CT, dict, None] = None,
167
+ **kwargs,
168
+ ) -> StructureSet:
169
+ """
170
+ Create a StructureSet from various input types.
171
+
172
+ Parameters
173
+ ----------
174
+ cst_data : Union[dict[str, Any], StructureSet, None] , optional
175
+ The input data to create the CT object from. Can be a dictionary,
176
+ existing CT object, file path, or None.
177
+
178
+ ct : Union[CT,dict,None], CT, None], optional
179
+ The input data to create the CT object from. Can be a dictionary,
180
+ existing CT object, or None.
181
+
182
+ **kwargs
183
+ Additional keyword arguments to create the CT object.
184
+
185
+ Returns
186
+ -------
187
+ cst
188
+ A StructureSet object created from the input data or keyword arguments.
189
+ """
190
+
191
+ # Check if already a valid model
192
+ if isinstance(cst_data, StructureSet):
193
+ if ct is not None and cst_data.ct_image != ct:
194
+ raise ValueError("CT image mismatch between StructureSet and provided CT")
195
+ return cst_data
196
+
197
+ # validate ct if present
198
+ if ct is not None:
199
+ ct = validate_ct(ct)
200
+
201
+ # If already a model dictionary check the ct setup
202
+ if isinstance(cst_data, dict):
203
+ ct_image = cst_data.pop("ct_image", cst_data.pop("ctImage", None))
204
+ if ct_image is not None:
205
+ cst_data["ct_image"] = ct_image
206
+ if ct is not None and ct != ct_image:
207
+ raise ValueError("CT image mismatch between StructureSet and provided CT")
208
+ elif ct is not None:
209
+ cst_data["ct_image"] = ct
210
+ else:
211
+ raise ValueError("No CT image reference provided!")
212
+ return StructureSet.model_validate(cst_data)
213
+
214
+ if cst_data is None and ct is not None: # If data is None
215
+ return StructureSet(ct_image=ct, **kwargs)
216
+ elif cst_data is None and ct is None:
217
+ return StructureSet(**kwargs)
218
+
219
+ # Other methods need the CT
220
+ if ct is None:
221
+ raise ValueError("No CT image reference provided!")
222
+
223
+ # Creation from an nd array (cell array matRad format)
224
+ if isinstance(cst_data, np.ndarray) and cst_data.dtype == object:
225
+ cst_data = cst_data.to_list()
226
+
227
+ # a list of volume information (e.g. imported from pymatreader from matRad mat file)
228
+ if isinstance(cst_data, list):
229
+ voi_list = []
230
+ for vdata in cst_data:
231
+ # First try to read the index lists
232
+ idx_list = []
233
+ # Only one scenario (3D CT)
234
+ if not isinstance(vdata[3], list):
235
+ idx_list.append(vdata[3].astype(int).tolist())
236
+ # Multiple scenarios (4D CT)
237
+ else:
238
+ for vdata_scen in vdata[3]:
239
+ idx_list.append(vdata_scen.astype(int).tolist())
240
+
241
+ # Now we create isimple ITK masks
242
+ masks = []
243
+ for idx in idx_list:
244
+ # TODO: Check index ordering
245
+ tmp_mask = sitk.GetArrayViewFromImage(ct.cube_hu).astype(np.uint8)
246
+ tmp_mask.fill(0)
247
+ tmp_mask[np.unravel_index(np.asarray(idx) - 1, tmp_mask.shape, order="C")] = 1
248
+ tmp_mask = np.swapaxes(tmp_mask, 1, 2)
249
+ mask_image = sitk.GetImageFromArray(tmp_mask)
250
+ mask_image.CopyInformation(ct.cube_hu)
251
+
252
+ masks.append(mask_image)
253
+
254
+ # For 4D, we need to join the masks. We also check here if the number of masks we could
255
+ # extract matches the number of dimensions in the CT image
256
+ if ct.cube_hu.GetDimension() == 4:
257
+ # First check if the mask is the same for all 4D scenarios
258
+ if len(masks) == 1:
259
+ masks = [masks[0] for _ in range(ct.cube_hu.GetDimension())]
260
+
261
+ # Now do a sanity check that we don't have an incompatible number of masks
262
+ if len(masks) != ct.cube_hu.GetSize()[3]:
263
+ raise ValueError("Incompatible number of masks for 4D CT")
264
+
265
+ masks = sitk.JoinSeries(*masks)
266
+
267
+ # If it is a 3D CT, we just drop the list
268
+ elif ct.cube_hu.GetDimension() == 3:
269
+ masks = masks[0]
270
+ else:
271
+ raise ValueError("Sanity Check failed -- unsupported CT dimensionality")
272
+
273
+ voi = validate_voi(name=str(vdata[1]), voi_type=str(vdata[2]), mask=masks, ct_image=ct)
274
+
275
+ voi_list.append(voi)
276
+
277
+ cst_dict = {"vois": voi_list, "ct_image": ct}
278
+ return StructureSet.model_validate(cst_dict)
279
+
280
+
281
+ def validate_cst(
282
+ cst_data: Union[dict[str, Any], StructureSet, None] = None,
283
+ ct: Union[CT, dict, None] = None,
284
+ **kwargs,
285
+ ) -> StructureSet:
286
+ """
287
+ Validate StructureSet.
288
+
289
+ Parameters
290
+ ----------
291
+ cst_data : Union[dict[str, Any], StructureSet, None] , optional
292
+ The input data to create the CT object from. Can be a dictionary,
293
+ existing CT object, file path, or None.
294
+
295
+ ct : Union[CT,dict,None], CT, None], optional
296
+ The input data to create the CT object from. Can be a dictionary,
297
+ existing CT object, or None.
298
+
299
+ **kwargs
300
+ Additional keyword arguments to create the CT object.
301
+
302
+ Returns
303
+ -------
304
+ cst
305
+ A StructureSet object created from the input data or keyword arguments.
306
+ """
307
+ return create_cst(cst_data, ct, **kwargs)