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,1015 @@
|
|
|
1
|
+
"""Base class for particle pencil beam dose calculation algorithms."""
|
|
2
|
+
|
|
3
|
+
import warnings
|
|
4
|
+
from abc import abstractmethod
|
|
5
|
+
from typing import cast, Literal, Any
|
|
6
|
+
import logging
|
|
7
|
+
import time
|
|
8
|
+
|
|
9
|
+
import numpy as np
|
|
10
|
+
from scipy.interpolate import interp1d
|
|
11
|
+
from scipy.integrate import cumulative_trapezoid
|
|
12
|
+
|
|
13
|
+
from pyRadPlan.ct import CT
|
|
14
|
+
from pyRadPlan.stf import SteeringInformation
|
|
15
|
+
from pyRadPlan.machines import IonAccelerator, IonPencilBeamKernel, LateralCutOff
|
|
16
|
+
from pyRadPlan.cst import StructureSet
|
|
17
|
+
from ._base_pencilbeam import PencilBeamEngineAbstract
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
logger = logging.getLogger(__name__)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class ParticlePencilBeamEngineAbstract(PencilBeamEngineAbstract):
|
|
24
|
+
"""
|
|
25
|
+
An abstract class representing Particle Pencil-Beam dose calculation
|
|
26
|
+
algorithms.
|
|
27
|
+
|
|
28
|
+
This class extends PencilBeamEngineAbstract by adding infrastructure for particles spots and
|
|
29
|
+
quantities like LET and biological dose for variable RBE calculations.
|
|
30
|
+
|
|
31
|
+
Attributes:
|
|
32
|
+
-----------
|
|
33
|
+
calc_let : bool
|
|
34
|
+
Boolean which defines if LET should be calculated.
|
|
35
|
+
calc_bio_dose : bool
|
|
36
|
+
Boolean to query biological dose calculation.
|
|
37
|
+
air_offset_correction : bool
|
|
38
|
+
Corrects WEPL for SSD difference to kernel database.
|
|
39
|
+
lateral_model : Literal["auto", "single", "double", "multi", "fastest"]
|
|
40
|
+
Lateral Model used. 'auto' uses the most accurate model available ( multiple Gaussians).
|
|
41
|
+
"fastest" uses the most simple, inaccurate model (e.g., single Gaussian).
|
|
42
|
+
cut_off_method : Literal["integral", "relative"]
|
|
43
|
+
Method used to determine lateral cut off. 'integral' uses the integral of the lateral
|
|
44
|
+
dose profile to obtain the cut-off distance. 'relative' finds the lateral distance at which
|
|
45
|
+
the dose drops to the requested cutoff
|
|
46
|
+
"""
|
|
47
|
+
|
|
48
|
+
calc_let: bool
|
|
49
|
+
calc_bio_dose: bool
|
|
50
|
+
air_offset_correction: bool
|
|
51
|
+
lateral_model: Literal["auto", "single", "double", "multi", "fastest"]
|
|
52
|
+
cut_off_method: Literal["integral", "relative"]
|
|
53
|
+
|
|
54
|
+
def __init__(self, pln):
|
|
55
|
+
self.calc_let = True
|
|
56
|
+
self.calc_bio_dose = False
|
|
57
|
+
self.air_offset_correction = True
|
|
58
|
+
self.lateral_model = "auto"
|
|
59
|
+
self.cut_off_method = "integral"
|
|
60
|
+
|
|
61
|
+
# Protected properties with public get access
|
|
62
|
+
self._constant_rbe = None # constant RBE value
|
|
63
|
+
self._v_tissue_index = None # Stores tissue indices available in the matRad base data
|
|
64
|
+
self._v_alpha_x = None # Stores Photon Alpha
|
|
65
|
+
self._v_beta_x = None # Stores Photon Beta
|
|
66
|
+
|
|
67
|
+
super().__init__(pln)
|
|
68
|
+
|
|
69
|
+
@abstractmethod
|
|
70
|
+
def _calc_particle_bixel(self, bixel):
|
|
71
|
+
pass
|
|
72
|
+
|
|
73
|
+
def _choose_lateral_model(self):
|
|
74
|
+
"""
|
|
75
|
+
Chooses / Validates the lateral model according to the requested
|
|
76
|
+
setting.
|
|
77
|
+
"""
|
|
78
|
+
|
|
79
|
+
available_models = {
|
|
80
|
+
"single": self._machine.has_single_gaussian_kernel,
|
|
81
|
+
"double": self._machine.has_double_gaussian_kernel,
|
|
82
|
+
"multi": self._machine.has_multi_gaussian_kernel,
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
# First we validate the users choice
|
|
86
|
+
if self.lateral_model in available_models:
|
|
87
|
+
if not available_models[self.lateral_model]:
|
|
88
|
+
logger.warning(
|
|
89
|
+
"Chosen Machine does not support a %s Gaussian Pencil-Beam model!",
|
|
90
|
+
self.lateral_model,
|
|
91
|
+
)
|
|
92
|
+
self.lateral_model = "auto"
|
|
93
|
+
else:
|
|
94
|
+
if self.lateral_model not in ["auto", "fastest"]:
|
|
95
|
+
logger.warning(
|
|
96
|
+
"Invalid lateral model %s. Using auto instead.",
|
|
97
|
+
self.lateral_model,
|
|
98
|
+
)
|
|
99
|
+
self.lateral_model = "auto"
|
|
100
|
+
|
|
101
|
+
# Now if auto, we choose the most accurate one (i.e. the last one in the dictionary that
|
|
102
|
+
# is available)
|
|
103
|
+
|
|
104
|
+
if self.lateral_model == "auto":
|
|
105
|
+
for key, available in available_models.items():
|
|
106
|
+
if available:
|
|
107
|
+
self.lateral_model = key
|
|
108
|
+
|
|
109
|
+
# if it is "auto"
|
|
110
|
+
if self.lateral_model == "fastest":
|
|
111
|
+
for key, available in available_models.items():
|
|
112
|
+
if available:
|
|
113
|
+
self.lateral_model = key
|
|
114
|
+
break
|
|
115
|
+
|
|
116
|
+
logger.info("Using a %s Gaussian pencil-beam kernel model!\n", self.lateral_model)
|
|
117
|
+
|
|
118
|
+
def _compute_bixel(self, curr_ray, k):
|
|
119
|
+
"""
|
|
120
|
+
Compute the bixel for the given ray and index.
|
|
121
|
+
|
|
122
|
+
Parameters
|
|
123
|
+
----------
|
|
124
|
+
curr_ray : dict
|
|
125
|
+
The current ray data.
|
|
126
|
+
k : int
|
|
127
|
+
The index of the bixel.
|
|
128
|
+
|
|
129
|
+
Returns
|
|
130
|
+
-------
|
|
131
|
+
dict
|
|
132
|
+
The computed bixel.
|
|
133
|
+
"""
|
|
134
|
+
# Initialize Bixel Geometry
|
|
135
|
+
bixel = self._init_bixel(curr_ray, k)
|
|
136
|
+
|
|
137
|
+
# Compute Bixel
|
|
138
|
+
bixel = self._calc_particle_bixel(bixel)
|
|
139
|
+
|
|
140
|
+
return bixel
|
|
141
|
+
|
|
142
|
+
def _init_bixel(self, curr_ray, k):
|
|
143
|
+
"""
|
|
144
|
+
Initialize general bixel geometry for particle dose calculation.
|
|
145
|
+
|
|
146
|
+
Parameters
|
|
147
|
+
----------
|
|
148
|
+
curr_ray : dict
|
|
149
|
+
The current ray data.
|
|
150
|
+
k : int
|
|
151
|
+
The index of the bixel.
|
|
152
|
+
|
|
153
|
+
Returns
|
|
154
|
+
-------
|
|
155
|
+
dict
|
|
156
|
+
The initialized bixel.
|
|
157
|
+
"""
|
|
158
|
+
|
|
159
|
+
bixel = {}
|
|
160
|
+
bixel["beam_index"] = curr_ray["beam_index"]
|
|
161
|
+
bixel["ray_index"] = curr_ray["ray_index"]
|
|
162
|
+
bixel["bixel_index"] = k
|
|
163
|
+
|
|
164
|
+
# First we get metadata: MU, corresponding base data entry, etc.
|
|
165
|
+
# Extract MU data if present (checks for downwards compatibility)
|
|
166
|
+
bixel["min_mu"] = 0
|
|
167
|
+
if "min_mu" in curr_ray:
|
|
168
|
+
bixel["min_mu"] = curr_ray["min_mu"][k]
|
|
169
|
+
|
|
170
|
+
bixel["max_mu"] = float("inf")
|
|
171
|
+
if "max_mu" in curr_ray:
|
|
172
|
+
bixel["max_mu"] = curr_ray["max_mu"][k]
|
|
173
|
+
|
|
174
|
+
bixel["num_particles_per_mu"] = 1e6
|
|
175
|
+
if "num_particles_per_mu" in curr_ray:
|
|
176
|
+
bixel["num_particles_per_mu"] = curr_ray["num_particles_per_mu"][k]
|
|
177
|
+
|
|
178
|
+
# Find energy index in base data
|
|
179
|
+
energy = curr_ray["beamlets"][k]["energy"]
|
|
180
|
+
energy_ix = self._machine.get_energy_index(energy, 4)
|
|
181
|
+
|
|
182
|
+
if energy_ix.size > 1:
|
|
183
|
+
raise ValueError("Multiple energies found in base data for one bixel!")
|
|
184
|
+
|
|
185
|
+
energy_ix = np.int64(energy_ix)
|
|
186
|
+
|
|
187
|
+
bixel["energy_ix"] = energy_ix
|
|
188
|
+
|
|
189
|
+
# Get the kernel for the current energy
|
|
190
|
+
tmp_machine = cast(IonAccelerator, self._machine)
|
|
191
|
+
bixel["kernel"] = tmp_machine.get_kernel_by_index(energy_ix)
|
|
192
|
+
|
|
193
|
+
bixel["range_shifter"] = curr_ray["beamlets"][k]["range_shifter"]
|
|
194
|
+
bixel["SSD"] = curr_ray["SSD"]
|
|
195
|
+
bixel["rad_depth_offset"] = curr_ray["rad_depth_offset"]
|
|
196
|
+
|
|
197
|
+
# Compute initial spot width
|
|
198
|
+
bixel["sigma_ini_sq"] = curr_ray["sigma_ini"][k] ** 2
|
|
199
|
+
|
|
200
|
+
# Apply beam modifiers
|
|
201
|
+
bixel = self._get_beam_modifiers(bixel)
|
|
202
|
+
|
|
203
|
+
# Gets bixel.ix (voxel indices) and bixel.subIx (logical
|
|
204
|
+
# indices to be used) after cutoff. Storing these allows us to
|
|
205
|
+
# use indexing for performance and avoid too many copies
|
|
206
|
+
bixel = self._get_bixel_indices_on_ray(bixel, curr_ray)
|
|
207
|
+
if "ix" not in bixel or bixel["ix"].size == 0:
|
|
208
|
+
return bixel
|
|
209
|
+
|
|
210
|
+
# Get quantities 1:1 from ray. Here we trust Python's memory
|
|
211
|
+
# management to not copy the arrays until they are modified.
|
|
212
|
+
# This allows us to efficiently access them by indexing in the
|
|
213
|
+
# bixel computation
|
|
214
|
+
bixel["radial_dist_sq"] = curr_ray["radial_dist_sq"][bixel["sub_ix"]]
|
|
215
|
+
bixel["rad_depths"] = curr_ray["rad_depths"][bixel["sub_ix"]]
|
|
216
|
+
# TODO:
|
|
217
|
+
# if self.calc_bio_dose:
|
|
218
|
+
# bixel["v_tissue_index"] = curr_ray["v_tissue_index"][bixel["sub_ix"]]
|
|
219
|
+
# bixel["v_alpha_x"] = curr_ray["v_alpha_x"][bixel["sub_ix"]]
|
|
220
|
+
# bixel["v_beta_x"] = curr_ray["v_beta_x"][bixel["sub_ix"]]
|
|
221
|
+
|
|
222
|
+
return bixel
|
|
223
|
+
|
|
224
|
+
def _interpolate_kernels_in_depth(self, bixel):
|
|
225
|
+
kernel = cast(IonPencilBeamKernel, bixel["kernel"])
|
|
226
|
+
depths = kernel.depths
|
|
227
|
+
|
|
228
|
+
# Add potential offset
|
|
229
|
+
depths = depths + kernel.offset - bixel["rad_depth_offset"]
|
|
230
|
+
|
|
231
|
+
# Conversion factor from MeV cm^2/g per primary to Gy mm^2 per 1e6 primaries
|
|
232
|
+
conversion_factor = 1.6021766208e-02
|
|
233
|
+
|
|
234
|
+
# Find all values we need to interpolate
|
|
235
|
+
used_kernels = {}
|
|
236
|
+
used_kernels["idd"] = conversion_factor * kernel.idd
|
|
237
|
+
|
|
238
|
+
# Lateral Kernel Model
|
|
239
|
+
if self.lateral_model == "single":
|
|
240
|
+
used_kernels["sigma"] = kernel.sigma
|
|
241
|
+
elif self.lateral_model == "double":
|
|
242
|
+
used_kernels["sigma_1"] = kernel.sigma_1
|
|
243
|
+
used_kernels["sigma_2"] = kernel.sigma_2
|
|
244
|
+
used_kernels["weight"] = kernel.weight
|
|
245
|
+
elif self.lateral_model == "multi":
|
|
246
|
+
used_kernels["weight_multi"] = kernel.weight_multi
|
|
247
|
+
used_kernels["sigma_multi"] = kernel.sigma_multi
|
|
248
|
+
else:
|
|
249
|
+
raise ValueError("Invalid Lateral Model")
|
|
250
|
+
|
|
251
|
+
# LET
|
|
252
|
+
if self.calc_let:
|
|
253
|
+
used_kernels["let"] = kernel.let
|
|
254
|
+
|
|
255
|
+
# bioDose
|
|
256
|
+
# TODO:
|
|
257
|
+
if self.calc_bio_dose:
|
|
258
|
+
used_kernels["alpha"] = kernel.alpha
|
|
259
|
+
used_kernels["beta"] = kernel.beta
|
|
260
|
+
|
|
261
|
+
# Interpolate all fields in X
|
|
262
|
+
kernel_interp = {}
|
|
263
|
+
for key, kernel_data in used_kernels.items():
|
|
264
|
+
if kernel_data.ndim > 1:
|
|
265
|
+
kernel_data = np.apply_along_axis(
|
|
266
|
+
lambda x: np.interp(bixel["rad_depths"], depths, x), axis=1, arr=kernel_data
|
|
267
|
+
)
|
|
268
|
+
else:
|
|
269
|
+
kernel_data = np.interp(bixel["rad_depths"], depths, kernel_data)
|
|
270
|
+
|
|
271
|
+
kernel_interp[key] = kernel_data
|
|
272
|
+
|
|
273
|
+
return kernel_interp
|
|
274
|
+
|
|
275
|
+
def _get_ray_geometry_from_beam(self, ray, curr_beam):
|
|
276
|
+
lateral_ray_cutoff = self._get_lateral_distance_from_dose_cutoff_on_ray(ray)
|
|
277
|
+
|
|
278
|
+
# Ray tracing for beam i and ray j
|
|
279
|
+
ix, radial_dist_sq, _, _ = self.calc_geo_dists(
|
|
280
|
+
curr_beam["bev_coords"],
|
|
281
|
+
ray["source_point_bev"],
|
|
282
|
+
ray["target_point_bev"],
|
|
283
|
+
ray["sad"],
|
|
284
|
+
curr_beam["valid_coords_all"],
|
|
285
|
+
lateral_ray_cutoff,
|
|
286
|
+
)
|
|
287
|
+
|
|
288
|
+
# Subindex given the relevant indices from the geometric distance calculation
|
|
289
|
+
ray["valid_coords"] = [beam_ix & ix for beam_ix in curr_beam["valid_coords"]]
|
|
290
|
+
ray["ix"] = [self._vdose_grid[ix_in_grid] for ix_in_grid in ray["valid_coords"]]
|
|
291
|
+
|
|
292
|
+
ray["radial_dist_sq"] = [
|
|
293
|
+
radial_dist_sq[beam_ix[ix]] for beam_ix in curr_beam["valid_coords"]
|
|
294
|
+
]
|
|
295
|
+
|
|
296
|
+
ray["valid_coords_all"] = np.any(np.vstack(ray["valid_coords"]), axis=1)
|
|
297
|
+
|
|
298
|
+
ray["geo_depths"] = [
|
|
299
|
+
rD[ix] for rD, ix in zip(curr_beam["geo_depths"], ray["valid_coords"])
|
|
300
|
+
] # usually not needed for particle beams
|
|
301
|
+
ray["rad_depths"] = [
|
|
302
|
+
rD[ix] for rD, ix in zip(curr_beam["rad_depths"], ray["valid_coords"])
|
|
303
|
+
]
|
|
304
|
+
return ray
|
|
305
|
+
|
|
306
|
+
def _get_bixel_indices_on_ray(self, curr_bixel, curr_ray):
|
|
307
|
+
kernel = cast(IonPencilBeamKernel, curr_bixel["kernel"])
|
|
308
|
+
|
|
309
|
+
# Create offset vector to account for additional offsets modeled in the base data
|
|
310
|
+
# and a potential range shifter
|
|
311
|
+
tmp_offset = kernel.offset - curr_bixel["rad_depth_offset"]
|
|
312
|
+
|
|
313
|
+
# Find depth-dependent lateral cutoff
|
|
314
|
+
if self.dosimetric_lateral_cutoff == 1:
|
|
315
|
+
curr_ix = curr_ray["rad_depths"] <= kernel.depths[-1] + tmp_offset
|
|
316
|
+
elif 0 < self.dosimetric_lateral_cutoff < 1:
|
|
317
|
+
cutoff_info = kernel.lateral_cut_off
|
|
318
|
+
|
|
319
|
+
if cutoff_info.cut_off.size > 1:
|
|
320
|
+
curr_ix = (
|
|
321
|
+
np.interp(
|
|
322
|
+
curr_ray["rad_depths"],
|
|
323
|
+
cutoff_info.depths + tmp_offset,
|
|
324
|
+
cutoff_info.cut_off**2,
|
|
325
|
+
left=np.nan,
|
|
326
|
+
right=np.nan,
|
|
327
|
+
)
|
|
328
|
+
>= curr_ray["radial_dist_sq"]
|
|
329
|
+
) & (curr_ray["rad_depths"] <= kernel.depths[-1] + tmp_offset)
|
|
330
|
+
else:
|
|
331
|
+
curr_ix = (cutoff_info.cut_off[0] ** 2 >= curr_ray["radial_dist_sq"]) & (
|
|
332
|
+
curr_ray["rad_depths"] <= kernel.depths[-1] + tmp_offset
|
|
333
|
+
)
|
|
334
|
+
else:
|
|
335
|
+
raise ValueError("dosimetric_lateral_cutoff must be a value > 0 and <= 1!")
|
|
336
|
+
|
|
337
|
+
curr_bixel["sub_ix"] = curr_ix
|
|
338
|
+
curr_bixel["ix"] = curr_ray["ix"][curr_ix]
|
|
339
|
+
|
|
340
|
+
return curr_bixel
|
|
341
|
+
|
|
342
|
+
def _get_beam_modifiers(self, curr_bixel):
|
|
343
|
+
add_sigma_sq = 0
|
|
344
|
+
rad_depth_offset = 0
|
|
345
|
+
|
|
346
|
+
# Consider range shifter for protons if applicable
|
|
347
|
+
if curr_bixel["range_shifter"]["eq_thickness"] > 0:
|
|
348
|
+
# TODO: We should do this check in dose calc initialization instead to spare some time
|
|
349
|
+
if self._machine["meta"]["radiationMode"] != "protons":
|
|
350
|
+
warnings.warn(
|
|
351
|
+
"Range shifter not valid for irradiation with particle other than protons!"
|
|
352
|
+
)
|
|
353
|
+
|
|
354
|
+
# Compute!
|
|
355
|
+
sigma_rashi = self._calc_sigma_rashi(
|
|
356
|
+
curr_bixel["kernel"]["energy"], curr_bixel["range_shifter"], curr_bixel["SSD"]
|
|
357
|
+
)
|
|
358
|
+
|
|
359
|
+
# Add to initial sigma in quadrature
|
|
360
|
+
add_sigma_sq += sigma_rashi**2
|
|
361
|
+
rad_depth_offset += curr_bixel["range_shifter"]["eq_thickness"]
|
|
362
|
+
|
|
363
|
+
curr_bixel["add_sigma_sq"] = add_sigma_sq
|
|
364
|
+
curr_bixel["rad_depth_offset"] += rad_depth_offset
|
|
365
|
+
|
|
366
|
+
return curr_bixel
|
|
367
|
+
|
|
368
|
+
def _init_dose_calc(self, ct, cst, stf):
|
|
369
|
+
"""
|
|
370
|
+
Modified inherited method of the superclass DoseEngine,
|
|
371
|
+
containing intialization which are specificly needed for
|
|
372
|
+
pencil beam calculation and not for other engines.
|
|
373
|
+
"""
|
|
374
|
+
|
|
375
|
+
dij = super()._init_dose_calc(ct, cst, stf)
|
|
376
|
+
|
|
377
|
+
# Choose the lateral pencil beam model
|
|
378
|
+
self._choose_lateral_model()
|
|
379
|
+
|
|
380
|
+
# Toggles correction of small difference of current SSD to distance used
|
|
381
|
+
# in generation of base data (e.g. phantom surface at isocenter)
|
|
382
|
+
|
|
383
|
+
# TODO: this is a dummy. bio_param not implemented yet...
|
|
384
|
+
self.bio_param = {"bioOpt": False}
|
|
385
|
+
|
|
386
|
+
# Omit field checks of fit_air_offset and BAMStoIsoDist as validated through machine model
|
|
387
|
+
|
|
388
|
+
# biology
|
|
389
|
+
if hasattr(self, "_constant_rbe") and not (self._constant_rbe is None):
|
|
390
|
+
dij["RBE"] = self._constant_rbe
|
|
391
|
+
|
|
392
|
+
# TODO: (Comment from matlab): This is clumsy and needs to be changed with the biomodel
|
|
393
|
+
# update
|
|
394
|
+
if self.bio_param["bioOpt"]:
|
|
395
|
+
self.calc_bio_dose = True
|
|
396
|
+
|
|
397
|
+
# Load biologicla base data if needed
|
|
398
|
+
if self.calc_bio_dose:
|
|
399
|
+
dij = self._load_biological_kernel(cst, dij) # TODO: Not fully implemented yet
|
|
400
|
+
# allocate alpha and beta dose container and sparse matrices in the dij struct,
|
|
401
|
+
# for more informations see corresponding method
|
|
402
|
+
dij = self._allocate_bio_dose_container(dij) # TODO: Not fully implemented yet
|
|
403
|
+
|
|
404
|
+
# Allocate LET containner and let sparse matrix in dij struct
|
|
405
|
+
if self.calc_let:
|
|
406
|
+
if self._machine.has_let_kernel:
|
|
407
|
+
dij = self._allocate_let_container(dij)
|
|
408
|
+
else:
|
|
409
|
+
logger.warning(
|
|
410
|
+
"No LET data found in machine data. LET calculation will be skipped."
|
|
411
|
+
)
|
|
412
|
+
self.calc_let = False
|
|
413
|
+
|
|
414
|
+
self._effective_lateral_cutoff = self.geometric_lateral_cutoff
|
|
415
|
+
|
|
416
|
+
return dij
|
|
417
|
+
|
|
418
|
+
def _init_beam(
|
|
419
|
+
self, dij: dict, ct: CT, cst: StructureSet, stf: SteeringInformation, i
|
|
420
|
+
) -> dict:
|
|
421
|
+
"""
|
|
422
|
+
Extends the inherited method with particle-specific initialization.
|
|
423
|
+
|
|
424
|
+
Parameters
|
|
425
|
+
----------
|
|
426
|
+
dij : dict
|
|
427
|
+
The dose influence matrix dictionary.
|
|
428
|
+
ct : CT
|
|
429
|
+
The CT object.
|
|
430
|
+
_cst : StructureSet
|
|
431
|
+
The structure set object. Unused here
|
|
432
|
+
stf : SteeringInformation
|
|
433
|
+
The steering information object.
|
|
434
|
+
i : int
|
|
435
|
+
Index of the beam.
|
|
436
|
+
|
|
437
|
+
Returns
|
|
438
|
+
-------
|
|
439
|
+
dict
|
|
440
|
+
Updated Beam Information dictionary.
|
|
441
|
+
"""
|
|
442
|
+
beam_info = super()._init_beam(dij, ct, cst, stf, i)
|
|
443
|
+
|
|
444
|
+
# Sanity Check
|
|
445
|
+
assert isinstance(self._machine, IonAccelerator)
|
|
446
|
+
|
|
447
|
+
# Assuming currBeam is part of beam_info
|
|
448
|
+
curr_beam = beam_info["beam"]
|
|
449
|
+
|
|
450
|
+
# Find max energy
|
|
451
|
+
max_energy = max(
|
|
452
|
+
beamlet["energy"] for ray in curr_beam["rays"] for beamlet in ray["beamlets"]
|
|
453
|
+
)
|
|
454
|
+
|
|
455
|
+
max_energy_ix = self._machine.get_energy_index(max_energy, 4)
|
|
456
|
+
|
|
457
|
+
max_energy_kernel = self._machine.get_kernel_by_index(max_energy_ix)
|
|
458
|
+
|
|
459
|
+
# Find minimum range shifter equivalent thickness
|
|
460
|
+
min_ra_shi = min(
|
|
461
|
+
beamlet["range_shifter"]["eq_thickness"]
|
|
462
|
+
for ray in curr_beam["rays"]
|
|
463
|
+
for beamlet in ray["beamlets"]
|
|
464
|
+
)
|
|
465
|
+
rad_depth_offset = max_energy_kernel.offset + min_ra_shi
|
|
466
|
+
|
|
467
|
+
# Apply limit in depth
|
|
468
|
+
sub_select_ix = [
|
|
469
|
+
rD < (max_energy_kernel.depths[-1] - rad_depth_offset)
|
|
470
|
+
for rD in beam_info["rad_depths"]
|
|
471
|
+
]
|
|
472
|
+
|
|
473
|
+
beam_info["valid_coords"] = [
|
|
474
|
+
np.array(
|
|
475
|
+
[
|
|
476
|
+
True if ss & vc else False
|
|
477
|
+
for ss, vc in zip(sub_select_ix[0], beam_info["valid_coords"])
|
|
478
|
+
]
|
|
479
|
+
)
|
|
480
|
+
] # list so that there are multiple scen
|
|
481
|
+
beam_info["valid_coords_all"] = np.any(np.column_stack(beam_info["valid_coords"]), axis=1)
|
|
482
|
+
|
|
483
|
+
# Precompute CutOff
|
|
484
|
+
logger.info("Calculating lateral cutoffs for beam %d...", i)
|
|
485
|
+
t_start = time.time()
|
|
486
|
+
self._calc_lateral_particle_cut_off(self.dosimetric_lateral_cutoff, beam_info)
|
|
487
|
+
t_elapsed = time.time() - t_start
|
|
488
|
+
logger.info("Done in %f seconds.", t_elapsed)
|
|
489
|
+
|
|
490
|
+
return beam_info
|
|
491
|
+
|
|
492
|
+
def _load_biological_kernel(self, _cst: StructureSet, dij: dict[str, Any]):
|
|
493
|
+
"""
|
|
494
|
+
Load / organize biological kernel data from the machine data and
|
|
495
|
+
store meta information in
|
|
496
|
+
the dose influence matrix dictionary.
|
|
497
|
+
|
|
498
|
+
Parameters
|
|
499
|
+
----------
|
|
500
|
+
_cst : StructureSet
|
|
501
|
+
The structure set object.
|
|
502
|
+
dij : dict
|
|
503
|
+
The dose influence matrix dictionary.
|
|
504
|
+
|
|
505
|
+
Returns
|
|
506
|
+
-------
|
|
507
|
+
dict
|
|
508
|
+
The updated dose influence matrix dictionary with biological information.
|
|
509
|
+
"""
|
|
510
|
+
logger.warning(
|
|
511
|
+
"Biological Kernel not implemented yet. "
|
|
512
|
+
"Biological dose calculation will not honor tissue settings."
|
|
513
|
+
)
|
|
514
|
+
return dij
|
|
515
|
+
|
|
516
|
+
def _allocate_bio_dose_container(self, dij: dict[str, Any]):
|
|
517
|
+
"""
|
|
518
|
+
Allocate space for container used in LET calculation.
|
|
519
|
+
|
|
520
|
+
Parameters
|
|
521
|
+
----------
|
|
522
|
+
dij : dict
|
|
523
|
+
The dose influence matrix dictionary.
|
|
524
|
+
|
|
525
|
+
Returns
|
|
526
|
+
-------
|
|
527
|
+
dict
|
|
528
|
+
The updated dose influence matrix dictionary with LET containers allocated.
|
|
529
|
+
"""
|
|
530
|
+
|
|
531
|
+
if self._machine.has_alpha_beta_kernels:
|
|
532
|
+
dij = self._allocate_quantity_matrices(dij, ["alpha_dose", "sqrt_beta_dose"])
|
|
533
|
+
else:
|
|
534
|
+
warnings.warn(
|
|
535
|
+
"Biological kernels not available. Biological dose will not be calculated."
|
|
536
|
+
)
|
|
537
|
+
|
|
538
|
+
return dij
|
|
539
|
+
|
|
540
|
+
def _allocate_let_container(self, dij):
|
|
541
|
+
"""
|
|
542
|
+
Allocate space for container used in LET calculation.
|
|
543
|
+
|
|
544
|
+
Parameters
|
|
545
|
+
----------
|
|
546
|
+
dij : dict
|
|
547
|
+
The dose influence matrix dictionary.
|
|
548
|
+
|
|
549
|
+
Returns
|
|
550
|
+
-------
|
|
551
|
+
dict
|
|
552
|
+
The updated dose influence matrix dictionary with LET containers allocated.
|
|
553
|
+
"""
|
|
554
|
+
# Get MatRad Config instance for displaying warnings
|
|
555
|
+
|
|
556
|
+
if self._machine.has_let_kernel:
|
|
557
|
+
dij = self._allocate_quantity_matrices(dij, ["let_dose"])
|
|
558
|
+
else:
|
|
559
|
+
warnings.warn("LET not available in the machine data. LET will not be calculated.")
|
|
560
|
+
|
|
561
|
+
return dij
|
|
562
|
+
|
|
563
|
+
def _calc_lateral_particle_cut_off(self, cut_off_level, stf_element):
|
|
564
|
+
# Sanity Checks
|
|
565
|
+
assert isinstance(self._machine, IonAccelerator)
|
|
566
|
+
|
|
567
|
+
if len(stf_element) > 1 and not isinstance(stf_element, dict):
|
|
568
|
+
raise ValueError(
|
|
569
|
+
"CutOff can only be precalculated for a single element, "
|
|
570
|
+
"but you provided steering information for multiple beams!"
|
|
571
|
+
)
|
|
572
|
+
|
|
573
|
+
if cut_off_level <= 0.98:
|
|
574
|
+
logger.warning(
|
|
575
|
+
"A lateral cut off below 0.98 may result in an inaccurate dose calculation"
|
|
576
|
+
)
|
|
577
|
+
|
|
578
|
+
if cut_off_level < 0 or cut_off_level > 1:
|
|
579
|
+
warnings.warn("Lateral cutoff is out of range - using default cut off of 0.99")
|
|
580
|
+
cut_off_level = 0.99
|
|
581
|
+
|
|
582
|
+
# conversion factor from kernel units (MeV cm^2/g per primary) to Gy mm^2 per 1e6 primaries
|
|
583
|
+
# TODO: this factor should probably be in the machine data and translate to MU
|
|
584
|
+
conversion_factor = 1.6021766208e-02
|
|
585
|
+
|
|
586
|
+
# Define some variables needed for the cutoff calculation
|
|
587
|
+
v_x = np.concatenate(([0], np.logspace(-1, 3, 1200))) # [mm]
|
|
588
|
+
|
|
589
|
+
# Integration steps
|
|
590
|
+
r_mid = 0.5 * (v_x[:-1] + v_x[1:]) # [mm]
|
|
591
|
+
dr = np.diff(v_x)
|
|
592
|
+
radial_dist_sq = r_mid**2
|
|
593
|
+
|
|
594
|
+
# Number of depth points for which a lateral cutoff is determined
|
|
595
|
+
num_depth_val = 35
|
|
596
|
+
|
|
597
|
+
# Extract SSD for each bixel
|
|
598
|
+
v_ssd = np.ones(
|
|
599
|
+
len(
|
|
600
|
+
[
|
|
601
|
+
beamlet["energy"]
|
|
602
|
+
for ray in stf_element["beam"]["rays"]
|
|
603
|
+
for beamlet in ray["beamlets"]
|
|
604
|
+
]
|
|
605
|
+
)
|
|
606
|
+
)
|
|
607
|
+
|
|
608
|
+
cnt = 0
|
|
609
|
+
# TODO: this can be done more efficiently. (instead of calc len() all the time)
|
|
610
|
+
# TODO: these for loops can be simplified!
|
|
611
|
+
for ray in stf_element["beam"]["rays"]:
|
|
612
|
+
len_ray_energy = len([beamlet["energy"] for beamlet in ray["beamlets"]])
|
|
613
|
+
v_ssd[cnt : cnt + len_ray_energy] = ray["SSD"]
|
|
614
|
+
# TODO: whats the purpose of this? in matRad it counts the len(v_ssd)+1 for some reason
|
|
615
|
+
cnt += len_ray_energy
|
|
616
|
+
|
|
617
|
+
# Setup energy, focus index, sigma look up table - only consider unique rows
|
|
618
|
+
energy_sigma_lut, ix_unique = np.unique(
|
|
619
|
+
np.column_stack(
|
|
620
|
+
(
|
|
621
|
+
[
|
|
622
|
+
beamlet["energy"]
|
|
623
|
+
for ray in stf_element["beam"]["rays"]
|
|
624
|
+
for beamlet in ray["beamlets"]
|
|
625
|
+
],
|
|
626
|
+
[
|
|
627
|
+
beamlet["focus_ix"]
|
|
628
|
+
for ray in stf_element["beam"]["rays"]
|
|
629
|
+
for beamlet in ray["beamlets"]
|
|
630
|
+
],
|
|
631
|
+
v_ssd,
|
|
632
|
+
)
|
|
633
|
+
),
|
|
634
|
+
axis=0,
|
|
635
|
+
return_index=True,
|
|
636
|
+
)
|
|
637
|
+
# add extra dimension for energy_sigma_lut
|
|
638
|
+
# TODO: there must be a simpler way to do this
|
|
639
|
+
energy_sigma_lut = np.hstack(
|
|
640
|
+
(energy_sigma_lut, np.full((len(energy_sigma_lut), 1), np.nan))
|
|
641
|
+
)
|
|
642
|
+
|
|
643
|
+
range_shifter_lut = [
|
|
644
|
+
beamlet["range_shifter"]
|
|
645
|
+
for ray in stf_element["beam"]["rays"]
|
|
646
|
+
for beamlet in ray["beamlets"]
|
|
647
|
+
]
|
|
648
|
+
range_shifter_lut = [range_shifter_lut[i] for i in ix_unique]
|
|
649
|
+
|
|
650
|
+
# Find the largest initial beam width considering focus index, SSD and range shifter
|
|
651
|
+
# for each individual energy
|
|
652
|
+
for i in range(len(energy_sigma_lut)):
|
|
653
|
+
|
|
654
|
+
# find index of maximum used energy (round to keV for numerical reasons)
|
|
655
|
+
energy_ix = self._machine.get_energy_index(energy_sigma_lut[i, 0], 4)
|
|
656
|
+
# Get the kernel entry
|
|
657
|
+
kernel = self._machine.get_kernel_by_index(energy_ix)
|
|
658
|
+
# Get the available beam foci
|
|
659
|
+
foci = self._machine.get_foci_by_index(energy_ix)
|
|
660
|
+
|
|
661
|
+
focus_ix = int(energy_sigma_lut[i, 1])
|
|
662
|
+
focus = foci[focus_ix]
|
|
663
|
+
|
|
664
|
+
sigma_ini = np.interp(energy_sigma_lut[i, 2], focus.dist, focus.sigma)
|
|
665
|
+
|
|
666
|
+
sigma_ini_sq = sigma_ini**2
|
|
667
|
+
|
|
668
|
+
# Consider range shifter for protons if applicable
|
|
669
|
+
if (
|
|
670
|
+
self._machine.radiation_mode == "protons"
|
|
671
|
+
and range_shifter_lut[i]["eq_thickness"] > 0
|
|
672
|
+
):
|
|
673
|
+
# TODO: this is not tested yet as only Generic is used
|
|
674
|
+
sigma_rashi = self._calc_sigma_rashi(
|
|
675
|
+
self._machine.energies[energy_ix],
|
|
676
|
+
range_shifter_lut[i],
|
|
677
|
+
energy_sigma_lut[i, 2],
|
|
678
|
+
)
|
|
679
|
+
sigma_ini_sq += sigma_rashi**2
|
|
680
|
+
|
|
681
|
+
energy_sigma_lut[i, 3] = sigma_ini_sq
|
|
682
|
+
|
|
683
|
+
# Find for each individual energy the broadest initial beam width
|
|
684
|
+
unique_energies = np.unique(energy_sigma_lut[:, 0])
|
|
685
|
+
largest_sigma_sq4unique_energies = np.full(len(unique_energies), np.nan)
|
|
686
|
+
ix_max = np.full(len(unique_energies), np.nan)
|
|
687
|
+
for i, energy in enumerate(unique_energies):
|
|
688
|
+
largest_sigma_sq4unique_energies[i] = np.max(
|
|
689
|
+
energy_sigma_lut[energy == energy_sigma_lut[:, 0], 3]
|
|
690
|
+
)
|
|
691
|
+
ix_max[i] = np.argmax(energy_sigma_lut[energy == energy_sigma_lut[:, 0], 3])
|
|
692
|
+
|
|
693
|
+
# Get energy indices for looping
|
|
694
|
+
v_energies_ix = np.where(np.isin(self._machine.energies, unique_energies))[0]
|
|
695
|
+
cnt = 0
|
|
696
|
+
|
|
697
|
+
# Loop over all entries in the machine.data struct
|
|
698
|
+
for energy_ix in v_energies_ix:
|
|
699
|
+
# Get the kernel entry
|
|
700
|
+
kernel = self._machine.get_kernel_by_index(energy_ix)
|
|
701
|
+
|
|
702
|
+
# set default depth cut off - finite value will be set during first iteration
|
|
703
|
+
depth_dose_cut_off = np.inf
|
|
704
|
+
|
|
705
|
+
# Get the current integrated depth dose profile
|
|
706
|
+
idd_org = conversion_factor * kernel.idd
|
|
707
|
+
peak_ix_org = np.argmax(idd_org)
|
|
708
|
+
|
|
709
|
+
# Get indices for which a lateral cutoff should be calculated
|
|
710
|
+
cum_int_energy = cumulative_trapezoid(idd_org, kernel.depths, initial=0)
|
|
711
|
+
|
|
712
|
+
peak_tail_relation = 0.5
|
|
713
|
+
num_depth_val_to_peak = int(np.ceil(num_depth_val * peak_tail_relation))
|
|
714
|
+
num_depth_val_tail = int(np.ceil(num_depth_val * (1 - peak_tail_relation)))
|
|
715
|
+
energy_steps_to_peak = cum_int_energy[peak_ix_org] / num_depth_val_to_peak
|
|
716
|
+
energy_steps_tail = (
|
|
717
|
+
cum_int_energy[-1] - cum_int_energy[peak_ix_org]
|
|
718
|
+
) / num_depth_val_tail
|
|
719
|
+
|
|
720
|
+
v_energy_steps = np.unique(
|
|
721
|
+
np.concatenate(
|
|
722
|
+
(
|
|
723
|
+
np.arange(0, cum_int_energy[peak_ix_org], energy_steps_to_peak),
|
|
724
|
+
[cum_int_energy[peak_ix_org]],
|
|
725
|
+
np.arange(
|
|
726
|
+
cum_int_energy[peak_ix_org + 1], cum_int_energy[-1], energy_steps_tail
|
|
727
|
+
),
|
|
728
|
+
[cum_int_energy[-1]],
|
|
729
|
+
)
|
|
730
|
+
)
|
|
731
|
+
)
|
|
732
|
+
|
|
733
|
+
cum_int_energy, ix = np.unique(cum_int_energy, return_index=True)
|
|
734
|
+
|
|
735
|
+
depth_values = np.interp(v_energy_steps, cum_int_energy, kernel.depths[ix])
|
|
736
|
+
idd = conversion_factor * np.interp(depth_values, kernel.depths, kernel.idd)
|
|
737
|
+
|
|
738
|
+
cnt += 1
|
|
739
|
+
|
|
740
|
+
# Create a default cutoff and store it in the kernel
|
|
741
|
+
kernel.lateral_cut_off = LateralCutOff(
|
|
742
|
+
comp_fac=1.0, depths=depth_values, cut_off=np.inf * np.ones_like(depth_values)
|
|
743
|
+
)
|
|
744
|
+
|
|
745
|
+
# TODO: this could probably be done for all depths with one calculation without a loop
|
|
746
|
+
for j, current_depth in enumerate(depth_values):
|
|
747
|
+
# If there's no cut-off set, we do not need to find it. Set it to infinity
|
|
748
|
+
if cut_off_level == 1:
|
|
749
|
+
continue
|
|
750
|
+
else:
|
|
751
|
+
# Create a dummy bixel calculating radial dose distribution for the current
|
|
752
|
+
# depth
|
|
753
|
+
bixel = {
|
|
754
|
+
"energy_ix": energy_ix,
|
|
755
|
+
"kernel": kernel,
|
|
756
|
+
"radial_dist_sq": radial_dist_sq,
|
|
757
|
+
"sigma_ini_sq": largest_sigma_sq4unique_energies[
|
|
758
|
+
cnt - 1
|
|
759
|
+
], # TODO: check if this result is correct (rounded but may be right)
|
|
760
|
+
"rad_depths": (current_depth + kernel.offset)
|
|
761
|
+
* np.ones_like(radial_dist_sq),
|
|
762
|
+
"v_tissue_index": np.ones_like(radial_dist_sq),
|
|
763
|
+
"v_alpha_x": 0.5 * np.ones_like(radial_dist_sq),
|
|
764
|
+
"v_beta_x": 0.05 * np.ones_like(radial_dist_sq),
|
|
765
|
+
"sub_ray_ix": np.ones_like(radial_dist_sq, dtype=bool),
|
|
766
|
+
"ix": np.arange(len(radial_dist_sq)),
|
|
767
|
+
"rad_depth_offset": 0,
|
|
768
|
+
"add_sigma_sq": 0,
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
bixel = self._calc_particle_bixel(bixel)
|
|
772
|
+
dose_r = bixel["physical_dose"]
|
|
773
|
+
|
|
774
|
+
# Do an integration check that the radial dose integrates to the tabulated
|
|
775
|
+
# integrated depth dose
|
|
776
|
+
cum_area = np.cumsum(2 * np.pi * r_mid * dose_r * dr)
|
|
777
|
+
relative_tolerance = 0.5 # in [%]
|
|
778
|
+
|
|
779
|
+
if abs((cum_area[-1] / idd[j]) - 1) * 100 > relative_tolerance:
|
|
780
|
+
warnings.warn("Shell integration in cut-off calculation is inconsistent!")
|
|
781
|
+
|
|
782
|
+
# obtain the cut-off compensation factor dending on the cut-off method
|
|
783
|
+
if self.cut_off_method == "integral":
|
|
784
|
+
ix = (cum_area >= idd[j] * cut_off_level).argmax()
|
|
785
|
+
kernel.lateral_cut_off.comp_fac = cut_off_level**-1
|
|
786
|
+
elif self.cut_off_method == "relative":
|
|
787
|
+
ix = (dose_r <= (1 - cut_off_level) * np.max(dose_r)).argmax()
|
|
788
|
+
rel_fac = cum_area[ix] / cum_area[-1]
|
|
789
|
+
kernel.lateral_cut_off.comp_fac = rel_fac**-1
|
|
790
|
+
else:
|
|
791
|
+
raise ValueError(
|
|
792
|
+
"Invalid Cutoff Method. Must be 'integral' or 'relative'!"
|
|
793
|
+
)
|
|
794
|
+
# Nothing was cut-off -> warn the user
|
|
795
|
+
if ix == len(cum_area):
|
|
796
|
+
depth_dose_cut_off = np.inf
|
|
797
|
+
warnings.warn("Couldn't find lateral cut off!")
|
|
798
|
+
else:
|
|
799
|
+
depth_dose_cut_off = r_mid[ix]
|
|
800
|
+
|
|
801
|
+
kernel.lateral_cut_off.cut_off[j] = depth_dose_cut_off
|
|
802
|
+
|
|
803
|
+
self._machine.update_kernel_at_index(energy_ix, kernel)
|
|
804
|
+
|
|
805
|
+
def _init_ray(self, beam, j):
|
|
806
|
+
ray = super()._init_ray(beam, j)
|
|
807
|
+
|
|
808
|
+
self._machine = cast(IonAccelerator, self._machine)
|
|
809
|
+
|
|
810
|
+
# Calculate initial sigma for all bixels on the current ray
|
|
811
|
+
# TODO: here [ray] since calc_sigma_ini takes multiple rays (why?)
|
|
812
|
+
ray["sigma_ini"] = self._calc_sigma_ini_on_ray(ray)
|
|
813
|
+
|
|
814
|
+
# Since pyRadPlan's ray cast starts at the skin and base data
|
|
815
|
+
# is generated at some source to phantom distance
|
|
816
|
+
# we can explicitly correct for the nozzle to air WEPL in
|
|
817
|
+
# the current case.
|
|
818
|
+
if self.air_offset_correction:
|
|
819
|
+
nozzle_to_skin = (ray["SSD"] + self._machine.bams_to_iso_dist) - self._machine.sad
|
|
820
|
+
ray["rad_depth_offset"] = 0.0011 * (nozzle_to_skin - self._machine.fit_air_offset)
|
|
821
|
+
else:
|
|
822
|
+
ray["rad_depth_offset"] = 0
|
|
823
|
+
|
|
824
|
+
# Just use tissue classes of voxels found by ray tracer
|
|
825
|
+
# TODO: not tested
|
|
826
|
+
# if self.calc_bio_dose:
|
|
827
|
+
# for s in range(len(self._v_tissue_index)):
|
|
828
|
+
# ray["vtissue_index"][s] = self._v_tissue_index[s][ray["valid_coords"][s], :]
|
|
829
|
+
# ray["valpha_x"][s] = self._v_alpha_x[s][ray["valid_coords"][s]]
|
|
830
|
+
# ray["vbeta_x"][s] = self._v_beta_x[s][ray["valid_coords"][s]]
|
|
831
|
+
|
|
832
|
+
return ray
|
|
833
|
+
|
|
834
|
+
def _extract_single_scenario_ray(self, ray, scen_idx):
|
|
835
|
+
scen_ray = super()._extract_single_scenario_ray(ray, scen_idx)
|
|
836
|
+
# TODO: Add multscen support
|
|
837
|
+
# Gets number of scenario
|
|
838
|
+
scen_num = 1 # self.mult_scen['scenNum'][scen_idx]
|
|
839
|
+
ct_scen = self.mult_scen.linear_mask[0][scen_num]
|
|
840
|
+
|
|
841
|
+
if "vTissueIndex" in scen_ray:
|
|
842
|
+
scen_ray["vTissueIndex"] = scen_ray["vTissueIndex"][ct_scen]
|
|
843
|
+
scen_ray["vAlphaX"] = scen_ray["vAlphaX"][ct_scen]
|
|
844
|
+
scen_ray["vBetaX"] = scen_ray["vBetaX"][ct_scen]
|
|
845
|
+
|
|
846
|
+
return scen_ray
|
|
847
|
+
|
|
848
|
+
def _fill_dij(
|
|
849
|
+
self, bixel, dij, stf, scen_idx, curr_beam_idx, curr_ray_idx, curr_bixel_idx, bixel_counter
|
|
850
|
+
):
|
|
851
|
+
dij = super()._fill_dij(
|
|
852
|
+
bixel, dij, stf, scen_idx, curr_beam_idx, curr_ray_idx, curr_bixel_idx, bixel_counter
|
|
853
|
+
)
|
|
854
|
+
|
|
855
|
+
# Add MU information
|
|
856
|
+
if not self._calc_dose_direct:
|
|
857
|
+
dij["min_mu"][bixel_counter] = bixel["min_mu"]
|
|
858
|
+
dij["max_mu"][bixel_counter] = bixel["max_mu"]
|
|
859
|
+
dij["num_of_particles_per_mu"][bixel_counter] = bixel["num_particles_per_mu"]
|
|
860
|
+
|
|
861
|
+
return dij
|
|
862
|
+
|
|
863
|
+
def _get_lateral_distance_from_dose_cutoff_on_ray(self, ray: dict):
|
|
864
|
+
# Find index of maximum used energy (round to keV for numerical reasons)
|
|
865
|
+
self._machine = cast(IonAccelerator, self._machine)
|
|
866
|
+
|
|
867
|
+
max_energy = max([beamlet["energy"] for beamlet in ray["beamlets"]])
|
|
868
|
+
kernel = self._machine.get_kernel_by_energy(max_energy)
|
|
869
|
+
lat_cut_off = kernel.lateral_cut_off
|
|
870
|
+
|
|
871
|
+
# Get the lateral cutoff distance
|
|
872
|
+
lateral_ray_cut_off = lat_cut_off.cut_off.max()
|
|
873
|
+
|
|
874
|
+
return lateral_ray_cut_off
|
|
875
|
+
|
|
876
|
+
def _calc_sigma_ini_on_ray(self, ray: dict, ssd: np.floating = None):
|
|
877
|
+
"""
|
|
878
|
+
This function evaluates simultaneously the initial sigma of the beam
|
|
879
|
+
for one or more energies.
|
|
880
|
+
|
|
881
|
+
Parameters
|
|
882
|
+
----------
|
|
883
|
+
ray : dict
|
|
884
|
+
The ray data.
|
|
885
|
+
ssd : float
|
|
886
|
+
The source to surface distance. Can be omitted if ray has SSD stored
|
|
887
|
+
|
|
888
|
+
Returns
|
|
889
|
+
-------
|
|
890
|
+
np.ndarray
|
|
891
|
+
The initial sigma for the ray energies
|
|
892
|
+
"""
|
|
893
|
+
|
|
894
|
+
if ssd is None:
|
|
895
|
+
if "SSD" not in ray:
|
|
896
|
+
raise ValueError("SSD not provided and not stored in ray data!")
|
|
897
|
+
ssd = ray["SSD"]
|
|
898
|
+
|
|
899
|
+
# energies on ray
|
|
900
|
+
sigma_ini = np.zeros((len(ray["beamlets"]),), dtype=np.float64)
|
|
901
|
+
for i, beamlet in enumerate(ray["beamlets"]):
|
|
902
|
+
# obtain focus
|
|
903
|
+
energy = beamlet["energy"]
|
|
904
|
+
focus_ix = beamlet["focus_ix"]
|
|
905
|
+
sigma_ini[i] = self._calc_sigma_ini_focus_ix(energy, focus_ix, ssd)
|
|
906
|
+
return sigma_ini
|
|
907
|
+
|
|
908
|
+
def _calc_sigma_ini_focus_ix(
|
|
909
|
+
self, energy: np.float64, focus_ix: int, ssd: np.floating
|
|
910
|
+
) -> np.float64:
|
|
911
|
+
"""
|
|
912
|
+
This function evaluates the initial sigma of the beam for a given
|
|
913
|
+
energy and focus index.
|
|
914
|
+
|
|
915
|
+
Parameters
|
|
916
|
+
----------
|
|
917
|
+
energy : np.float64
|
|
918
|
+
The energy of the beam.
|
|
919
|
+
focus_ix : int
|
|
920
|
+
The focus index.
|
|
921
|
+
ssd : np.floating
|
|
922
|
+
The source to surface distance.
|
|
923
|
+
|
|
924
|
+
Returns
|
|
925
|
+
-------
|
|
926
|
+
np.float64
|
|
927
|
+
The initial sigma for the given energy and focus index.
|
|
928
|
+
"""
|
|
929
|
+
focus = self._machine.foci[energy][focus_ix]
|
|
930
|
+
interpolator = interp1d(focus.dist, focus.sigma, fill_value="extrapolate")
|
|
931
|
+
return interpolator(ssd)
|
|
932
|
+
|
|
933
|
+
def _calc_sigma_rashi(self, bd_entry, range_shifter: dict, ssd: float):
|
|
934
|
+
# Distance of range shifter to patient surface
|
|
935
|
+
rashi_dist = ssd - range_shifter["sourceRashiDistance"]
|
|
936
|
+
|
|
937
|
+
# Convert to cm
|
|
938
|
+
z_rs_cm = rashi_dist / 10.0 # [cm]
|
|
939
|
+
t = range_shifter["eqThickness"] / 10.0 # [cm]
|
|
940
|
+
|
|
941
|
+
# Constants
|
|
942
|
+
a1 = 0.21 # [1]
|
|
943
|
+
a2 = 0.77 # [1]
|
|
944
|
+
c0 = 0.0191027 # [cm]
|
|
945
|
+
c1 = 0.0204539 # [1]
|
|
946
|
+
alpha = 0.0022 # [cm MeV ^ (-p)]
|
|
947
|
+
p = 1.77 # [1]
|
|
948
|
+
|
|
949
|
+
# Determine range
|
|
950
|
+
if "range" in bd_entry:
|
|
951
|
+
range_in_water = bd_entry["range"]
|
|
952
|
+
else:
|
|
953
|
+
energy = bd_entry["energy"]
|
|
954
|
+
range_in_water = alpha * (energy**p)
|
|
955
|
+
|
|
956
|
+
# Check if valid computation possible or range shifter too thick
|
|
957
|
+
if t / range_in_water >= 0.95:
|
|
958
|
+
raise ValueError(
|
|
959
|
+
"Computation of range shifter sigma invalid. Range shifter is too thick."
|
|
960
|
+
)
|
|
961
|
+
|
|
962
|
+
# Improved HONG's Formula [1, Eq. 21]
|
|
963
|
+
s = t / range_in_water
|
|
964
|
+
sigma_t = (a1 * s + a2 * s**2) * (c0 + c1 * range_in_water)
|
|
965
|
+
|
|
966
|
+
# Constants for further calculations
|
|
967
|
+
c1 = 13.6 # MeV
|
|
968
|
+
c2 = 0.038
|
|
969
|
+
lr_water = 36.08 # rad. length [cm]
|
|
970
|
+
lr_pmma = 40.55 # rad. length [cm]
|
|
971
|
+
rsp_pmma = 1.165 # rSP [rel. u.]
|
|
972
|
+
prsf_pmma = np.sqrt(
|
|
973
|
+
rsp_pmma**3
|
|
974
|
+
* lr_water
|
|
975
|
+
/ lr_pmma
|
|
976
|
+
* (1 + 2 * c2 * np.log(rsp_pmma * lr_water / lr_pmma))
|
|
977
|
+
)
|
|
978
|
+
|
|
979
|
+
# Calculate F1 and F2
|
|
980
|
+
f1_part1 = (2 * c1**2 * alpha ** (2 / p)) / (4 * lr_pmma * (2 / p - 1))
|
|
981
|
+
f1_part2 = ((1 - s) ** (2 - 2 / p) - 1) / (2 / p - 2) - s
|
|
982
|
+
f1_part3 = range_in_water ** (2 - 2 / p)
|
|
983
|
+
f1 = f1_part1 * f1_part2 * f1_part3
|
|
984
|
+
|
|
985
|
+
f2_part1 = (c1**2 * alpha ** (2 / p)) / (4 * lr_pmma * (2 / p - 1))
|
|
986
|
+
f2_part2 = (((1 - s) ** (1 - 2 / p) - 1)) / 1
|
|
987
|
+
f2_part3 = range_in_water ** (1 - 2 / p)
|
|
988
|
+
f2 = f2_part1 * f2_part2 * f2_part3
|
|
989
|
+
|
|
990
|
+
sigma_proj_sq = prsf_pmma**2 * (
|
|
991
|
+
sigma_t**2 + f1 * z_rs_cm * rsp_pmma + f2 * (z_rs_cm * rsp_pmma) ** 2
|
|
992
|
+
) # [cm ^ 2]
|
|
993
|
+
|
|
994
|
+
# Convert to mm
|
|
995
|
+
sigma_rashi = 10.0 * np.sqrt(sigma_proj_sq) # [mm]
|
|
996
|
+
|
|
997
|
+
return sigma_rashi
|
|
998
|
+
|
|
999
|
+
def round2(self, a: np.floating, b: int) -> np.floating:
|
|
1000
|
+
"""
|
|
1001
|
+
Helper function for energy selection.
|
|
1002
|
+
|
|
1003
|
+
Parameters
|
|
1004
|
+
----------
|
|
1005
|
+
a : np.floating
|
|
1006
|
+
The number to round.
|
|
1007
|
+
b : int
|
|
1008
|
+
The number of decimal places to round to.
|
|
1009
|
+
|
|
1010
|
+
Returns
|
|
1011
|
+
-------
|
|
1012
|
+
np.floating
|
|
1013
|
+
The rounded number.
|
|
1014
|
+
"""
|
|
1015
|
+
return np.round(a * 10**b) / 10**b
|