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
|
@@ -0,0 +1,806 @@
|
|
|
1
|
+
"""Base class for pencil beam dose calculation algorithms."""
|
|
2
|
+
from abc import abstractmethod
|
|
3
|
+
from typing import cast, Any, Literal
|
|
4
|
+
import warnings
|
|
5
|
+
import logging
|
|
6
|
+
import time
|
|
7
|
+
from tqdm import tqdm
|
|
8
|
+
from tqdm.contrib.logging import logging_redirect_tqdm
|
|
9
|
+
|
|
10
|
+
import SimpleITK as sitk
|
|
11
|
+
import numpy as np
|
|
12
|
+
from scipy import sparse
|
|
13
|
+
|
|
14
|
+
from pyRadPlan.core import resample_image, np2sitk
|
|
15
|
+
from pyRadPlan.ct import CT, default_hlut
|
|
16
|
+
from pyRadPlan.cst import StructureSet
|
|
17
|
+
from pyRadPlan.stf import SteeringInformation
|
|
18
|
+
from pyRadPlan.geometry import get_beam_rotation_matrix
|
|
19
|
+
from pyRadPlan.raytracer import RayTracerSiddon
|
|
20
|
+
|
|
21
|
+
from ._base import DoseEngineBase
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
logger = logging.getLogger(__name__)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class PencilBeamEngineAbstract(DoseEngineBase):
|
|
28
|
+
"""
|
|
29
|
+
An abstract class representing the Pencil Beam Engine.
|
|
30
|
+
|
|
31
|
+
This class extends DoseEngineBase and provides the foundational structure for implementing a
|
|
32
|
+
pencil beam dose calculation engine. It includes methods for initializing dose calculations,
|
|
33
|
+
setting defaults, and various helper methods required for the dose calculation process.
|
|
34
|
+
|
|
35
|
+
Attributes
|
|
36
|
+
----------
|
|
37
|
+
keep_rad_depth_cubes : bool
|
|
38
|
+
Flag to keep radiation depth cubes.
|
|
39
|
+
geometric_lateral_cutoff : float
|
|
40
|
+
Lateral geometric cut-off in mm, used for raytracing and geometry.
|
|
41
|
+
dosimetric_lateral_cutoff : float
|
|
42
|
+
Relative dosimetric cut-off (in fraction of values calculated).
|
|
43
|
+
ssd_density_threshold : float
|
|
44
|
+
Threshold for SSD computation.
|
|
45
|
+
use_given_eq_density_cube : bool
|
|
46
|
+
Use the given density cube ct.cube and omit conversion from cubeHU.
|
|
47
|
+
ignore_outside_densities : bool
|
|
48
|
+
Ignore densities outside of cst contours.
|
|
49
|
+
num_of_dij_fill_steps : int
|
|
50
|
+
Number of times during dose calculation the temporary containers are moved to a sparse
|
|
51
|
+
matrix.
|
|
52
|
+
cube_wed : sitk.Image
|
|
53
|
+
Relative electron density / stopping power cube.
|
|
54
|
+
hlut : np.ndarray
|
|
55
|
+
Hounsfield lookup table to create relative electron density cube.
|
|
56
|
+
|
|
57
|
+
Methods
|
|
58
|
+
-------
|
|
59
|
+
__init__()
|
|
60
|
+
Initializes the PencilBeamEngineAbstract class.
|
|
61
|
+
set_defaults()
|
|
62
|
+
Sets default values for the attributes.
|
|
63
|
+
_compute_bixel(curr_ray, k)
|
|
64
|
+
Abstract method to compute bixel.
|
|
65
|
+
_calc_dose(ct, cst, stf)
|
|
66
|
+
Calculates the dose.
|
|
67
|
+
_init_dose_calc(ct, cst, stf)
|
|
68
|
+
Initializes dose calculation.
|
|
69
|
+
_allocate_quantity_matrices(dij, names)
|
|
70
|
+
Allocates quantity matrix containers.
|
|
71
|
+
_init_beam(curr_beam, ct, cst, stf, i)
|
|
72
|
+
Initializes the beam.
|
|
73
|
+
_init_ray(curr_beam, j)
|
|
74
|
+
Initializes the ray.
|
|
75
|
+
_extract_single_scenario_ray(ray, scen_idx)
|
|
76
|
+
Extracts a single scenario ray.
|
|
77
|
+
_get_ray_geometry_from_beam(ray, curr_beam)
|
|
78
|
+
Gets ray geometry from beam.
|
|
79
|
+
_get_lateral_distance_from_dose_cutoff_on_ray(ray)
|
|
80
|
+
Gets lateral distance from dose cutoff on ray.
|
|
81
|
+
_fill_dij(bixel, dij, stf, scen_idx, curr_beam_idx, curr_ray_idx, curr_bixel_idx, counter)
|
|
82
|
+
Fills the dose influence matrix (dij).
|
|
83
|
+
_finalize_dose(dij)
|
|
84
|
+
Finalizes the dose.
|
|
85
|
+
calcGeoDists(rot_coords_bev, sourcePoint_bev, targetPoint_bev, SAD, radDepthIx, lateralCutOff)
|
|
86
|
+
Calculates geometric distances.
|
|
87
|
+
geometric_cutoff()
|
|
88
|
+
Property for geometric cutoff.
|
|
89
|
+
warn_deprecated_engine_property(old_name, new_name, internal_name)
|
|
90
|
+
Warns about deprecated engine properties.
|
|
91
|
+
"""
|
|
92
|
+
|
|
93
|
+
keep_rad_depth_cubes: bool
|
|
94
|
+
geometric_lateral_cutoff: float
|
|
95
|
+
dosimetric_lateral_cutoff: float
|
|
96
|
+
ssd_density_threshold: float
|
|
97
|
+
use_given_eq_density_cube: bool
|
|
98
|
+
ignore_outside_densities: bool
|
|
99
|
+
cube_wed: sitk.Image
|
|
100
|
+
hlut: np.ndarray
|
|
101
|
+
|
|
102
|
+
def __init__(self, pln):
|
|
103
|
+
self.keep_rad_depth_cubes = False
|
|
104
|
+
self.geometric_lateral_cutoff: float = 50
|
|
105
|
+
self.dosimetric_lateral_cutoff: float = 0.9950
|
|
106
|
+
self.ssd_density_threshold: float = 0.0500
|
|
107
|
+
self.use_given_eq_density_cube: bool = False
|
|
108
|
+
self.ignore_outside_densities: bool = True
|
|
109
|
+
self.cube_wed = None
|
|
110
|
+
self.hlut = None
|
|
111
|
+
|
|
112
|
+
self._computed_quantities = []
|
|
113
|
+
self._effective_lateral_cutoff = None
|
|
114
|
+
self._num_of_bixels_container = None
|
|
115
|
+
self._rad_depth_cubes = []
|
|
116
|
+
|
|
117
|
+
super().__init__(pln)
|
|
118
|
+
|
|
119
|
+
@abstractmethod
|
|
120
|
+
def _compute_bixel(self, curr_ray, k):
|
|
121
|
+
raise NotImplementedError("Method _compute_bixel must be implemented in derived class.")
|
|
122
|
+
|
|
123
|
+
def _calc_dose(self, ct: CT, cst: StructureSet, stf: SteeringInformation):
|
|
124
|
+
"""
|
|
125
|
+
Calculate the dose using the pencil beam method.
|
|
126
|
+
|
|
127
|
+
Parameters
|
|
128
|
+
----------
|
|
129
|
+
ct : CT
|
|
130
|
+
The CT object.
|
|
131
|
+
cst : StructureSet
|
|
132
|
+
The structure set object.
|
|
133
|
+
stf : SteeringInformation
|
|
134
|
+
The steering information object.
|
|
135
|
+
|
|
136
|
+
Returns
|
|
137
|
+
-------
|
|
138
|
+
dict
|
|
139
|
+
The dose influence matrix dictionary.
|
|
140
|
+
"""
|
|
141
|
+
|
|
142
|
+
# Initialize
|
|
143
|
+
dij = self._init_dose_calc(ct, cst, stf)
|
|
144
|
+
|
|
145
|
+
# We loop over scenario in the scenario model
|
|
146
|
+
# TODO: we need to correctly work out scenarios
|
|
147
|
+
for shift_scen in range(self.mult_scen.tot_num_shift_scen):
|
|
148
|
+
# Find first instance of the shift to select the shift values
|
|
149
|
+
# TODO!: Check for more than one Scenario
|
|
150
|
+
ix_shift_scen = np.where(self.mult_scen.linear_mask[:, 1] == shift_scen)
|
|
151
|
+
|
|
152
|
+
scen_stf = stf
|
|
153
|
+
# Manipulate isocenter
|
|
154
|
+
for beam in scen_stf.beams:
|
|
155
|
+
beam.iso_center += self.mult_scen.iso_shift[ix_shift_scen, :].reshape(-1)
|
|
156
|
+
|
|
157
|
+
if self.mult_scen.tot_num_shift_scen > 1:
|
|
158
|
+
print(f"Shift scenario {shift_scen} of {self.mult_scen.tot_num_shift_scen}: \n")
|
|
159
|
+
|
|
160
|
+
bixel_counter = 0
|
|
161
|
+
|
|
162
|
+
# Loop over all beams
|
|
163
|
+
with logging_redirect_tqdm():
|
|
164
|
+
for i in tqdm(range(dij["num_of_beams"]), desc="Beam", unit="b", leave=False):
|
|
165
|
+
# Initialize Beam Geometry
|
|
166
|
+
curr_beam = self._init_beam(dij, ct, cst, scen_stf, i)
|
|
167
|
+
|
|
168
|
+
# Keep tabs on bixels computed in this beam
|
|
169
|
+
bixel_beam_counter = 0
|
|
170
|
+
|
|
171
|
+
# Ray calculation
|
|
172
|
+
for j in tqdm(
|
|
173
|
+
range(curr_beam["beam"]["num_of_rays"]), desc="Ray", unit="r", leave=False
|
|
174
|
+
):
|
|
175
|
+
# Initialize Ray Geometry
|
|
176
|
+
curr_ray = self._init_ray(curr_beam, j)
|
|
177
|
+
|
|
178
|
+
# TODO: incorporate scenarios correctly
|
|
179
|
+
for ct_scen in range(self.mult_scen.num_of_ct_scen):
|
|
180
|
+
for range_scen in range(self.mult_scen.tot_num_range_scen):
|
|
181
|
+
|
|
182
|
+
# Obtain scenario index
|
|
183
|
+
full_scen_idx = self.mult_scen.sub2scen_ix(
|
|
184
|
+
ct_scen, shift_scen, range_scen
|
|
185
|
+
)
|
|
186
|
+
|
|
187
|
+
if self.mult_scen.scen_mask[full_scen_idx]:
|
|
188
|
+
# Extract single scenario ray
|
|
189
|
+
scen_ray = self._extract_single_scenario_ray(
|
|
190
|
+
curr_ray, full_scen_idx
|
|
191
|
+
)
|
|
192
|
+
|
|
193
|
+
for k in range(curr_ray["num_of_bixels"]):
|
|
194
|
+
# Bixel Computation
|
|
195
|
+
curr_bixel = self._compute_bixel(scen_ray, k)
|
|
196
|
+
|
|
197
|
+
# fill the current bixel in the sparse dose influence
|
|
198
|
+
# matrix
|
|
199
|
+
dij = self._fill_dij(
|
|
200
|
+
curr_bixel,
|
|
201
|
+
dij,
|
|
202
|
+
scen_stf,
|
|
203
|
+
full_scen_idx,
|
|
204
|
+
i,
|
|
205
|
+
j,
|
|
206
|
+
k,
|
|
207
|
+
bixel_counter + k,
|
|
208
|
+
)
|
|
209
|
+
|
|
210
|
+
# Progress Update & Bookkeeping
|
|
211
|
+
bixel_counter += curr_ray["num_of_bixels"]
|
|
212
|
+
bixel_beam_counter += curr_ray["num_of_bixels"]
|
|
213
|
+
|
|
214
|
+
# Finalize dose calculation
|
|
215
|
+
logger.info("Finalizing dose calculation...")
|
|
216
|
+
t_start = time.time()
|
|
217
|
+
dij = self._finalize_dose(dij)
|
|
218
|
+
t_end = time.time()
|
|
219
|
+
logger.info("Done in %f seconds.", t_end - t_start)
|
|
220
|
+
|
|
221
|
+
return dij
|
|
222
|
+
|
|
223
|
+
def _init_dose_calc(self, ct: CT, cst: StructureSet, stf: SteeringInformation):
|
|
224
|
+
"""
|
|
225
|
+
Modified inherited method of the superclass DoseEngine,
|
|
226
|
+
containing initialization which is specifically needed for
|
|
227
|
+
pencil beam calculation and not for other engines.
|
|
228
|
+
"""
|
|
229
|
+
|
|
230
|
+
dij = super()._init_dose_calc(ct, cst, stf)
|
|
231
|
+
|
|
232
|
+
# calculate rED or rSP from HU or take provided wedCube
|
|
233
|
+
if self.use_given_eq_density_cube and not hasattr(ct, "cube_hu"):
|
|
234
|
+
logging.warning(
|
|
235
|
+
"HU Conversion requested to be omitted but no ct.cube exists! "
|
|
236
|
+
"Will override and do the conversion anyway!"
|
|
237
|
+
)
|
|
238
|
+
self.use_given_eq_density_cube = False
|
|
239
|
+
|
|
240
|
+
if self.use_given_eq_density_cube:
|
|
241
|
+
ct_wed = ct.cube_hu
|
|
242
|
+
logging.info("Omitting HU to rED/rSP conversion and using existing ct.cube!\n")
|
|
243
|
+
else:
|
|
244
|
+
# TODO: obtain correct hlut
|
|
245
|
+
if self.hlut is None:
|
|
246
|
+
self.hlut = default_hlut()
|
|
247
|
+
ct_wed = ct.compute_wet(self.hlut)
|
|
248
|
+
|
|
249
|
+
self.cube_wed = ct_wed
|
|
250
|
+
|
|
251
|
+
# Ignore densities outside of contours
|
|
252
|
+
if self.ignore_outside_densities: # TODO: default = None (not tested yet)
|
|
253
|
+
mask_image = np2sitk.linear_indices_to_sitk_mask(
|
|
254
|
+
self._vct_grid, self.cube_wed, order="numpy"
|
|
255
|
+
)
|
|
256
|
+
|
|
257
|
+
# # TODO: ct does not yet support multi_scen
|
|
258
|
+
# for i in range(ct.num_of_ct_scen):
|
|
259
|
+
# self.cube_wed.ToScalarImage()
|
|
260
|
+
# self.cube_wed[erase_ct_dens_mask == 1] = 0
|
|
261
|
+
|
|
262
|
+
# Apply the mask to the cube_wed image
|
|
263
|
+
self.cube_wed = sitk.Mask(self.cube_wed, mask_image, outsideValue=0)
|
|
264
|
+
|
|
265
|
+
# Allocate memory for quantity containers
|
|
266
|
+
dij = self._allocate_quantity_matrices(dij, ["physical_dose"])
|
|
267
|
+
|
|
268
|
+
return dij
|
|
269
|
+
|
|
270
|
+
def _allocate_quantity_matrices(self, dij: dict[str, Any], names: list[str]):
|
|
271
|
+
|
|
272
|
+
# Loop over all requested quantities
|
|
273
|
+
for q_name in names:
|
|
274
|
+
# Create dij list for each quantity
|
|
275
|
+
dij[q_name] = np.empty(self.mult_scen.scen_mask.shape, dtype=object)
|
|
276
|
+
|
|
277
|
+
# Loop over all scenarios and preallocate quantity containers
|
|
278
|
+
# TODO: write test for this
|
|
279
|
+
for i in range(self.mult_scen.scen_mask.size):
|
|
280
|
+
# Only if there is a scenario we will allocate
|
|
281
|
+
if self.mult_scen.scen_mask.flat[i]:
|
|
282
|
+
if self._calc_dose_direct:
|
|
283
|
+
dij[q_name].flat[i] = np.zeros(
|
|
284
|
+
(self.dose_grid.num_voxels,), dtype=np.float32
|
|
285
|
+
)
|
|
286
|
+
else:
|
|
287
|
+
# This could probably be optimized by using direct access to the
|
|
288
|
+
# lil_matrix's data structures
|
|
289
|
+
# TODO: we could store a single sparse pattern matrix and then only store
|
|
290
|
+
# the values for all quantities for better memory management
|
|
291
|
+
dij[q_name].flat[i] = sparse.lil_matrix(
|
|
292
|
+
(self._num_of_columns_dij, self.dose_grid.num_voxels),
|
|
293
|
+
dtype=np.float32,
|
|
294
|
+
)
|
|
295
|
+
|
|
296
|
+
self._computed_quantities.append(q_name)
|
|
297
|
+
|
|
298
|
+
return dij
|
|
299
|
+
|
|
300
|
+
def _init_beam(
|
|
301
|
+
self, _dij: dict, ct: CT, _cst: StructureSet, stf: SteeringInformation, i
|
|
302
|
+
) -> dict:
|
|
303
|
+
"""
|
|
304
|
+
Method for initializing the beams for analytical pencil beam dose
|
|
305
|
+
calculation.
|
|
306
|
+
|
|
307
|
+
Parameters
|
|
308
|
+
----------
|
|
309
|
+
dij : dict
|
|
310
|
+
The dose influence matrix dictionary.
|
|
311
|
+
ct : CT
|
|
312
|
+
The CT object.
|
|
313
|
+
_cst : StructureSet
|
|
314
|
+
The structure set object. Unused here
|
|
315
|
+
stf : SteeringInformation
|
|
316
|
+
The steering information object.
|
|
317
|
+
i : int
|
|
318
|
+
Index of the beam.
|
|
319
|
+
|
|
320
|
+
Returns
|
|
321
|
+
-------
|
|
322
|
+
dict
|
|
323
|
+
Beam Information dictionary
|
|
324
|
+
"""
|
|
325
|
+
# TODO: here .model_dump() is used to get beam as dict. Its possible to change...
|
|
326
|
+
# ... the ray_tracing to handle this as the model
|
|
327
|
+
beam_info = {"beam": stf.beams[i].model_dump(), "beam_index": i}
|
|
328
|
+
|
|
329
|
+
# Convert voxel indices to real coordinates using iso center of beam i
|
|
330
|
+
coords_v = self._vox_world_coords - beam_info["beam"]["iso_center"]
|
|
331
|
+
coords_vdose_grid = self._vox_world_coords_dose_grid - beam_info["beam"]["iso_center"]
|
|
332
|
+
|
|
333
|
+
# Get Rotation Matrix
|
|
334
|
+
beam_info["rot_mat_system_T"] = get_beam_rotation_matrix(
|
|
335
|
+
beam_info["beam"]["gantry_angle"], beam_info["beam"]["couch_angle"]
|
|
336
|
+
)
|
|
337
|
+
|
|
338
|
+
# Rotate coordinates (1st couch around Y axis, 2nd gantry movement)
|
|
339
|
+
rot_coords_v = np.dot(coords_v, beam_info["rot_mat_system_T"])
|
|
340
|
+
rot_coords_vdose_grid = np.dot(coords_vdose_grid, beam_info["rot_mat_system_T"])
|
|
341
|
+
|
|
342
|
+
rot_coords_v -= beam_info["beam"]["source_point_bev"]
|
|
343
|
+
rot_coords_vdose_grid -= beam_info["beam"]["source_point_bev"]
|
|
344
|
+
|
|
345
|
+
# Calculate geometric distances
|
|
346
|
+
geo_dist_vdose_grid = [
|
|
347
|
+
np.sqrt(np.sum(rot_coords_vdose_grid**2, axis=1)) for _ in range(ct.num_of_ct_scen)
|
|
348
|
+
]
|
|
349
|
+
|
|
350
|
+
# Calculate radiological depth cube
|
|
351
|
+
logger.info("Calculating radiological depth cube...")
|
|
352
|
+
|
|
353
|
+
ct_cube = self.cube_wed
|
|
354
|
+
raytracer = RayTracerSiddon([ct_cube])
|
|
355
|
+
|
|
356
|
+
start_time = time.time()
|
|
357
|
+
|
|
358
|
+
rad_depth_cubes = raytracer.trace_cubes(beam_info["beam"])
|
|
359
|
+
|
|
360
|
+
# TODO: add universal time-debugging method
|
|
361
|
+
end_time = time.time()
|
|
362
|
+
elapsed_time = end_time - start_time
|
|
363
|
+
logger.info("Elapsed time for rayTracing per Beam: %f seconds", elapsed_time)
|
|
364
|
+
|
|
365
|
+
resampled_rad_depth_cube = resample_image(
|
|
366
|
+
input_image=rad_depth_cubes[0],
|
|
367
|
+
interpolator=sitk.sitkLinear,
|
|
368
|
+
target_grid=self.dose_grid,
|
|
369
|
+
)
|
|
370
|
+
if self.keep_rad_depth_cubes:
|
|
371
|
+
self._rad_depth_cubes.append(resampled_rad_depth_cube)
|
|
372
|
+
|
|
373
|
+
rad_depth_cube_dosegrid = sitk.GetArrayViewFromImage(resampled_rad_depth_cube)
|
|
374
|
+
rad_depth_vdose_grid = rad_depth_cube_dosegrid.ravel()[self._vdose_grid]
|
|
375
|
+
|
|
376
|
+
# Find valid coordinates
|
|
377
|
+
coord_is_valid = np.isfinite(rad_depth_vdose_grid)
|
|
378
|
+
|
|
379
|
+
beam_info["valid_coords"] = coord_is_valid
|
|
380
|
+
beam_info["valid_coords_all"] = coord_is_valid
|
|
381
|
+
|
|
382
|
+
# TODO: !remove brakets once mutliscen is implemented
|
|
383
|
+
beam_info["rad_depths"] = [rad_depth_vdose_grid]
|
|
384
|
+
beam_info["geo_depths"] = geo_dist_vdose_grid
|
|
385
|
+
beam_info["bev_coords"] = rot_coords_vdose_grid
|
|
386
|
+
|
|
387
|
+
# Check existence of target_points
|
|
388
|
+
if any(r["target_point"] is None for r in beam_info["beam"]["rays"]):
|
|
389
|
+
logger.debug("Missing target_point in rays. Calculating target points...")
|
|
390
|
+
for ray in beam_info["beam"]["rays"]:
|
|
391
|
+
ray["target_point"] = 2 * ray["ray_pos"] - beam_info["beam"]["source_point"]
|
|
392
|
+
ray["target_point_bev"] = (
|
|
393
|
+
2 * ray["ray_pos_bev"] - beam_info["beam"]["source_point_bev"]
|
|
394
|
+
)
|
|
395
|
+
|
|
396
|
+
# Compute SSDs
|
|
397
|
+
curr_beam = self._compute_ssd(beam_info, ct, density_threshold=self.ssd_density_threshold)
|
|
398
|
+
|
|
399
|
+
logger.info("Done.")
|
|
400
|
+
|
|
401
|
+
return curr_beam
|
|
402
|
+
|
|
403
|
+
def _init_ray(self, curr_beam: dict, j: int) -> dict:
|
|
404
|
+
"""
|
|
405
|
+
Initialize a ray for pencil beam dose calculation.
|
|
406
|
+
|
|
407
|
+
Parameters
|
|
408
|
+
----------
|
|
409
|
+
curr_beam : dict
|
|
410
|
+
The current beam data.
|
|
411
|
+
j : int
|
|
412
|
+
The ray index.
|
|
413
|
+
|
|
414
|
+
Returns
|
|
415
|
+
-------
|
|
416
|
+
dict
|
|
417
|
+
The initialized ray.
|
|
418
|
+
"""
|
|
419
|
+
ray = curr_beam["beam"]["rays"][j]
|
|
420
|
+
ray["beam_index"] = curr_beam["beam_index"]
|
|
421
|
+
ray["ray_index"] = j
|
|
422
|
+
ray["iso_center"] = curr_beam["beam"]["iso_center"]
|
|
423
|
+
|
|
424
|
+
if "num_of_bixels_per_ray" not in curr_beam["beam"]:
|
|
425
|
+
ray["num_of_bixels"] = 1
|
|
426
|
+
else:
|
|
427
|
+
ray["num_of_bixels"] = curr_beam["beam"]["num_of_bixels_per_ray"][j]
|
|
428
|
+
|
|
429
|
+
ray["source_point_bev"] = curr_beam["beam"]["source_point_bev"]
|
|
430
|
+
ray["sad"] = curr_beam["beam"]["sad"]
|
|
431
|
+
ray["bixel_width"] = curr_beam["beam"]["bixel_width"]
|
|
432
|
+
|
|
433
|
+
ray = self._get_ray_geometry_from_beam(ray, curr_beam)
|
|
434
|
+
|
|
435
|
+
return ray
|
|
436
|
+
|
|
437
|
+
def _compute_ssd(
|
|
438
|
+
self,
|
|
439
|
+
beam_info: dict,
|
|
440
|
+
_ct: CT,
|
|
441
|
+
mode: Literal["first"] = "first",
|
|
442
|
+
density_threshold: float = 0.05,
|
|
443
|
+
show_warning: bool = True,
|
|
444
|
+
):
|
|
445
|
+
"""
|
|
446
|
+
Compute SSD (Source to Surface Distance) for each ray in the
|
|
447
|
+
steering information.
|
|
448
|
+
|
|
449
|
+
Parameters
|
|
450
|
+
----------
|
|
451
|
+
beam_info : dict
|
|
452
|
+
Beam Information
|
|
453
|
+
ct : CT
|
|
454
|
+
The CT object.
|
|
455
|
+
mode : Literal["first"], optional
|
|
456
|
+
Mode for handling multiple cubes to compute one SSD. Only 'first' is implemented.
|
|
457
|
+
density_threshold : float, optional
|
|
458
|
+
Value determining the skin threshold.
|
|
459
|
+
show_warning : bool, optional
|
|
460
|
+
Flag to show warnings.
|
|
461
|
+
|
|
462
|
+
Returns
|
|
463
|
+
-------
|
|
464
|
+
SteeringInformation
|
|
465
|
+
Updated steering information object with SSD values.
|
|
466
|
+
"""
|
|
467
|
+
|
|
468
|
+
beam = beam_info["beam"]
|
|
469
|
+
|
|
470
|
+
# TODO: Add MultiScenario Support - remove this line
|
|
471
|
+
if mode == "first":
|
|
472
|
+
ssd = [None] * beam["num_of_rays"]
|
|
473
|
+
|
|
474
|
+
ray_pos_bev = np.array([ray["ray_pos_bev"] for ray in beam["rays"]])
|
|
475
|
+
target_points = np.array([ray["target_point"] for ray in beam["rays"]])
|
|
476
|
+
|
|
477
|
+
raytracer = RayTracerSiddon([self.cube_wed])
|
|
478
|
+
alpha, _, rho, d12, _ = raytracer.trace_rays(
|
|
479
|
+
beam["iso_center"],
|
|
480
|
+
beam["source_point"].reshape((1, 3)),
|
|
481
|
+
target_points,
|
|
482
|
+
)
|
|
483
|
+
|
|
484
|
+
# find rays that do not hit patients
|
|
485
|
+
ix_nan = np.all(np.isnan(rho[0]), axis=1)
|
|
486
|
+
if np.any(ix_nan):
|
|
487
|
+
msg = f"{ix_nan.sum()} rays do not hit patient. Trying to fix afterwards..."
|
|
488
|
+
if show_warning:
|
|
489
|
+
warnings.warn(msg)
|
|
490
|
+
else:
|
|
491
|
+
logger.warning(msg)
|
|
492
|
+
|
|
493
|
+
ix_ssd = -1 * np.ones_like(ix_nan, dtype=np.int64)
|
|
494
|
+
ix_ssd[~ix_nan] = np.argmax(rho[0][~ix_nan] > density_threshold, axis=1)
|
|
495
|
+
|
|
496
|
+
ssd = beam["sad"] * np.ones_like(ix_ssd, dtype=np.float32)
|
|
497
|
+
|
|
498
|
+
ssd[~ix_nan] = d12[~ix_nan].squeeze() * alpha[~ix_nan, ix_ssd[~ix_nan]]
|
|
499
|
+
|
|
500
|
+
# Now assign the ssd to all rays
|
|
501
|
+
for j, ray in enumerate(beam["rays"]):
|
|
502
|
+
if ix_nan[j]: # Try to fix SSD by using SSD of closest neighboring ray
|
|
503
|
+
ray["SSD"] = self._closest_neighbor_ssd(ray_pos_bev, ssd, ray["ray_pos_bev"])
|
|
504
|
+
else:
|
|
505
|
+
ray["SSD"] = float(ssd[j])
|
|
506
|
+
|
|
507
|
+
else:
|
|
508
|
+
raise ValueError(f"Invalid mode {mode} for SSD calculation")
|
|
509
|
+
|
|
510
|
+
beam_info["beam"] = beam
|
|
511
|
+
|
|
512
|
+
return beam_info
|
|
513
|
+
|
|
514
|
+
def _closest_neighbor_ssd(
|
|
515
|
+
self, ray_pos_bev: np.ndarray, ssd: np.ndarray, curr_pos: np.ndarray
|
|
516
|
+
) -> float:
|
|
517
|
+
"""
|
|
518
|
+
Find the closest neighboring ray's SSD.
|
|
519
|
+
|
|
520
|
+
Parameters
|
|
521
|
+
----------
|
|
522
|
+
ray_pos_bev : np.ndarray
|
|
523
|
+
Array of ray positions.
|
|
524
|
+
curr_pos : np.ndarray
|
|
525
|
+
Current ray position.
|
|
526
|
+
|
|
527
|
+
Returns
|
|
528
|
+
-------
|
|
529
|
+
float
|
|
530
|
+
SSD value of the closest neighboring ray.
|
|
531
|
+
"""
|
|
532
|
+
distances = np.sum((ray_pos_bev - curr_pos) ** 2, axis=1)
|
|
533
|
+
sorted_indices = np.argsort(distances)
|
|
534
|
+
for ix in sorted_indices:
|
|
535
|
+
if ssd[ix] is not None:
|
|
536
|
+
return float(ssd[ix])
|
|
537
|
+
raise ValueError(
|
|
538
|
+
"Error in SSD calculation: Could not fix SSD calculation by using closest neighboring "
|
|
539
|
+
"ray."
|
|
540
|
+
)
|
|
541
|
+
|
|
542
|
+
#
|
|
543
|
+
# """Find the closest neighbor to ray j and return its SSD."""
|
|
544
|
+
# distances = np.linalg.norm(ray_pos_bev - ray_pos_bev[j], axis=1)
|
|
545
|
+
# distances[j] = np.inf
|
|
546
|
+
# return SSD[np.argmin(distances)]
|
|
547
|
+
|
|
548
|
+
def _extract_single_scenario_ray(self, ray: dict, scen_idx: int):
|
|
549
|
+
"""
|
|
550
|
+
Extract a single scenario ray and adapt radiological depths.
|
|
551
|
+
|
|
552
|
+
Parameters
|
|
553
|
+
----------
|
|
554
|
+
ray (dict):
|
|
555
|
+
The ray data.
|
|
556
|
+
scen_idx (int):
|
|
557
|
+
The scenario index.
|
|
558
|
+
|
|
559
|
+
Returns
|
|
560
|
+
-------
|
|
561
|
+
dict:
|
|
562
|
+
The scenario ray with adapted radiological depths.
|
|
563
|
+
"""
|
|
564
|
+
# Gets number of scenario
|
|
565
|
+
scen_num = self.mult_scen.scen_num(scen_idx)
|
|
566
|
+
ct_scen = self.mult_scen.linear_mask[0][scen_num]
|
|
567
|
+
|
|
568
|
+
# First, create a ray of the specific scenario to adapt rad depths
|
|
569
|
+
scen_ray = ray.copy()
|
|
570
|
+
scen_ray["rad_depths"] = scen_ray["rad_depths"][ct_scen]
|
|
571
|
+
scen_ray["rad_depths"] = (1 + self.mult_scen.rel_range_shift[scen_num]) * scen_ray[
|
|
572
|
+
"rad_depths"
|
|
573
|
+
] + self.mult_scen.abs_range_shift[scen_num]
|
|
574
|
+
scen_ray["radial_dist_sq"] = scen_ray["radial_dist_sq"][ct_scen]
|
|
575
|
+
scen_ray["ix"] = scen_ray["ix"][ct_scen]
|
|
576
|
+
|
|
577
|
+
if self.mult_scen.abs_range_shift[scen_num] < 0:
|
|
578
|
+
# TODO: better way to handle this?
|
|
579
|
+
scen_ray["rad_depths"][scen_ray["rad_depths"] < 0] = 0
|
|
580
|
+
|
|
581
|
+
if "geo_depths" in scen_ray:
|
|
582
|
+
scen_ray["geo_depths"] = scen_ray["geo_depths"][ct_scen]
|
|
583
|
+
|
|
584
|
+
if "lat_dists" in scen_ray:
|
|
585
|
+
scen_ray["lat_dists"] = scen_ray["lat_dists"][ct_scen]
|
|
586
|
+
|
|
587
|
+
if "iso_lat_dists" in scen_ray:
|
|
588
|
+
scen_ray["iso_lat_dists"] = scen_ray["iso_lat_dists"][ct_scen]
|
|
589
|
+
|
|
590
|
+
return scen_ray
|
|
591
|
+
|
|
592
|
+
def _get_ray_geometry_from_beam(self, _ray: dict, _curr_beam: dict) -> dict:
|
|
593
|
+
raise NotImplementedError(
|
|
594
|
+
"Method _get_ray_geometry_from_beam must be implemented in derived class."
|
|
595
|
+
)
|
|
596
|
+
|
|
597
|
+
def _get_lateral_distance_from_dose_cutoff_on_ray(self, _ray: dict) -> float:
|
|
598
|
+
"""
|
|
599
|
+
Obtain the maximum lateral cutoff distance given a dosimetric cutoff
|
|
600
|
+
on a a ray.
|
|
601
|
+
|
|
602
|
+
Parameters
|
|
603
|
+
----------
|
|
604
|
+
_ray : dict
|
|
605
|
+
The ray data. Unused in this base implementation.
|
|
606
|
+
|
|
607
|
+
Returns
|
|
608
|
+
-------
|
|
609
|
+
float
|
|
610
|
+
The lateral distance from the dose cutoff on the ray.
|
|
611
|
+
"""
|
|
612
|
+
|
|
613
|
+
lateral_ray_cutoff = self._effective_lateral_cutoff
|
|
614
|
+
return lateral_ray_cutoff
|
|
615
|
+
|
|
616
|
+
def _fill_dij(
|
|
617
|
+
self,
|
|
618
|
+
bixel: dict,
|
|
619
|
+
dij: dict,
|
|
620
|
+
_stf: SteeringInformation,
|
|
621
|
+
scen_idx: int,
|
|
622
|
+
curr_beam_idx: int,
|
|
623
|
+
curr_ray_idx: int,
|
|
624
|
+
curr_bixel_idx: int,
|
|
625
|
+
bixel_counter: int,
|
|
626
|
+
):
|
|
627
|
+
"""
|
|
628
|
+
Fill the dose influence matrix (dij) with the computed dose cube.
|
|
629
|
+
This is the last step in bixel dose calculation.
|
|
630
|
+
|
|
631
|
+
Parameters
|
|
632
|
+
----------
|
|
633
|
+
bixel : dict
|
|
634
|
+
The bixel data.
|
|
635
|
+
dij : dict
|
|
636
|
+
The dose influence matrix.
|
|
637
|
+
stf : SteeringInformation
|
|
638
|
+
The structure containing beam information. Unused in this base implementation.
|
|
639
|
+
scen_idx : int
|
|
640
|
+
The scenario index.
|
|
641
|
+
curr_beam_idx : int
|
|
642
|
+
The current beam index.
|
|
643
|
+
curr_ray_idx : int
|
|
644
|
+
The current ray index.
|
|
645
|
+
curr_bixel_idx : int
|
|
646
|
+
The current bixel index.
|
|
647
|
+
bixel_counter : int
|
|
648
|
+
The counter for the bixels.
|
|
649
|
+
|
|
650
|
+
Returns
|
|
651
|
+
-------
|
|
652
|
+
dict
|
|
653
|
+
The updated dose influence matrix.
|
|
654
|
+
"""
|
|
655
|
+
# Only fill if we actually had bixel (indices) to compute
|
|
656
|
+
if bixel and "ix" in bixel and bixel["ix"].any():
|
|
657
|
+
sub_scen_idx = [
|
|
658
|
+
np.unravel_index(scen_idx, self.mult_scen.scen_mask.shape)[i]
|
|
659
|
+
for i in range(self.mult_scen.scen_mask.ndim)
|
|
660
|
+
]
|
|
661
|
+
sub_scen_idx = tuple(sub_scen_idx)
|
|
662
|
+
|
|
663
|
+
for q_name in self._computed_quantities:
|
|
664
|
+
if self._calc_dose_direct:
|
|
665
|
+
# We accumulate the current bixel to the container
|
|
666
|
+
dij[q_name][sub_scen_idx][bixel["ix"]] += bixel[q_name]
|
|
667
|
+
else:
|
|
668
|
+
# We insert into the lil sparse matrix
|
|
669
|
+
# This could probably be optimized by using direct access to the lil_matrix's
|
|
670
|
+
# data structures
|
|
671
|
+
dij[q_name][sub_scen_idx][bixel_counter, bixel["ix"]] = bixel[q_name]
|
|
672
|
+
|
|
673
|
+
# Bookkeeping of bixel numbers
|
|
674
|
+
# remember beam and bixel number
|
|
675
|
+
if self._calc_dose_direct:
|
|
676
|
+
dij["beam_num"][curr_beam_idx] = curr_beam_idx
|
|
677
|
+
dij["ray_num"][curr_beam_idx] = curr_beam_idx
|
|
678
|
+
dij["bixel_num"][curr_beam_idx] = curr_beam_idx
|
|
679
|
+
else:
|
|
680
|
+
dij["beam_num"][bixel_counter] = curr_beam_idx
|
|
681
|
+
dij["ray_num"][bixel_counter] = curr_ray_idx
|
|
682
|
+
dij["bixel_num"][bixel_counter] = curr_bixel_idx
|
|
683
|
+
|
|
684
|
+
return dij
|
|
685
|
+
|
|
686
|
+
def _finalize_dose(self, dij: dict) -> dict:
|
|
687
|
+
"""
|
|
688
|
+
Finalize the dose influence matrix by removing dose influence for
|
|
689
|
+
voxels outside of segmentations for every CT scenario.
|
|
690
|
+
|
|
691
|
+
Parameters
|
|
692
|
+
----------
|
|
693
|
+
dij : dict
|
|
694
|
+
The dose influence matrix.
|
|
695
|
+
|
|
696
|
+
Returns
|
|
697
|
+
-------
|
|
698
|
+
dict
|
|
699
|
+
The updated dose influence matrix.
|
|
700
|
+
"""
|
|
701
|
+
|
|
702
|
+
# Loop over all scenarios and remove dose influence for voxels outside of segmentations
|
|
703
|
+
for i in range(self.mult_scen.scen_mask.size):
|
|
704
|
+
# Only if there is a scenario we will allocate
|
|
705
|
+
if self.mult_scen.scen_mask.flat[i]:
|
|
706
|
+
# Loop over all used quantities
|
|
707
|
+
for q_name in self._computed_quantities:
|
|
708
|
+
tmp_matrix = cast(sparse.lil_matrix, dij[q_name].flat[i])
|
|
709
|
+
tmp_matrix = tmp_matrix.tocsr().T
|
|
710
|
+
tmp_matrix.eliminate_zeros()
|
|
711
|
+
dij[q_name].flat[i] = tmp_matrix
|
|
712
|
+
|
|
713
|
+
if self.keep_rad_depth_cubes and self._rad_depth_cubes:
|
|
714
|
+
dij["rad_depth_cubes"] = self._rad_depth_cubes
|
|
715
|
+
|
|
716
|
+
# Call the finalizeDose method from the base class
|
|
717
|
+
dij = super()._finalize_dose(dij)
|
|
718
|
+
|
|
719
|
+
return dij
|
|
720
|
+
|
|
721
|
+
@staticmethod
|
|
722
|
+
def calc_geo_dists(
|
|
723
|
+
rot_coords_bev, source_point_bev, target_point_bev, sad, rad_depth_ix, lateral_cutoff
|
|
724
|
+
):
|
|
725
|
+
"""
|
|
726
|
+
Calculate geometric distances for dose calculation.
|
|
727
|
+
|
|
728
|
+
Parameters
|
|
729
|
+
----------
|
|
730
|
+
rot_coords_bev : ndarray
|
|
731
|
+
Coordinates in beam's eye view (BEV) of the voxels where ray tracing results are
|
|
732
|
+
available.
|
|
733
|
+
source_point_bev : ndarray
|
|
734
|
+
Source point in voxel coordinates in BEV.
|
|
735
|
+
target_point_bev : ndarray
|
|
736
|
+
Target point in voxel coordinates in BEV.
|
|
737
|
+
sad : float
|
|
738
|
+
Source-to-axis distance.
|
|
739
|
+
rad_depth_ix : ndarray
|
|
740
|
+
Subset of voxels for which radiological depth calculations are available.
|
|
741
|
+
lateral_cutoff : float
|
|
742
|
+
Lateral cutoff specifying the neighborhood for dose calculations.
|
|
743
|
+
|
|
744
|
+
Returns
|
|
745
|
+
-------
|
|
746
|
+
ix : ndarray
|
|
747
|
+
Indices of voxels where dose influence is computed.
|
|
748
|
+
rad_distances_sq : ndarray
|
|
749
|
+
Squared radial distances to the central ray.
|
|
750
|
+
lat_dists : ndarray
|
|
751
|
+
Lateral distances to the central ray (in X & Z).
|
|
752
|
+
iso_lat_dists : ndarray
|
|
753
|
+
Lateral distances to the central ray projected onto the isocenter plane.
|
|
754
|
+
rot_coords_bev, source_point_bev, target_point_bev, sad, rad_depth_ix, lateral_cutoff
|
|
755
|
+
"""
|
|
756
|
+
# Put [0 0 0] position in the source point for beamlet who passes through isocenter
|
|
757
|
+
a = -source_point_bev.T
|
|
758
|
+
|
|
759
|
+
# Normalize the vector
|
|
760
|
+
a = a / np.linalg.norm(a)
|
|
761
|
+
|
|
762
|
+
# Put [0 0 0] position in the source point for a single beamlet
|
|
763
|
+
b = (target_point_bev - source_point_bev).T
|
|
764
|
+
|
|
765
|
+
# Normalize the vector
|
|
766
|
+
b = b / np.linalg.norm(b)
|
|
767
|
+
|
|
768
|
+
# Define rotation matrix
|
|
769
|
+
if np.all(a == b):
|
|
770
|
+
rot_coords_temp = rot_coords_bev[rad_depth_ix, :]
|
|
771
|
+
else:
|
|
772
|
+
|
|
773
|
+
def ssc(v: np.ndarray) -> np.ndarray:
|
|
774
|
+
"""Skew-symmetric cross product matrix."""
|
|
775
|
+
return np.array([[0, -v[2], v[1]], [v[2], 0, -v[0]], [-v[1], v[0], 0]])
|
|
776
|
+
|
|
777
|
+
derived_rot_mat = (
|
|
778
|
+
np.eye(3)
|
|
779
|
+
+ ssc(np.cross(a, b))
|
|
780
|
+
+ np.dot(ssc(np.cross(a, b)), ssc(np.cross(a, b)))
|
|
781
|
+
* (1 - np.dot(a, b))
|
|
782
|
+
/ (np.linalg.norm(np.cross(a, b)) ** 2)
|
|
783
|
+
)
|
|
784
|
+
rot_coords_temp = np.dot(rot_coords_bev[rad_depth_ix, :], derived_rot_mat)
|
|
785
|
+
|
|
786
|
+
# Put [0 0 0] position CT in center of the beamlet
|
|
787
|
+
lat_dists = rot_coords_temp[:, [0, 2]] + source_point_bev[[0, 2]]
|
|
788
|
+
|
|
789
|
+
# Check if radial distance exceeds lateral cutoff (projected to iso center)
|
|
790
|
+
rad_distances_sq = np.sum(lat_dists**2, axis=1)
|
|
791
|
+
subset_mask = rad_distances_sq <= (lateral_cutoff / sad) ** 2 * rot_coords_temp[:, 1] ** 2
|
|
792
|
+
|
|
793
|
+
ix = rad_depth_ix.copy()
|
|
794
|
+
# Apply mask for return quantities
|
|
795
|
+
ix[rad_depth_ix] = subset_mask
|
|
796
|
+
|
|
797
|
+
# Return radial distances squared
|
|
798
|
+
rad_distances_sq = rad_distances_sq[subset_mask]
|
|
799
|
+
|
|
800
|
+
# Lateral distances in X & Z
|
|
801
|
+
lat_dists = lat_dists[subset_mask, :]
|
|
802
|
+
|
|
803
|
+
# Lateral distances projected onto isocenter
|
|
804
|
+
iso_lat_dists = lat_dists / rot_coords_temp[subset_mask, 1][:, np.newaxis] * sad
|
|
805
|
+
|
|
806
|
+
return ix, rad_distances_sq, lat_dists, iso_lat_dists
|