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
@@ -0,0 +1,591 @@
1
+ """Base class for all dose engines."""
2
+ from importlib import resources
3
+ import logging
4
+ import warnings
5
+ from typing import ClassVar, Union
6
+ from abc import ABC, abstractmethod
7
+
8
+ import SimpleITK as sitk
9
+ import numpy as np
10
+
11
+ from pyRadPlan.core import Grid
12
+ from pyRadPlan.core.np2sitk import linear_indices_to_grid_coordinates
13
+ from pyRadPlan.core.resample import resample_numpy_array
14
+ from pyRadPlan.ct import CT, resample_ct
15
+ from pyRadPlan.cst import StructureSet
16
+ from pyRadPlan.stf import SteeringInformation
17
+ from pyRadPlan.plan import Plan
18
+ from pyRadPlan.dij import Dij, validate_dij
19
+ from pyRadPlan.scenarios import create_scenario_model, ScenarioModel
20
+ from pyRadPlan.machines import load_machine_from_mat, validate_machine
21
+
22
+ logger = logging.getLogger(__name__)
23
+
24
+ # from dose.calcDoseInit import init_dose_calc
25
+
26
+
27
+ class DoseEngineBase(ABC):
28
+ """
29
+ Abstract base class for all dose engines. All dose engines should
30
+ inherit from this class.
31
+
32
+ Parameters
33
+ ----------
34
+ pln : Plan
35
+ The Plan object to assign properties from.
36
+
37
+ Attributes
38
+ ----------
39
+ short_name : str
40
+ The short name of the dose engine.
41
+ name : str
42
+ The name of the dose engine.
43
+ possible_radiation_modes : list[str]
44
+ The possible radiation modes for the dose engine.
45
+ is_dose_engine : bool = True
46
+ Helper class variable telling you that this is a dose engine
47
+ select_voxels_in_scenarios : bool
48
+ Whether to select voxels in scenarios.
49
+ mult_scen : Union[str, ScenarioModel]
50
+ The scenario model.
51
+ bio_model : Union[str, dict]
52
+ The biological model.
53
+ dose_grid : Union[Grid,dict]
54
+ The dose grid to use (struct with at least doseGrid.resolution.x/y/z set).
55
+ """
56
+
57
+ # Constant, Abstract properties
58
+ short_name: ClassVar[str]
59
+ name: ClassVar[str]
60
+ possible_radiation_modes: ClassVar[list[str]] = NotImplemented
61
+ is_dose_engine: ClassVar[bool] = True # Helper variable
62
+
63
+ mult_scen: Union[str, ScenarioModel]
64
+ bio_model: Union[str, dict]
65
+ dose_grid: Union[Grid, dict]
66
+
67
+ select_voxels_in_scenarios: bool
68
+
69
+ # Public properties
70
+ def __init__(self, pln: Plan):
71
+
72
+ # Assign default parameters from Matrad_Config or manually
73
+ self.dose_grid = None
74
+ self.mult_scen = "nomScen"
75
+ self.select_voxels_in_scenarios = None
76
+ self.dose_grid = None
77
+
78
+ if pln is not None:
79
+ self.assign_properties_from_pln(pln, True)
80
+
81
+ self.dose_grid = None
82
+ self.voxel_sub_ix = None # selection of where to calculate / store dose, empty by default
83
+ self._dose_grid = None
84
+ self._ct_grid = None
85
+
86
+ # Protected properties with public get access
87
+ self._machine = None # base data defined in machine file
88
+ self._timers = None # timers of dose calc
89
+ self._num_of_columns_dij = None # number of columns in the dij struct
90
+ self._vox_world_coords = None # ct voxel coordinates in world
91
+ self._vox_world_coords_dose_grid = None # dose grid voxel coordinates in world
92
+ self._vct_grid = None # voxel grid inside patient
93
+ self._vdose_grid = None # voxel dose grid
94
+ self._vct_grid_scen_ix = None # logical subindexes of scenarios in ct grid
95
+ self._vdose_grid_scen_ix = None # logical subindexes of scenarios in dose grid
96
+ self._vct_grid_mask = None # voxel grid inside patient as logical mask
97
+ self._vdose_grid_mask = None # voxel dose grid inside patient as logical mask
98
+ self._robust_voxels_on_grid = None # voxels to be computed in robustness scenarios
99
+
100
+ # Protected properties with private get access
101
+ self._last_progress_update = None
102
+ self._calc_dose_direct = False
103
+
104
+ # initializing super() class (here: ABC)
105
+ super().__init__()
106
+
107
+ # Public methods
108
+ def assign_properties_from_pln(self, pln: Plan, warn_when_property_changed: bool = False):
109
+ """
110
+ Assign properties from a Plan object to the Dose Engine.
111
+ This includes the Scenario Model and the Biological Model, and any
112
+ other properties that
113
+ can be stored in the prop_dose_calc dictionary within the Plan object.
114
+ This function will check if a property exists for the dose engine and,
115
+ if yes, set it.
116
+
117
+ Parameters
118
+ ----------
119
+ pln : Plan
120
+ The Plan object to assign properties from.
121
+ warn_when_property_changed : bool
122
+ Whether to warn when properties are changed.
123
+ """
124
+
125
+ # Set Scenario Model
126
+ if hasattr(pln, "mult_scen"):
127
+ self.mult_scen = pln.mult_scen
128
+
129
+ # Assign Biologival Model
130
+ if hasattr(pln, "bio_param"):
131
+ self.bio_param = pln.bio_param # TODO: No bio_param yet
132
+
133
+ if not isinstance(warn_when_property_changed, bool):
134
+ warn_when_property_changed = False
135
+
136
+ # Overwrite default properties within the engine
137
+ # with the ones given in the prop_dose_calc dict
138
+ if hasattr(pln, "prop_dose_calc") and isinstance(
139
+ pln.prop_dose_calc, dict
140
+ ): # TODO: This is not tested yet
141
+ prop_dict = pln.prop_dose_calc
142
+ if (
143
+ "engine" in prop_dict
144
+ and prop_dict["engine"]
145
+ and prop_dict["engine"] != self.short_name
146
+ ):
147
+ raise ValueError(
148
+ f"Inconsistent dose engines given! pln asks for '{prop_dict['engine']}', "
149
+ f"but you are using '{self.short_name}'!"
150
+ )
151
+ prop_dict.pop("engine", None)
152
+ else:
153
+ prop_dict = {}
154
+
155
+ fields = prop_dict.keys()
156
+
157
+ # Set up warning message
158
+ if warn_when_property_changed:
159
+ warning_msg = "Property in Dose Engine overwritten from pln.propDoseCalc"
160
+ else:
161
+ warning_msg = None
162
+
163
+ for field in fields:
164
+ if not hasattr(self, field):
165
+ warnings.warn('Property "{}" not found in Dose Engine!'.format(field))
166
+ else:
167
+ if warn_when_property_changed and warning_msg:
168
+ logger.warning(warning_msg + f": {field}")
169
+
170
+ setattr(self, field, prop_dict[field])
171
+
172
+ def calc_dose_forward(
173
+ self, ct: CT, cst: StructureSet, stf: SteeringInformation, w: np.ndarray
174
+ ):
175
+ """
176
+ Perform a forward dose calculation, i.e., compute a dose cube by
177
+ directly applying
178
+ a set of weights during dose calculation.
179
+
180
+ Parameters
181
+ ----------
182
+ ct : CT
183
+ The CT scan data.
184
+ cst : StructureSet
185
+ The structure set containing volumes of interest (VOIs).
186
+ stf : SteeringInformation
187
+ The steering information containing beam configurations.
188
+ w : np.ndarray
189
+ The weights to apply during dose calculation.
190
+
191
+ Returns
192
+ -------
193
+ Dij
194
+ The dose information
195
+
196
+ Notes
197
+ -----
198
+ pyRadPlan handles the forward dose calculation by setting a switch in the dose engine
199
+ (_calc_dose_direct) to True. This facilitates reusing of algorithms in both forward and
200
+ influence matrix calculations.
201
+ """
202
+
203
+ raise NotImplementedError("This method is not implemented yet!")
204
+ self._calc_dose_direct = True
205
+ dij = self._calc_dose(ct, cst, stf)
206
+
207
+ # TODO: now do the forward weighting with w
208
+
209
+ return dij
210
+
211
+ def calc_dose_influence(self, ct: CT, cst: StructureSet, stf: SteeringInformation) -> Dij:
212
+ """
213
+ Calculate the set of dose/quantity influence matrices, i.e.,
214
+ matrices that map a fluence
215
+ vector to a dose/quantity distribution.
216
+
217
+ Parameters
218
+ ----------
219
+ ct : CT
220
+ The CT scan data.
221
+ cst : StructureSet
222
+ The structure set containing volumes of interest (VOIs).
223
+ stf : SteeringInformation
224
+ The steering information containing beam configurations.
225
+
226
+ Returns
227
+ -------
228
+ Dij
229
+ The dose influence matrix collection
230
+
231
+ Notes
232
+ -----
233
+ pyRadPlan handles the influence matrix calculation by setting a switch in the dose engine
234
+ (_calc_dose_direct) to False. This facilitates reusing of algorithms in both forward and
235
+ influence matrix calculations.
236
+ """
237
+
238
+ self._calc_dose_direct = False
239
+ dij = self._calc_dose(ct, cst, stf)
240
+
241
+ return dij
242
+
243
+ def set_overlap_priorities(self, cst: StructureSet, ct_dim=None) -> StructureSet:
244
+ """Set overlap priorities for the structures in the CST."""
245
+
246
+ logger.info("Adjusting structures for overlap... ")
247
+
248
+ num_of_ct_scenarios = np.unique([x.num_of_scenarios for x in cst.vois])
249
+
250
+ # Sanity check
251
+ if len(num_of_ct_scenarios) > 1:
252
+ raise ValueError("Inconsistent number of scenarios in cst struct.")
253
+
254
+ # TODO: This is not yet implemented
255
+ # for i in range(num_of_ct_scenarios[0]):
256
+ # # consider VOI priorities
257
+ # for j in range(len(cst.vois)):
258
+ # idx = cst.vois[j].indices[i]
259
+
260
+ # for k in range(len(cst.vois)):
261
+ # pass
262
+
263
+ return cst
264
+
265
+ def select_voxels_from_cst(self, cst, dose_grid, selection_mode):
266
+ """
267
+ Function to get mask of the voxels (on dose grid) that are included
268
+ in
269
+ cst structures specified by selection_mode.
270
+ """
271
+ self.set_overlap_priorities(self, cst, dose_grid["dimensions"])
272
+
273
+ selected_cst_structs = []
274
+
275
+ include_mask = [
276
+ np.zeros(np.prod(dose_grid["dimensions"]), dtype=bool) for _ in range(len(cst[:, 4]))
277
+ ]
278
+
279
+ if selection_mode == "all":
280
+ for ct_scen_idx in range(len(include_mask)):
281
+ include_mask[ct_scen_idx][:] = True
282
+ else:
283
+ if isinstance(selection_mode, str):
284
+ if selection_mode == "targetOnly":
285
+ selected_cst_structs = [i for i, x in enumerate(cst[:, 2]) if x == "TARGET"]
286
+ elif selection_mode == "objectivesOnly":
287
+ for i in range(len(cst)):
288
+ if len(cst[i, 5]) > 0:
289
+ selected_cst_structs.append(i)
290
+ elif selection_mode == "oarsOnly":
291
+ selected_cst_structs = [i for i, x in enumerate(cst[:, 2]) if x == "OAR"]
292
+ elif selection_mode == "robustnessOnly":
293
+ for i in range(len(cst)):
294
+ for j in range(len(cst[i, 5])):
295
+ if (
296
+ "robustness" in cst[i, 5][j]
297
+ and cst[i, 5][j]["robustness"] != "none"
298
+ ):
299
+ selected_cst_structs.append(i)
300
+ else:
301
+ raise ValueError(f"Unrecognized voxel selection mode: {selection_mode}")
302
+ elif isinstance(selection_mode, (list, np.ndarray)):
303
+ selected_cst_structs = np.unique(
304
+ np.intersect1d(selection_mode, np.arange(len(cst)) + 1)
305
+ )
306
+ if not np.array_equal(selected_cst_structs, np.unique(selection_mode)):
307
+ warnings.warn(
308
+ "Specified structures are not compatible with cst structures. "
309
+ f"Only performing calculation on structures: {selected_cst_structs}"
310
+ )
311
+
312
+ # Loop over all cst structures
313
+ for i in range(len(cst)):
314
+ if len(cst[i, 4][0]) > 0:
315
+ if len(cst[i, 5]) > 0:
316
+ # Loop over obj/constraint functions
317
+ for j in range(len(cst[i, 5])):
318
+ obj = cst[i, 5][j]
319
+
320
+ if not isinstance(obj, dict):
321
+ try:
322
+ pass
323
+ # TODO: obj = matRad_DoseOptimizationFunction.
324
+ # createInstanceFromStruct(obj)
325
+ except ValueError:
326
+ logger.error(
327
+ f"cst[{i},5][{j}] is not a valid Objective/constraint! "
328
+ "Remove or Replace and try again!"
329
+ )
330
+
331
+ robustness = obj.get("robustness", "none")
332
+
333
+ if i in selected_cst_structs:
334
+ for ct_idx in range(len(cst[i, 4])):
335
+ include_mask[ct_idx][cst[i, 4][ct_idx]] = 1
336
+
337
+ if robustness == "none":
338
+ logger.info(
339
+ f"Including cst structure {cst[i, 1]} even though this "
340
+ "structure has no robustness."
341
+ )
342
+ else:
343
+ logger.info(
344
+ f"Excluding cst structure {cst[i, 1]} even though this "
345
+ "structure has an objective or constraint."
346
+ )
347
+
348
+ if robustness != "none":
349
+ logger.info(
350
+ f"Excluding cst structure {cst[i, 1]} even though this "
351
+ "structure has robustness."
352
+ )
353
+ else:
354
+ if i in selected_cst_structs:
355
+ logger.info(
356
+ f"Including cst structure {cst[i, 1]} even though this structure "
357
+ "does not have any objective or constraint"
358
+ )
359
+
360
+ return include_mask
361
+
362
+ def resize_cst_to_grid(self, cst: StructureSet, dij, new_ct: CT) -> StructureSet:
363
+
364
+ """Resize the CST to the dose cube resolution."""
365
+
366
+ logger.info("Resampling structure set... ")
367
+
368
+ cst.resample_on_new_ct(new_ct)
369
+
370
+ logger.info("Done!")
371
+ return cst
372
+
373
+ # private methods
374
+ def _init_dose_calc(self, ct: CT, cst: StructureSet, stf: SteeringInformation) -> dict:
375
+ """
376
+ Initializes the dose calculation process for a given CT scan,
377
+ structure
378
+ set, and steering information.
379
+
380
+ Parameters
381
+ ----------
382
+ self : DoseEngineBase
383
+ The instance of the dose engine.
384
+ ct : CT
385
+ The CT scan data.
386
+ cst : StructureSet
387
+ The structure set containing volumes of interest (VOIs).
388
+ stf : SteeringInformation
389
+ The steering information containing beam configurations.
390
+
391
+ Returns
392
+ -------
393
+ dict
394
+ A dictionary containing the dose influence matrix (dij) and related information.
395
+
396
+ Description
397
+ -----------
398
+ This method sets up the necessary grids and parameters for dose calculation. It initializes
399
+ the CT and dose grids, checks machine and radiation mode consistency, creates a scenario
400
+ model, and sets up arrays for bookkeeping. It also adjusts the isocenter internally for
401
+ different dose grids and converts CT subscripts to world coordinates. Additionally, it
402
+ loads the machine file from the base data folder and performs voxel selection for dose
403
+ calculation.
404
+ """
405
+
406
+ self._ct_grid = Grid.from_sitk_image(ct.cube_hu)
407
+
408
+ dij = {}
409
+
410
+ # Default: dose influence matrix computation
411
+ # TODO: Not sure whether this if statement works as intended
412
+ if not hasattr(self, "_calc_dose_direct"):
413
+ self._calc_dose_direct = False
414
+ if self._calc_dose_direct:
415
+ logger.info("Forward dose calculation using '%s' Dose Engine...", self.name)
416
+ else:
417
+ logger.info("Dose influence matrix calculation using '%s' Dose Engine...", self.name)
418
+
419
+ # Check if machine and radiation_mode are consistent
420
+ machine = list(set(beam.machine for beam in stf.beams))
421
+ radiation_mode = list(set(beam.radiation_mode for beam in stf.beams))
422
+
423
+ assert (
424
+ len(machine) == 1 or len(radiation_mode) == 1
425
+ ), "machine and radiation mode need to be unique within supplied stf!"
426
+
427
+ machine = machine[0]
428
+ radiation_mode = radiation_mode[0]
429
+
430
+ # ScenarioModel
431
+ if not isinstance(self.mult_scen, ScenarioModel):
432
+ self.mult_scen = create_scenario_model(self.mult_scen, ct)
433
+
434
+ # TODO: Add BioModel Support
435
+ # if not np.isnan(self.bio_param["RBE"]):
436
+ # dij['RBE'] = self.bio_param['RBE']
437
+
438
+ # store CT grid
439
+ dij["ct_grid"] = ct.grid
440
+
441
+ if self.dose_grid is None:
442
+ self.dose_grid = ct.grid.resample({"x": 5.0, "y": 5.0, "z": 5.0})
443
+
444
+ if not isinstance(self.dose_grid, Grid):
445
+ self.dose_grid = Grid.model_validate(self.dose_grid)
446
+
447
+ dij["dose_grid"] = self.dose_grid
448
+
449
+ # Meta information for dij #TODO: Change dij Model in future
450
+ dij["num_of_beams"] = len(stf.beams)
451
+ dij["num_of_scenarios"] = 1 # TODO: Add support for multiple scenarios
452
+ dij["num_of_rays_per_beam"] = [stf.beams[i].num_of_rays for i in range(len(stf.beams))]
453
+ dij["total_num_of_bixels"] = int(
454
+ sum([stf.beams[i].total_number_of_bixels for i in range(len(stf.beams))])
455
+ )
456
+ dij["total_num_of_rays"] = int(sum(dij["num_of_rays_per_beam"]))
457
+
458
+ # Check if full dose influence data is required
459
+ if self._calc_dose_direct:
460
+ self._num_of_columns_dij = len(stf.beams)
461
+
462
+ else:
463
+ self._num_of_columns_dij = dij["total_num_of_bixels"]
464
+
465
+ # Set up arrays for book keeping
466
+ dij["bixel_num"] = np.nan * np.ones(self._num_of_columns_dij)
467
+ dij["ray_num"] = np.nan * np.ones(self._num_of_columns_dij)
468
+ dij["beam_num"] = np.nan * np.ones(self._num_of_columns_dij)
469
+
470
+ # Default MU calibration
471
+ dij["min_mu"] = np.zeros(self._num_of_columns_dij)
472
+ dij["max_mu"] = np.ones(self._num_of_columns_dij) * np.inf
473
+ dij["num_of_particles_per_mu"] = np.ones(self._num_of_columns_dij) * 1e6
474
+
475
+ if not hasattr(self, "voxel_sub_ix") or self.voxel_sub_ix is None:
476
+ # take only voxels inside patient
477
+ tmp_vct_grid_scen = [None] * ct.num_of_ct_scen
478
+
479
+ for s in range(ct.num_of_ct_scen):
480
+ tmp_scen = [cst.vois[c].indices_numpy for c in range(0, len(cst.vois))]
481
+ tmp_vct_grid_scen[s] = np.unique(np.concatenate(tmp_scen))
482
+
483
+ else: # TODO: this "else" has not yet been tested
484
+ if isinstance(self.voxel_sub_ix, list):
485
+ tmp_vct_grid_scen = [None] * ct.num_of_ct_scen
486
+
487
+ for s in range(ct.num_of_ct_scen):
488
+ tmp_vct_grid_scen[s] = self.voxel_sub_ix
489
+
490
+ else:
491
+ tmp_vct_grid_scen = self.voxel_sub_ix
492
+
493
+ self._vct_grid = np.unique(np.concatenate(tmp_vct_grid_scen))
494
+
495
+ # Find subindexes for the individual scenarios. This helps with subselection later.
496
+ self._vct_grid_scen_ix = [np.isin(self._vct_grid, c) for c in tmp_vct_grid_scen]
497
+
498
+ # Initialize tmp_vdose_grid_scen
499
+ tmp_vdose_grid_scen = [None] * ct.num_of_ct_scen
500
+
501
+ if self._ct_grid == self._dose_grid:
502
+ self._dose_grid = self._ct_grid
503
+ resampled_ct = ct
504
+ else:
505
+ resampled_ct = resample_ct(
506
+ ct=ct,
507
+ interpolator=sitk.sitkNearestNeighbor,
508
+ target_grid=self.dose_grid,
509
+ )
510
+ self._dose_grid = Grid.from_sitk_image(resampled_ct.cube_hu)
511
+ for s in range(ct.num_of_ct_scen):
512
+ # Receive linear indices and grid locations from the dose grid
513
+ tmp_cube = np.zeros(ct.cube_dim[::-1], dtype=np.float32)
514
+ tmp_cube.ravel()[tmp_vct_grid_scen[s]] = 1
515
+
516
+ interpolated_tmp_cube = resample_numpy_array(
517
+ tmp_cube,
518
+ reference_image=ct.cube_hu,
519
+ interpolator=sitk.sitkNearestNeighbor,
520
+ target_image=resampled_ct.cube_hu,
521
+ )
522
+
523
+ tmp_vdose_grid_scen[s] = np.where(
524
+ np.abs(np.round(interpolated_tmp_cube)).ravel().astype(bool)
525
+ )
526
+
527
+ # Get unique dose grid
528
+ self._vdose_grid = np.unique(np.concatenate(tmp_vdose_grid_scen, axis=0))
529
+
530
+ # Find subindexes for the dose grid scenarios
531
+ self._vdose_grid_scen_ix = [np.isin(self._vdose_grid, c) for c in tmp_vdose_grid_scen]
532
+
533
+ # Convert CT subscripts to world coordinates.
534
+ self._vox_world_coords = linear_indices_to_grid_coordinates(
535
+ self._vct_grid, self._ct_grid, index_type="numpy"
536
+ )
537
+
538
+ self._vox_world_coords_dose_grid = linear_indices_to_grid_coordinates(
539
+ self._vdose_grid, self._dose_grid, index_type="numpy"
540
+ )
541
+
542
+ # Create helper masks
543
+ self._vdose_grid_mask = np.zeros(self.dose_grid.num_voxels, dtype=bool)
544
+ self._vdose_grid_mask[self._vdose_grid] = True
545
+
546
+ self._vct_grid_mask = np.zeros(np.prod(ct.cube_dim), dtype=bool)
547
+ self._vct_grid_mask[self._vct_grid] = True
548
+
549
+ # Load machine file from base data folder
550
+ self._machine = self.load_machine(radiation_mode, machine)
551
+
552
+ # Voxel selection for dose calculation
553
+ # TODO: set overlap priorites - Skips most of the function
554
+ cst = self.set_overlap_priorities(cst, ct_dim=None)
555
+
556
+ # resizing cst to dose cube resolution
557
+ cst = self.resize_cst_to_grid(cst, dij, resampled_ct)
558
+
559
+ # TODO: this function has not yet been implemented
560
+ # structures that are selected here will be included in dose calculation over
561
+ # the robust scenarios
562
+ # self._robust_voxels_on_grid = select_voxels_from_cst(cst, dij["ct_grid"])
563
+
564
+ return dij
565
+
566
+ def _finalize_dose(self, dij: dict) -> Dij:
567
+ return validate_dij(dij)
568
+
569
+ def _progress_update(self, pos, total):
570
+ raise NotImplementedError
571
+
572
+ # Private and abstract methods
573
+
574
+ @abstractmethod
575
+ def _calc_dose(self, ct: CT, cst: StructureSet, stf: SteeringInformation) -> Dij:
576
+ raise NotImplementedError("Method '_calc_dose' must be implemented.")
577
+
578
+ # static methods
579
+ @staticmethod
580
+ def is_available(pln, machine):
581
+ available, msg = [], []
582
+ return available, msg
583
+
584
+ @staticmethod
585
+ def load_machine(radiation_mode, machine_name):
586
+ fileName = radiation_mode + "_" + machine_name + ".mat"
587
+ machines_path = resources.files("pyRadPlan.data.machines")
588
+ path = machines_path.joinpath(fileName)
589
+ machine = load_machine_from_mat(path)
590
+ machine = validate_machine(machine)
591
+ return machine