Monte Carlo Simulation Tools
A collection of useful functions for Monte Carlo simulations, implemented in the fredtools.MonteCarlo subpackage.
FRED Monte Carlo
- fredtools.setFieldsFolderStruct(folderPath: PathLike | str, RNfileName: PathLike | str, folderName: str = 'FRED', overwrite: bool = False, displayInfo: bool = False) PathLike | str
Create a folder structure for each field in the treatment plan.
The function creates a folder structure in a given folderPath for each field separately. The folder structure is in the form:
folderPath/folderName:
/ 1_Field2
/ 2_Field3
/ 3_Field1
…
The number at the beginning of the folder name is the delivery number and the number after Field is the ID of the field.
- Parameters:
folderPath (path) – Path to a folder to create the structure.
RNfileName (path) – Path to RN dicom file of a treatment plan.
folderName (string, optional) – Name of the folder to create. (def. ‘FRED’)
overwrite (bool, optional) – Determine if the folder should be overwritten. If true, then all the data in the existing folder will be removed. (def. False)
displayInfo (bool, optional) – Displays a summary of the function results. (def. False)
- Returns:
Path to created folder structure.
- Return type:
path
- Raises:
FileNotFoundError – If the folder given by folderPath does not exist.
FileExistsError – If the simulation folder already exists and overwrite is False.
- fredtools.readFREDStat(fileName: PathLike | str, displayInfo: bool = False) DottedDict
Read FRED simulation statistics information from the log file.
The function reads some statistics information from a FRED run.out logfile. If some information is unavailable, then a NaN or numpy.np.nan is returned.
- Parameters:
fileName (string) – A string path to FRED output logfile (usually in out/log/run.out)
displayInfo (bool, optional) – Displays a summary of the function results. (def. False)
- Returns:
A dictionary with the read data.
- Return type:
DottedDict
- Raises:
FileNotFoundError – If the file given by fileName does not exist.
Notes
Keys suffixed with _s hold values in seconds, keys suffixed with _us in microseconds, and keys suffixed with _prim_s in primaries per second.
- fredtools.getFREDVersions() List[str]
List the installed FRED versions.
The function lists the FRED versions installed on the machine.
- Returns:
List of FRED versions.
- Return type:
List of strings
- Raises:
RuntimeError – If the FRED executable reports an error when listing the versions.
See also
checkFREDVersioncheck if the FRED version is installed.
- fredtools.checkFREDVersion(version: str) bool
Check if the FRED version is installed.
The function validates if the version of FRED, given by the parameter is installed on the machine.
- Parameters:
version (str) – Version to be checked. Usually it is in format ‘#.#.#’, but can be any string, e.g. ‘devel’.
- Returns:
True if the version is installed.
- Return type:
bool
- Raises:
ValueError – If version is not a string.
See also
getFREDVersionslist the installed FRED versions.
- fredtools.getFREDVersion(version: str = '') str
Get the full FRED version name.
The function checks if the version of FRED is installed and returns its full version name.
- Parameters:
version (str, optional) – Version in format #.#.#. An empty string means the currently active FRED version. (def. ‘’)
- Returns:
Full version name returned by FRED.
- Return type:
str
- Raises:
ValueError – If the requested FRED version is not installed on the machine.
RuntimeError – If the FRED executable reports an error when checking the version.
See also
getFREDVersionslist the installed FRED versions.
- fredtools.runFRED(fileName: PathLike | str, version: str = '', params: Iterable[str] = [], displayInfo: bool = False) List[str]
Run FRED simulation.
The function runs FRED simulation defined by the FRED input file name in the given FRED version.
- Parameters:
fileName (path) – Path string to FRED input file. Usually, it is called fred.inp.
version (str, optional) – Version of FRED in format #.#.#. If no version is given then the current version installed is used. (def. “”)
params (str or list of strings, optional) – Additional parameters to FRED engine, for instance [“-C”, “-V5”, “-nogpu”] etc. (def. [])
displayInfo (bool, optional) – Displays a summary of the function results. (def. False)
- Returns:
Standard output of the FRED subprocess in the form of a list of string lines.
- Return type:
list of str
- Raises:
ValueError – If the requested FRED version is not installed on the machine or if the FRED input file given by fileName does not exist.
See also
readFREDStatread FRED simulation statistics information from logfile.
checkFREDVersioncheck if the FRED version is installed.
getFREDVersionslist the installed FRED versions.
Beam model
- fredtools.readBeamModel(fileName: PathLike | str) dict
Read beam model from a YAML file.
The function reads the beam model parameters from a YAML beam model file. The beam model must be defined as a dictionary. All the pandas DataFrame-like lists will be converted to pandas.DataFrame objects, whereas any items in square brackets will be converted to a numpy array object.
- Parameters:
fileName (string) – A string path to beam model YAML file.
- Returns:
A dictionary with the beam model and required keys.
- Return type:
dict
See also
writeBeamModelwrite beam model to YAML file.
interpolateBeamModelinterpolate all beam model parameters for a given nominal energy.
- fredtools.writeBeamModel(beamModel: dict, fileName: PathLike | str) None
Write beam model to YAML.
The function writes the beam model parameters in YAML format for a beam model file. The beam model must be defined as a dictionary. If a value of a given key is a pandas DataFrame, it will be saved to a nicely formatted table.
- Parameters:
beamModel (dict) – Beam model defined as a dictionary with the required keys.
fileName (string) – A string path to beam model YAML file. It is recommended to use .bm file extension.
See also
readBeamModelread beam model from YAML beam model file.
interpolateBeamModelinterpolate all beam model parameters for a given nominal energy.
- fredtools.interpolateBeamModel(beamModel: DataFrame, nomEnergy: int | float | number | Iterable[int | float | number], interpolation: Literal['linear', 'spline', 'nearest'] = 'linear', splineOrder: Annotated[int, FieldInfo(annotation=NoneType, required=True, metadata=[Strict(strict=True), Ge(ge=0), Le(le=5)])] = 3) DataFrame
Interpolate beam model for a given nominal energy.
The function interpolates all the beam model parameters for a given nominal energies which must be in range of the defined nominal energies in the beam model. The possible interpolation methods are ‘nearest’, ‘linear’ or ‘spline’ with order in range 0-5.
- Parameters:
beamModel (DataFrame) – Beam model defined as a pandas DataFrame object.
nomEnergy (scalar or list) – The list of nominal energies to interpolate the beam model parameters for.
interpolation ({'linear', 'nearest', 'spline'}, optional) – Determine the interpolation method. (def. ‘linear’)
splineOrder (int, optional) – Order of spline interpolation. Must be in range 0-5. (def. 3)
- Returns:
Pandas DataFrame with all parameters interpolated.
- Return type:
Pandas DataFrame
- Raises:
ValueError – If the interpolation method cannot be recognised, if the spline order is not in range 0-5, or if any of the given nominal energies is outside the beam model nominal energy range.
See also
readBeamModelread beam model from YAML beam model file.
writeBeamModelwrite beam model to YAML file.
- fredtools.calcRaysVectors(targetPoint: Iterable[int | float | number] | Iterable[Iterable[int | float | number]], SAD: Iterable[int | float | number]) Tuple[ndarray[tuple[Any, ...], dtype[_ScalarT]], ndarray[tuple[Any, ...], dtype[_ScalarT]]]
Calculate rays positions and direction versors.
The function calculates the ray position and direction versor from the target position. The target point can be a 3-element iterable or Nx3 iterable for multiple points. The SAD parameter describes the absolute distances of the spreading devices in order [X, Y]. It does not matter if the first divergence is in X or Y, the function takes this information from the distances, but the order [X,Y] must be preserved.
- Parameters:
targetPoint (3-element or Nx3 iterable) – The position of a single target point or positions of N target points.
SAD (2-element iterable) – The absolute distances of the spreading devices in order [X,Y].
- Returns:
A tuple with two Nx3 arrays, where the first is the ray position and the second is the ray direction versor.
- Return type:
(Nx3 numpy.array, Nx3 numpy.array)
- Raises:
AttributeError – If targetPoint is not an iterable of shape Nx3 or if SAD is not a 2-element iterable.
- class fredtools.beamModel
Container describing a pencil beam scanning beam model.
The class stores a complete description of a beam model, including:
beam model description fields: name, creationTime, radiationType (one of ‘proton’, ‘carbon’ or ‘helium’), siteName, machineName, machineVendor, machineModel and free-text notes;
machine parameters: spreadingDeviceDistance, i.e. the absolute distances of the spreading devices in mm in the order [X, Y], and sourceToAxisDistance (SAD) in mm;
energy model: a pandas DataFrame (energyModel), indexed by the nominal energy nomEnergy, with the columns ‘Energy’ and ‘dEnergy’ (mean energy and energy spread in MeV), ‘aX’, ‘bX’, ‘cX’, ‘aY’, ‘bY’, ‘cY’ (sigma squared model parameters of the beam envelope in X and Y) and ‘scalingFactor’ (dosimetric calibration in p/MU), together with the interpolation method (‘linear’, ‘nearest’ or ‘spline’) and splineOrder used for interpolation;
range shifter model: a pandas DataFrame (rsModel) with at least the columns ‘name’, ‘L’ and ‘material’;
nozzle materials: a pandas DataFrame (materials) with at least the columns ‘name’, ‘density’ and ‘basedOn’.
A beam model can be loaded from a YAML file with the fromYAML method or from a pickle file with the fromPickle class method, and saved to a pickle file with the toPickle method. The energy model can be interpolated for any nominal energy with the interpolateBeamModel method, whereas the getSigma and getGateParams methods calculate the beam envelope and GATE/OpenGATE beam parameters, respectively. The displayInfo method logs a summary of the beam model.
- Raises:
AttributeError – Raised by the property setters when an invalid value is assigned, for instance a wrong type of name, creationTime, siteName, machineName, machineVendor, machineModel, spreadingDeviceDistance, sourceToAxisDistance, interpolation or splineOrder, or when the DataFrame assigned to energyModel, rsModel or materials does not contain the required columns.
- property creationTime: str
Returns the creation time of the beam model.
- displayInfo() None
Displays information about the beam model.
- property energyModel: DataFrame
Returns the energy model of the beam model.
- classmethod fromPickle(fileName: PathLike | str) Self
Loads the beam model from a pickle file.
- Parameters:
fileName (PathLike) – The name of the file to load the beam model from. The file must be in binary format.
- Returns:
An instance of the beamModel class loaded from the pickle file.
- Return type:
Self
- Raises:
FileNotFoundError – If the file does not exist.
TypeError – If the file does not contain a valid beamModel object.
- fromYAML(fileName: PathLike | str) None
Loads the beam model from a YAML file.
- Parameters:
fileName (PathLike) – The path to the YAML file containing the beam model.
- Raises:
AttributeError – If the energy model imported from the YAML file does not contain the required columns.
- getGateParams(sourceToAxisDistance: Annotated[float, Ge(ge=0)], nomEnergy: int | float | number | Iterable[int | float | number]) DataFrame
Get the beam parameters for GATE simulation.
This function calculates the beam parameters for GATE simulation based on the source-to-axis distance and nominal energy. According to the GATE documentation, the beam propagation parameters are modelled according to the Fermi-Eyges theory (Techniques of Proton Radiotherapy: Transport Theory B. Gottschalk May 1, 2012), that describes the correlated momentum spread of the particle with 4 parameters (each for x and y direction, assuming a beam directed as z):
sigma: beam size in [X,Y] directions at the beam production point (sourceToAxisDistance)
divergence: beam divergence in [X,Y] directions
emittance: constant area in phase space in [X,Y] directions
convergence: beam convergence in [X,Y] directions
- Parameters:
sourceToAxisDistance (float) – The distance from the beam source to the isocenter in mm.
nomEnergy (float or iterable of floats) – The nominal energy of the beam in MeV or a list of nominal energies.
- Returns:
A DataFrame containing the beam parameters for GATE simulation, indexed by the nominal energy in [MeV], including: - Energy: mean (actual) beam energy in [MeV] - dEnergy: energy spread in [MeV] - sigmaX: beam size in X direction in [mm] - sigmaY: beam size in Y direction in [mm] - thetaX: beam divergence in X direction in [rad] - thetaY: beam divergence in Y direction in [rad] - epsilonX: emittance in X direction in [mm * rad] - epsilonY: emittance in Y direction in [mm * rad] - convergenceX: convergence in X direction (usually True) - convergenceY: convergence in Y direction (usually True) - scalingFactor: scaling factor for the beam model (in [p/MU])
- Return type:
DataFrame
- Raises:
ValueError – If any of the given nominal energies is outside the nominal energy range of the energy model.
- getSigma(distance: int | float | number, nomEnergy: int | float | number | Iterable[int | float | number]) Tuple[int | float | number, int | float | number] | Tuple[List[int | float | number], List[int | float | number]]
Calculate the beam sigma in X and Y at a given distance from the isocenter.
The method calculates the beam envelope, i.e. the beam sigma in X and Y directions, at a given distance from the isocenter, based on the sigma squared model (sigma^2 = a + b*distance + c*distance^2) of the energy model, interpolated for the given nominal energies.
- Parameters:
distance (scalar) – The distance from the isocenter in mm, at which to calculate the beam sigma. The distance is defined along the beam direction with zero at the isocenter, negative values upstream (towards the source) and positive values downstream. For instance, the beam sigma at the source position is obtained for a negative Source-To-Axis Distance, i.e.
distance=-sourceToAxisDistance.nomEnergy (scalar or iterable of scalars) – The nominal energy or energies to calculate the beam sigma for.
- Returns:
A tuple (sigmaX, sigmaY) with the beam sigma in mm in X and Y directions. The elements are scalars if nomEnergy is a scalar, or lists if nomEnergy is an iterable. If the energy model is empty, a warning is logged and the tuple (0, 0) is returned.
- Return type:
tuple of two scalars or tuple of two lists
- Raises:
ValueError – If any of the given nominal energies is outside the nominal energy range of the energy model.
- interpolateBeamModel(nomEnergy: int | float | number | Iterable[int | float | number]) DataFrame
Interpolate the energy model for given nominal energies.
The method interpolates all the parameters of the energy model for the given nominal energies, which must be in the range of the nominal energies defined in the energy model. The interpolation is performed with the method defined by the interpolation property (‘linear’, ‘nearest’ or ‘spline’) and, for splines, with the order defined by the splineOrder property.
- Parameters:
nomEnergy (scalar or iterable of scalars) – The nominal energy or energies to interpolate the energy model parameters for.
- Returns:
A pandas DataFrame, indexed by the nominal energy, with all the energy model parameters interpolated.
- Return type:
DataFrame
- Raises:
AttributeError – If the energy model has not been defined.
ValueError – If any of the given nominal energies is outside the nominal energy range of the energy model.
See also
fredtools.MonteCarlo.beamModel.interpolateBeamModelmodule-level function interpolating a beam model defined as a DataFrame.
- property interpolation: str
Returns the interpolation method used for the energy model.
- property machineModel: str | None
Returns the model of the machine used for the beam model.
- property machineName: str | None
Returns the name of the machine used for the beam model.
- property machineVendor: str | None
Returns the vendor of the machine used for the beam model.
- property materials: DataFrame
Returns the materials used in the beam model.
- property name: str | None
Returns the name of the beam model.
- property nomEnergies: tuple
Returns the nominal energies the beam model is defined for.
The nominal energies are usually the ones defined by the TPS.
- property radiationType: str
Returns the radiation type.
- property rsModel: DataFrame
Returns the range shifter model of the beam model.
- property siteName: str | None
Returns the name of the site where the beam model was created.
- property sourceToAxisDistance: float
Returns the Source-To-Axis Distance (SAD) in mm.
The Source-To-Axis Distance (SAD) describes the absolute distance of the source to the isocenter.
- property splineOrder: int
Returns the order of the spline used for the energy model.
- property spreadingDeviceDistance: Tuple[float, float]
Returns the spreading device distance in mm.
The spreading device distance describes the absolute distances of the spreading devices in the order [X, Y].
- toPickle(fileName: PathLike | str) None
Saves the beam model to a pickle file.
- Parameters:
fileName (PathLike) – The name of the file to save the beam model to. The file will be saved in binary format. If the file already exists, it will be overwritten.
GATE Monte Carlo
- fredtools.readGATE_HITSActor(fileName: PathLike | str) DataFrame
Read GATE hits data for active volume.
The function reads hits results of GATE active volume saved to numpy pickle (.npy) or root (.root) file. All the columns are read but some of them are renamed:
Edep is deposited energy in [MeV]
PDGCode is the same as PDG encoding [PDGschemeHits]
- Parameters:
fileName (path) – Path string to .npy or .root file.
- Returns:
Dataframe with the data.
- Return type:
pandas DataFrame
- Raises:
ValueError – If the file cannot be read as a numpy pickle or root file, or if the file extension is not ‘.npy’ or ‘.root’.
See also
readGATE_PSActorread GATE phase space actor data.
readGATEStatread GATE simulation statistics information from Simulation Statistic Actor output.
References
- fredtools.readGATE_PSActor(fileName: PathLike | str) DataFrame
Read GATE phase space actor data.
The function reads the results of a GATE phase space actor saved to numpy pickle (.npy) or root (.root) file. All the columns are read but some of them are renamed:
Ekine, EkinePre and EkinePost are kinetic energies in [MeV]
Edep is deposited energy in [MeV]
PDGCode is the same as PDG encoding [PDGschemePS]
The columns are sorted so that those matching the name groups ID, PDG, Ekine, Edep, DEDX and Length come first, in this order.
- Parameters:
fileName (path) – Path string to .npy or .root file.
- Returns:
Dataframe with the data.
- Return type:
pandas DataFrame
- Raises:
ValueError – If the file cannot be read as a numpy pickle or root file, or if the file extension is not ‘.npy’ or ‘.root’.
See also
readGATE_HITSActorread GATE hits data for active volume.
readGATEStatread GATE simulation statistics information from Simulation Statistic Actor output.
References
- fredtools.readGATEStat(fileNameLogOut: PathLike | str, displayInfo: bool = False) dict
Read GATE simulation statistics information from Simulation Statistic Actor.
The function reads some statistics information from the GATE Simulation Statistic Actor output [GATEStatActor].
- Parameters:
fileNameLogOut (path) – A string path to GATE Simulation Statistic Actor output.
displayInfo (bool, optional) – Displays a summary of the function results. (def. False)
- Returns:
A dictionary with the read data.
- Return type:
dict
References