betaFeedback

WorksPhysics and Astronomy

A geometry-aware framework for electromagnetic fields in GATE 10

Abstract

Objective. An increasing number of medical-physics applications require the modelling of charged-particle transport in electromagnetic (EM) fields. We aim to provide GATE 10 users with a flexible mechanism for defining such fields in Monte Carlo simulations while preserving the native Geant4 particle-transport machinery. Approach. Our framework separates the handling of coordinates from EM field evaluation. Fields are attached to geometry volumes, defined in their local frame, and represented by analytic expressions, field maps, or arbitrary Python functions. They automatically follow the position and orientation of these volumes, including in nested and dynamic geometries. We validated the framework against native Geant4 transport and tested coordinate transformations, nested volumes, and dynamic geometry. We also compared the computational cost of the three field representations. Main results. The framework reproduced the native Geant4 trajectories exactly for all tested field types with direct Geant4 counterparts. Coordinate transformations introduced only floating-point-level differences, while simulations with dynamically changing geometry reproduced the equivalent static configurations exactly. All three representations produced equivalent transport. Mapped fields added at most 18% to the single-threaded runtime of analytic fields, while Python functions required 6.9 times as much. The compiled representations scaled with the number of threads, whereas Python functions became slower as threads were added. Significance. The framework adds flexible, geometry-aware EM field definitions to GATE 10 without modifying the underlying Geant4 transport machinery, and is part of the open-source GATE 10 codebase. It also provides a basis for extending GATE 10 with additional field representations in the future.

Introduction

Monte Carlo (MC) particle-transport simulations are an essential tool in research and treatment planning in radiotherapy, providing a high-fidelity description of radiation transport and energy deposition in complex, heterogeneous media. GATE, an open-source layer built on top of the Geant4 toolkit (Agostinelli et al., [1]; Allison et al., [2, 3]), has been widely adopted across imaging and dosimetry [15, 16, 17]. The latest version, GATE 10, replaces the legacy macro interface with an accessible Python-based interface while retaining the capabilities of Geant4 [18, 9].

An increasing number of medical-physics applications require the modelling of charged-particle transport in electromagnetic (EM) fields. A prominent example is magnetic-resonance-guided radiotherapy (MRgRT), where magnetic fields deflect charged-particle trajectories and can therefore alter dose distributions: in photon therapy through the deflection of secondary electrons [13, 14], and in proton therapy through the deflection of the primary beam itself [20, 19]. Beyond MRgRT, dipoles and quadrupoles steer and focus beams in accelerators and treatment beamlines, where modelling beam losses requires charged-particle transport through these fields together with interactions in the surrounding material [10]. Electric and magnetic fields also play a central role in radiation detectors, where they act directly on the secondary charged particles that determine the detector signal. For instance, in Faraday cups used for proton dosimetry, electric and magnetic fields are applied to control secondary-electron contributions, which can limit the accuracy of the collected charge unless corrected for [22, 6]. These applications differ not only in the fields involved, but also in how fields relate to the simulation geometry: a single field can encompass an entire patient, a beamline might contain several independently positioned field-producing elements, and a detector may contain a field confined to a single component. A general and well-validated capability for EM field transport in a medical-physics Monte Carlo framework is therefore of broad interest.

Geant4 provides a general framework for defining EM fields and for tracking charged particles through them. GATE has historically provided access to a subset of these capabilities through interfaces shaped by the applications that motivated them. Uniform magnetic fields were introduced in early versions of GATE for emission-tomography studies in which a single field encompasses the whole scanner, and were subsequently used to quantify the effect of magnetic fields on positron range in PET/MR [21, 5]. Spatially varying fields were later introduced in GATE 8 through three-dimensional field maps supplied as look-up tables and interpolated over the extent of the grid [12]. These capabilities were retained in GATE 9 and used, for example, to commission a beamline with an integrated dipole for MR-guided proton and carbon-ion radiotherapy [7]. However, neither interface was ported to GATE 10 during the transition to the Python-based architecture. This created a need to reintroduce EM field transport in GATE 10, and an opportunity to provide a more general mechanism for defining fields in relation to the simulation geometry, while preserving the native Geant4 particle-transport machinery.

In this work, we introduce a framework for defining EM fields in GATE 10 and associating them directly with simulation volumes. The framework separates the handling of coordinates from EM field evaluation, allowing the same geometry-dependent coordinate treatment to be used with different field representations. Three interchangeable approaches are provided: analytic fields for closed-form descriptions, mapped fields for fields defined on regular grids, and Python functions for arbitrary user-defined spatial dependencies. Fields are defined in the local coordinate system of their associated volume and automatically follow its position and orientation, including when the geometry is nested or dynamically modified. We validate the framework against native Geant4 transport, test its behaviour under translations, rotations, and nested and dynamic geometries, and compare the computational cost of the three field representations.

Methods

Our framework integrates user-defined EM fields into GATE 10 while leaving particle transport entirely to the native Geant4 machinery. It separates the field-evaluation process into two independent components: coordinate transformation and field evaluation. § 2.1 to § 2.5 describe the formulation and implementation of this approach. Section 2.6 describes the tests used to validate the framework.

Charged-particle tracking in Geant4

A track in a Monte Carlo simulation advances in discrete transport steps. The transport step length is set by the particle–medium interaction properties and truncated at geometric boundaries, so that energy depositions are assigned to the correct volume and cross-sections are updated when an interface is crossed.

When a charged particle travels through a region of space containing an EM field, its trajectory is bent by the Lorentz force, according to the equation of motion

drds=p∣p∣,dpds=q∣p∣(p×B+∣p∣vE)(1)\frac{d\mathbf{r}}{ds} = \frac{\mathbf{p}}{\lvert\mathbf{p}\rvert}, \qquad\frac{d\mathbf{p}}{ds} = \frac{q}{\lvert\mathbf{p}\rvert}\left(\mathbf{p} \times\mathbf{B} + \frac{\lvert\mathbf{p}\rvert}{v}\mathbf{E}\right) \tag*{(1)}

where r\mathbf{r} is the position vector, p\mathbf{p} the momentum vector, ss the path length, qq the charge, vv the speed, B\mathbf{B} the magnetic field, and E\mathbf{E} the electric field. Accordingly, Geant4 replaces the straight-line transport step by a numerical integration of (1), generally using an adaptive Runge–Kutta integration method. This subdivides the transport step into integration substeps, whose length is adapted to keep the integration error within a prescribed tolerance. Each substep evaluates the right-hand side of (1) at several intermediate points, one per stage of the integration method. Geant4 then approximates the resulting curved path by a series of straight segments, or “chords”, which is what allows the geometry navigator to find boundary intersections. A candidate intersection is finally refined to within a user-defined tolerance.

Geant4 performs this transport through a chain of cooperating classes [8 Sec. 4.3]. An equation of motion supplies the right-hand side of (1). An integration stepper advances the state by one integration substep and estimates the local error, and an integration driver adapts the substep length to keep that error within tolerance. A chord finder locates boundary intersections using the chord approximation. Finally, a field manager binds all the classes above together with the field object, which holds the field definition. The field object exposes this definition through a single method, GetFieldValue(), which receives a query point in world coordinates and returns the field vector at that point, also in world coordinates. This method is called once per integration stage, so a single transport step may trigger several field queries.

The field manager is attached to a logical volume, the reusable template describing the shape of a solid and its material, which may be instantiated as one or more physical volumes, each being a placement of that template in the simulation geometry, thus carrying its own local coordinate frame. A single field object therefore serves every placement of its host logical volume at once.

Two families of numerical parameters govern the tracking accuracy. Table 1 lists them, together with their default values as implemented in GATE 10, which are inherited from Geant4 11.4.2. The first family controls the numerical integration of (1), and hence the stepper and the integration driver; the second controls the intersection of the curved trajectory with volume boundaries, and hence the chord finder. All of them are exposed to the user, so they can be tuned to the needs of a particular simulation.

Quantity controlledGATE 10 keywordDefault value
Integration of the equation of motion
Numerical method used to integrate (1)stepperaDormandPrince745
Integration substep length below which the accuracy requirement is no longer enforcedstep_minimum10−210^{-2} mm
Position error accepted over one transport step, from which the relative tolerance ε\varepsilon is deriveddelta_one_step10−210^{-2} mm
Lower bound on ε\varepsilonmin_epsilon_step5×10−55 \times10^{-5}
Upper bound on ε\varepsilonmax_epsilon_step10−310^{-3}
Intersection with volume boundaries
Maximum sagitta between a chord and the true curved pathdelta_chord0.25 mm
Accuracy of the computed boundary-crossing pointdelta_intersection10−310^{-3} mm

Table 1. User-exposed parameters controlling the integration of the equation of motion and the intersection of the curved trajectory with volume boundaries, with their default values in GATE 10.

The tolerance required from the integration is expressed as a relative bound ε\varepsilon, computed once per transport step as the ratio of delta_one_step to the proposed transport step length, and then clamped to [min_epsilon_step, max_epsilon_step]. Within that transport step, the integration driver estimates the local error of each substep, compares it with ε\varepsilon, and subdivides the substep until the estimate is below tolerance. To avoid unbounded subdivisions, the accuracy requirement is relaxed for substeps shorter than step_minimum.

The sagitta of each chord, i.e. the maximum distance between the chord and the arc it replaces, is bounded by delta_chord. Once a candidate crossing has been found, delta_intersection sets how precisely the crossing point is calculated.

Of the machinery described above, only the field object depends on how a field is defined; every other component is generic. Therefore, GetFieldValue() is the single interface through which a field definition can enter Geant4 transport.

Implementation design

Our framework intervenes at a single point of the chain described above: it overrides GetFieldValue() in the field object and leaves the rest of the tracking machinery unchanged. The equation of motion, integration stepper, integration driver, and chord finder are therefore the native Geant4 ones, and any field defined through our framework is transported exactly as a native Geant4 field would be.

Three design goals shaped what happens inside the override. First, the user should define a field in the natural local frame of the volume that hosts it, while Geant4 queries it in world coordinates. Second, common fields with a closed form and fields supplied as field maps should be evaluated entirely in compiled code, since the field is queried at every stage of every integration substep, which makes field evaluation one of the most frequently executed operations in a simulation. Third, when neither of these cases applies, the user should still be able to supply the field as an ordinary Python function that encodes an arbitrary spatial dependence.

The override therefore separates coordinate handling from field evaluation. Coordinate handling is the same for every field, whereas field evaluation depends on how the field was defined, so we delegate it to an interchangeable component, which we call a field provider.

Figure 1 illustrates the resulting design. § 2.3 describes the change of coordinates, § 2.4 covers the three field providers, and § 2.5 then presents the user-facing Python interface.

The coordinate pipeline

The first part of the override transforms the query from the world frame used by Geant4 to the local frame of the volume to which the field is attached. We denote this query point in the world frame by pw\mathbf{p}_{w}, and the corresponding position in the local frame of the host volume by pℓ\mathbf{p}_{\ell}. Once the host placement has been identified, the point pw\mathbf{p}_{w} is transformed to its local frame to obtain pℓ\mathbf{p}_{\ell}. The field is then evaluated by the corresponding provider as Fℓ=f(pℓ)\mathbf{F}_{\ell}=f(\mathbf{p}_{\ell}), where Fℓ\mathbf{F}_{\ell} is the field

vector in the local frame. The result is transformed back to the world frame, giving Fw\mathbf{F}_{w}, which is returned to Geant4. Because this coordinate handling is independent of the field definition, it is implemented once in a C++ class template shared by all field providers.

The host placement is resolved from Geant4’s navigation history. A physical volume is placed inside a mother volume, of which it is a daughter, at its own position and orientation in the mother’s frame, so the geometry is a tree rooted at the world, the volume containing all others. The transform from world coordinates to the local frame of any physical volume is the composition of the transforms along the chain of ancestors linking it to the world. Geant4 maintains exactly that chain as a track advances through the geometry: the navigator records the physical volumes from the world down to the volume currently occupied by the track. This chain is the navigation history of the track, and each of its levels stores the corresponding physical volume and its world-to-local transform. At each field query, the chain is searched from the deepest level towards the world until the physical volume whose logical volume matches the field’s host logical volume is found. Its stored transform is used to transform pw\mathbf{p}_{w} to pℓ\mathbf{p}_{\ell}. After evaluating the provider, the inverse rotation is applied to Fℓ\mathbf{F}_{\ell} to obtain Fw\mathbf{F}_{w}.

A field defined for a host logical volume is inherited by its daughter volumes unless a daughter defines a field of its own. Thus, a track inside a daughter without its own field is governed by the field of the nearest ancestor to which a field is attached. Since the field is evaluated in the host volume’s local frame, its orientation remains defined relative to that volume rather than the daughter containing the track. A rotation of the host volume therefore rotates the field together with the volume, while preserving its orientation relative to the host throughout its daughters.

This mechanism also supports dynamic geometry in GATE 10, where a simulation is executed as a sequence of runs between which dynamic actors may translate or rotate volumes [18]. Because the navigation history is rebuilt from the active geometry at the beginning of each run, the transform retrieved during field evaluation automatically reflects the placement of the host volume for the current run.

Field providers

The evaluation of the field in local coordinates is supplied by a field provider (Figure 1, bottom band). Three providers are available, corresponding to the three ways in which a user may define a field: as a closed-form analytic expression, as a tabulated field map, or as an arbitrary Python function. All three expose the same evaluation interface to the coordinate pipeline, while differing in how they represent and evaluate the field internally. The data the user supplies to configure them is covered in § 2.5.

Framework for Geant4 and GATE field evaluation

Figure 1. The framework is a single override of one Geant4 method, GetFieldValue(). A field is registered by attaching a field manager to a logical volume (top), so one field object serves every physical placement of that volume. The field manager owns the chord finder, integration driver, stepper and equation of motion. Field queries are emitted once per integration stage of each integration substep. That is the only point at which the field definition enters the tracking machinery. The GATE field object (middle) derives from the corresponding Geant4 field class and overrides GetFieldValue(), wrapping the evaluation in the shared coordinate pipeline. The evaluation of the field in local coordinates is supplied by one of three interchangeable field providers, exposed to the user as eleven concrete types (bottom).

Analytic fields. The analytic provider represents fields for which a common closed form is available. We implement uniform magnetic and electric fields, ideal magnetic quadrupoles and sextupoles, and a uniform EM field. The first four are taken from the Geant4 catalogue of pre-defined field objects, while the last is provided by GATE. At runtime, the provider delegates field evaluation to the corresponding compiled field object. This provider therefore introduces little overhead, making analytic fields the fastest option, at the cost of being restricted to the available closed-form implementations.

Mapped fields. The mapped provider represents fields that are known numerically, such as the output of a finite-element solver or a measured field map. A mapped field is defined by a regular Cartesian grid of nodes, each carrying a field vector, tabulated in the local frame of the host volume. At setup, the Python layer derives the grid origin and spacing from the node positions and transfers the data to the C++ layer, where each field component is stored as a contiguous array in lexicographic node order. A query can therefore be evaluated through an index computation followed by interpolation of the neighbouring nodes. Two interpolation schemes are available. Nearest-neighbour interpolation returns the field of the closest node. Trilinear interpolation returns the weighted average of the eight nodes of the enclosing cell,

F(p)=∑c=07wc(p)Fc,∑cwc=1,(2)\mathbf{F}(\mathbf{p}) = \sum_{c=0}^{7} w_c(\mathbf{p}) \mathbf{F}_c, \qquad\sum_c w_c = 1, \tag*{(2)}

with each weight wcw_c being the product of the fractional coordinates, or their complements, within the cell. Outside the grid, the query point is clamped to the nearest face, edge or vertex, so that the field is held constant beyond the map rather than extrapolated.

Callback fields. The callback provider allows the field to be defined by an arbitrary Python function of the local coordinates of the query point. The underlying field object is created using the pybind11 trampoline pattern that GATE 10 uses for callbacks from Geant4 [9]. Any field expressible in Python is therefore admissible, which makes this a particularly useful provider for prototyping and exploratory work. This flexibility comes at a substantial runtime cost: each query crosses the C++/Python boundary and acquires the global interpreter lock, serialising field evaluation across worker threads even in a multi-threaded simulation. We quantify this cost in § 3.

The provider choice also affects the ability to serialise a simulation for archiving and replay. GATE 10 serialises simulations to JSON [18], allowing the simulation configuration to be stored and reconstructed. Analytic and mapped fields can be represented in this format, whereas callback fields cannot, because arbitrary Python functions do not have a canonical JSON representation. Consequently, simulations containing callback fields cannot currently be fully serialised and replayed from the JSON configuration alone, and an exception is raised when attempting to do so.

The user-facing Python interface

At the Python level, a field is an ordinary simulation object, inheriting from the GATE 10 GateObject base class [9]. The user creates a field with a name, configures it through attributes, and attaches it to a volume with volume.add_field(...). A logical volume can have at most one attached field, reflecting the fact that Geant4 binds a single field manager to a logical volume. Electric and magnetic fields that coexist in the same region are therefore described by one joint EM field object rather than by two separate fields.

A field attached to a logical volume automatically applies to all of its physical placements, with the field evaluated in the local frame of each placement through the coordinate pipeline of § 2.3. Conversely, the same Python field object can be attached to multiple distinct volumes, allowing one field definition to be reused throughout the geometry. At setup, GATE creates the corresponding internal field object for each attachment. Integration and boundary tolerances, i.e. the parameters of Table 1, are configured as field attributes along with the field data.

The three providers of § 2.4 are exposed to the user as eleven concrete classes, listed in Table 2. The table summarises the available field types and the field data required to configure each of them. Examples for all possible configurations are provided in the GATE user guide [11].

Python classField data supplied by the user
Analytic provider
UniformMagneticFieldConstant field vector
UniformElectricFieldConstant field vector
UniformElectroMagneticFieldConstant electric and magnetic field vectors
QuadrupoleMagneticFieldField gradient
SextupoleMagneticFieldField gradient
Mapped provider
MappedMagneticFieldField sampled on a Cartesian grid, plus interpolation scheme
MappedElectricFieldField sampled on a Cartesian grid, plus interpolation scheme
MappedElectroMagneticFieldElectric and magnetic fields sampled on independent Cartesian grids, plus interpolation scheme
Callback provider
CustomMagneticFieldPython function of position returning (Bx,By,Bz)(B_x, B_y, B_z)
CustomElectricFieldPython function of position returning (Ex,Ey,Ez)(E_x, E_y, E_z)
CustomElectroMagneticFieldPython function of position returning (Bx,By,Bz,Ex,Ey,Ez)(B_x, B_y, B_z, E_x, E_y, E_z)

Table 2. The eleven field types available through the GATE 10 Python interface, and the data the user supplies for each. All field data is expressed in the local frame of the host volume.

For analytic fields, the configuration consists of the parameters of the corresponding closed-form expression. Uniform fields are specified by their field vector, while quadrupoles and sextupoles by their field gradient.

Listing 1 shows a minimal example: a uniform magnetic field defined in a box. The three steps it follows, creating the field, setting its data and tolerances, and attaching it to a volume, are the same for every class of Table 2; only the field data differs.

import opengate as gate
from opengate.geometry import fields

sim = gate.Simulation()
tesla = gate.g4_units.tesla
cm = gate.g4_units.cm

box = sim.add_volume("Box", "magnet")
box.size = [50 * cm, 50 * cm, 50 * cm]
box.material = "G4_Galactic"

field = fields.UniformMagneticField(name="B")
field.field_vector = [0, 1 * tesla, 0]  # in the local frame of ‘box‘
field.stepper = "ClassicalRK4"
field.delta_chord = 1e-3 * cm

box.add_field(field)

Listing 1. Minimal example: a uniform magnetic field defined in the local frame of a volume.

Mapped fields are configured by supplying the field data through the field_matrix attribute as an N×6N \times6 matrix whose columns are the three node coordinates and the three field components, all expressed in the local frame of the host volume. The interpolation scheme is selected through the interpolation attribute. For a mapped EM field, the electric and magnetic components are supplied separately through the field_matrix_E and field_matrix_B attributes, whose grids can be independent of each other. The supplied matrices are validated at setup: the spacing must be uniform along each axis, every combination of sampled coordinates must be present, and each axis must carry at least two distinct values. A matrix that violates any of these constraints raises an exception before the simulation starts. Tabulated field data is normally produced by a field solver or by a measurement, so it is loaded from a file rather than written inline, and the field is then configured and attached exactly as in Listing Listing 1.

Callback fields are configured by assigning a Python function to the field_function attribute. The function receives the local coordinates of the query point, and returns the field components in the local frame. Purely electric or magnetic fields return three components, while a combined EM field returns six, the first three being the magnetic components and the last three the electric ones. Listing 2 illustrates this signature and return convention with the field of an infinite straight wire.

mm = gate.g4_units.mm

a = 10 * mm
B_a = 0.1 * tesla

def wire_field(x, y, z):
    rho2 = x**2 + y**2
    if rho2 == 0.0:
        return [0.0, 0.0, 0.0]
    return [-B_a * a * y / rho2, B_a * a * x / rho2, 0.0]

field = fields.CustomMagneticField(name="wire")
field.field_function = wire_field
box.add_field(field)

caption: Listing 2. A custom field defined as a Python function of the local coordinates: the field of an infinite straight wire along the local zz axis, normalised to BaB_a at a radius aa.

Validation tests

We validate the framework with three sets of tests targeting its compatibility with Geant4, its handling of coordinate transformations and dynamic geometry, and the equivalence of the three different field providers. Additionally, we quantify the computational cost of each provider. All tests track 100 MeV protons through the fields in vacuum. Vacuum is chosen because in the absence of interactions with matter, the trajectories are determined by the field alone, so that any difference between two simulations can be attributed to the field implementation rather than to stochastic interactions.

Unless otherwise stated, all tests use the same baseline geometry, phase-space input, physics list and tracking setup. The geometry consists of a 4 m cubic vacuum world containing a 500 mm vacuum cube centred at the origin, which serves as the host volume for the field. The beam consists of 10 000 protons with 100 MeV kinetic energy, emitted from a disk of 50 mm radius with positions distributed uniformly across the disk and directions distributed uniformly within a cone of 10° half-angle. In vacuum, each trajectory is fully determined by the initial position and direction of the proton and by the field, so no statistical averaging is needed. The protons start from different positions and directions so that their trajectories sample a large part of the field region, giving between 1.7×1061.7 \times10^{6} and 2.1×1062.1 \times10^{6} compared step points per pair of simulations. The phase-space source is located 250 mm upstream of the host volume. All simulations use the QGSP_BERT_EMV reference physics list. Unless otherwise specified, transport steps inside the host volume are limited to 3 mm, and all simulations are run single-threaded with the same random seed.

All simulations were run on compute nodes of the Merlin7 cluster at the Paul Scherrer Institute, each equipped with two 64-core AMD EPYC 7742 processors and running SUSE Linux Enterprise Server 15 SP6. They used the GATE 10 development version at commit 0bc96f8 (following release 10.1.1) and Geant4 11.4.2 built with multithreading support, both compiled in release mode with GCC 7.5.0, together with CPython 3.14.3 in its standard build. The scripts of all tests are available in Ballesterо Ribó (2026).

For trajectory-equivalence tests, the trajectories of the primary protons are compared at each recorded step point using the differences in particle position, direction, and kinetic energy. For each quantity, the maximum difference across all step points and primaries is reported as the maximum residual. Trajectories are considered bitwise identical when every recorded double-precision quantity agrees exactly, i.e. all residuals are zero.

Equivalence with native Geant4. We first test whether the framework preserves the native Geant4 tracking. A bare Geant4 application is compared with a GATE 10 simulation using the framework for the four field types with built-in Geant4 counterparts: uniform magnetic, ideal quadrupole, ideal sextupole, and uniform electric fields. The host volume is placed at the world origin without rotation, reducing the coordinate transformation pipeline to the identity and isolating the field evaluation interface.

The two applications use the same physics list and tracking configuration, including the parameters of Table 1. Both applications are built against the same Geant4 installation with the same compiler and optimisation flags, and are run single-threaded on the same machine.

The four fields are Buniform=(0.1,0.5,−0.2) T\mathbf{B}_{\mathrm{uniform}} = (0.1, 0.5, -0.2)\ \mathrm{T}, Bquadrupole=g(y,x,0)\mathbf{B}_{\mathrm{quadrupole}} = g(y,x,0) with g=5 T/mg = 5\ \mathrm{T}/\mathrm{m}, Bsextupole=g(xy,(x2−y2)/2,0)\mathbf{B}_{\mathrm{sextupole}} = g(xy,(x^2-y^2)/2,0) with g=5 T/m2g = 5\ \mathrm{T}/\mathrm{m}^2, and Euniform=(0.1,0.5,−0.2) MV/m\mathbf{E}_{\mathrm{uniform}} = (0.1,0.5,-0.2)\ \mathrm{MV}/\mathrm{m}.

Coordinate handling and dynamic geometry. We next test whether a field defined in the local coordinate system of a host volume is preserved under geometry transformations and dynamic motion. All tests use an ideal magnetic quadrupole with gradient g=5 T/mg = 5\ \mathrm{T}/\mathrm{m} defined in the local coordinate system of the host volume.

First, the host volume is placed at the world origin in one configuration, and then it is translated by (60,−40,0) mm(60,-40,0)\ \mathrm{mm} and rotated by (30,40,50)∘(30,40,50)^\circ around the xx, yy, and zz axes in a second configuration. The particle source undergoes the same rigid transformation, so the two configurations represent the same physical situation in different world frames. The resulting trajectories should therefore be related by the applied rigid transformation. The transformed trajectory is brought back to the reference frame before calculating the residual.

Second, a spherical daughter volume of radius 100 mm100\ \mathrm{mm} is placed at the centre of the host volume. The daughter is rotated by (20,−35,45)∘(20,-35,45)^\circ in one configuration and left unrotated in the other. Because the spherical boundary is invariant under rotation and the daughter carries no field of its own, the field should be unchanged. This test therefore isolates the effect of the additional navigation level between the particle and the field host introduced by the daughter volume.

Finally, the host volume is translated and rotated over three consecutive runs using a dynamic actor. The resulting trajectories are compared with those obtained from three static simulations representing the same placements, while the beam remains fixed. This test verifies that the field follows the physical placement of its host volume when the geometry is modified between runs.

Provider equivalence and cost. We finally evaluate the equivalence and computational cost of the three field providers. For the equivalence test, an ideal magnetic sextupole B=g(xy,(x2−y2)/2,0)\mathbf{B} = g(xy,(x^2-y^2)/2,0) with g=1×10−4 T/mm2g = 1 \times10^{-4}\ \mathrm{T}/\mathrm{mm}^2 is defined in the local frame of the host volume. A sextupole was selected because its quadratic dependence on position cannot be reproduced exactly by trilinear interpolation, unlike uniform and quadrupole fields. The analytic provider uses the compiled closed form, while the callback provider evaluates a Python function returning the same expression. The mapped provider samples the field on Cartesian grids of 1263126^3, 2513251^3 and 5013501^3 nodes spanning the host volume, corresponding to node spacings of 4 mm4\ \mathrm{mm}, 2 mm2\ \mathrm{mm} and 1 mm1\ \mathrm{mm}, with both nearest-neighbour and trilinear interpolation tested at every spacing. Trajectory residuals are evaluated against the analytic provider, which is taken as the reference.

For the runtime measurements, the phase-space source is generated with 1 000 000 primaries using the same energy, spatial, and angular distributions as the baseline source. The field is the uniform magnetic field B=(0.1,0.5,−0.2) T\mathbf{B} = (0.1,0.5,-0.2)\ \mathrm{T}, which the mapped provider samples on a grid of 1003100^3 nodes spanning the host volume. The wall-clock time of the event loop, which excludes the initialisation of geometry, physics, fields, and worker threads, is measured using one, two, four, and eight worker threads, with five independent runs for each configuration. The median runtime and the full range of the five runs are recorded for each provider. The number of primaries is chosen so that the tracking time remains well above the fixed per-run overhead still included in the measurement.

Each run of one provider at all four thread counts was executed as a single job with exclusive access to a compute node, so that no other workload shared the node during the measurement. The five runs of each provider were executed on different nodes, so the reported ranges include node-to-node variation. Each job first executed a discarded single-threaded simulation of 200 primaries to warm the file-system caches.

Results

Compatibility with native Geant4

The residuals of every trajectory-equivalence test are collected in Table 3. For the four field types with native Geant4 counterparts, the GATE 10 trajectories were bitwise identical to the corresponding bare Geant4 ones, with exactly zero residuals in position, direction, and kinetic energy for the uniform magnetic field, quadrupole, sextupole, and uniform electric field.

Maximum residuals of the trajectory-equivalence tests, taken over every recorded step point of every primary. For the provider-equivalence tests, the analytic provider serves as the reference and the field is an ideal sextupole of gradient 1×10−4 T/mm21 \times10^{-4}\ \mathrm{T}/\mathrm{mm}^{2}, which neither interpolation scheme reproduces exactly; the mapped provider is therefore listed once per grid, the node spacings hh of 4 mm, 2 mm and 1 mm corresponding to 126, 251 and 501 nodes per axis across the host volume. These tests use the baseline geometry, source and tracking setup. A residual of exactly 0 denotes bitwise identity of every recorded quantity.

TestConfigurationmax Δr\Delta r [mm]max Δθ\Delta\theta [rad]max ΔEk\Delta E_k [MeV]
Native Geant4Uniform B\mathbf{B}000
Native Geant4Quadrupole B\mathbf{B}000
Native Geant4Sextupole B\mathbf{B}000
Native Geant4Uniform E\mathbf{E}000
Coordinate transformsTranslation + rotation1.07×10−121.07 \times10^{-12}3.01×10−153.01 \times10^{-15}0
Coordinate transformsNested volume1.64×10−121.64 \times10^{-12}1.00×10−151.00 \times10^{-15}0
Coordinate transformsDynamic geometry000
Provider equivalenceMapped, nearest, h=4h = 4 mm1.205.87×10−35.87 \times10^{-3}0
Provider equivalenceMapped, nearest, h=2h = 2 mm3.99×10−13.99 \times10^{-1}1.78×10−31.78 \times10^{-3}0
Provider equivalenceMapped, nearest, h=1h = 1 mm1.69×10−11.69 \times10^{-1}7.88×10−47.88 \times10^{-4}0
Provider equivalenceMapped, trilinear, h=4h = 4 mm1.15×10−21.15 \times10^{-2}4.94×10−54.94 \times10^{-5}0
Provider equivalenceMapped, trilinear, h=2h = 2 mm2.66×10−32.66 \times10^{-3}1.15×10−51.15 \times10^{-5}0
Provider equivalenceMapped, trilinear, h=1h = 1 mm5.58×10−45.58 \times10^{-4}2.39×10−62.39 \times10^{-6}0
Provider equivalenceCallback000

Table 3.

Coordinate transformations and dynamic geometry

The combined translation and rotation test yielded a maximum position residual of 1.07×10−121.07 \times10^{-12} mm and a maximum directional residual of 3.01×10−153.01 \times10^{-15} rad, while the nested-volume test yielded 1.64×10−121.64 \times10^{-12} mm and 1.00×10−151.00 \times10^{-15} rad, respectively. The trajectories of the dynamic-geometry test were bitwise identical to the corresponding static configurations. No difference in kinetic energy was observed in any of the tests. The non-zero residuals were at the floating-point precision level and did not correspond to a physically relevant difference in the tested trajectories.

Provider equivalence and cost

The three field providers also reproduced equivalent transport for the common sextupole field. The callback provider, which evaluates the same closed form in Python, produced trajectories bitwise identical to those of the analytic provider in position, direction and kinetic energy. The mapped provider converged towards the analytic reference as the grid was refined: the maximum position residual of trilinear interpolation fell from 1.15×10−21.15 \times10^{-2} mm at a node spacing of 4 mm to 5.58×10−45.58 \times10^{-4} mm at 1 mm, and that of nearest-neighbour interpolation from 1.20 mm to 1.69×10−11.69 \times10^{-1} mm. At equal resolution, trilinear interpolation was therefore between 105 and 304 times more accurate than nearest-neighbour interpolation. No difference in kinetic energy was observed in any configuration, as expected for a purely magnetic field.

The cost of the three providers is shown in Figure 2. Single-threaded, the analytic provider tracked 1 000 000 primaries in 241.4 s (range 240.1 s to 247.8 s). Relative to it, the mapped provider required 9.9 % more runtime with nearest-neighbour interpolation and 18.1 % more with trilinear interpolation, while the callback provider required 6.87 times as much. The analytic provider remained the fastest at every thread count.

Figure 2. Cost of the three field providers for the tracking of 1 000 000 primaries, shown as the median of five runs, with bands and error bars showing the full range of the runs. (a) Wall-clock time of the tracking phase against the number of worker threads. (b) The same data as speedup with respect to the single-threaded run of the same provider.

The providers differed also in their multi-threaded behaviour. The compiled providers continued to scale over the whole range tested, reaching speedups of 2.21 to 2.24 at two worker threads, 4.30 to 4.37 at four and 7.56 to 7.74 at eight. The callback provider instead became slower as threads were added, requiring 8.2 times its single-threaded runtime at two threads and 8.7 times at eight threads. Its runtime relative to the analytic provider consequently increased from 6.9 to 455.

Discussion

The proposed framework integrates EM fields into the GATE geometry interface without modifying the underlying Geant4 particle transport. The framework intervenes only at the field-evaluation interface exposed by Geant4, while the equation of motion, numerical integration and boundary-intersection machinery remain native Geant4 components. The bitwise agreement obtained for field types with native Geant4 counterparts demonstrates that this additional GATE layer does not alter the underlying transport. At the same time, separating coordinate handling and field evaluation from the transport machinery allows field representations to be extended independently. This provides a stable integration point with Geant4, so that changes to the underlying tracking algorithms do not require a separate reimplementation on the GATE side.

Another key aspect is that fields can be defined relative to the physical component to which they belong rather than in the global simulation frame. This is particularly relevant for geometries containing EM elements with their own position and orientation, since the same field definition can then be reused for different physical placements. The validation results show that this association is preserved through translations, rotations and additional levels of geometry nesting, and that it remains valid when the geometry is modified between simulation runs. This naturally couples the field definition to the geometry and avoids requiring users to manually transform field definitions when EM components are repositioned or rotated. The same mechanism also allows a field attached to a logical volume to be reused by multiple physical placements, while retaining the local orientation of each placement.

The three-provider architecture provides users with flexibility in how EM fields are defined while allowing the computational cost of field evaluation to be tailored to the intended application. Analytic fields provide the lowest evaluation cost when a suitable closed form is available. Mapped fields extend this approach to arbitrary spatial distributions supplied on regular grids: in the validation tests, the additional cost was modest when compared with the analytic provider, including when trilinear interpolation was used. They therefore provide a practical option for production simulations in which fields are obtained from numerical solvers or measurements. Callback fields offer the greatest flexibility, allowing arbitrary spatial dependencies to be expressed directly in Python. This flexibility, however, comes at a substantially higher computational cost, which scales poorly with the number of worker threads, a behaviour consistent with field evaluation being serialised by the global interpreter lock and with contention for that lock. Callback fields are therefore best suited for prototyping and exploratory work, while analytic and mapped fields are more appropriate for computationally intensive simulations.

The validation tests were designed to test the principal architectural properties of the framework rather than to exhaustively cover all possible field definitions and geometries. The trajectory tests included representative native Geant4 field types, rigid transformations, nested volumes and dynamic geometry, while the provider tests demonstrated equivalent transport for a common field and quantified the computational cost of the different implementations. All tests were performed in vacuum, so that the field was the only influence on the trajectories. This choice does not limit the results to transport in vacuum: the framework only supplies the field value requested by the Geant4 integrator, while energy loss, scattering and the production of secondary particles in matter remain handled by the unmodified Geant4 physics models, as in any Geant4 simulation with a field. The performance measurements were obtained for a controlled workload and should therefore not be interpreted as universal timing benchmarks: the relative cost of field evaluation will depend on field complexity, the number of field queries, the tracking configuration and the materials traversed. These limitations should be considered when selecting a provider for a particular application.

Conclusion

We introduced a framework for defining EM fields in GATE 10 and associating them directly with simulation volumes while retaining the native Geant4 particle-transport machinery. The framework separates geometry-dependent coordinate handling from field evaluation and provides a common interface for analytic, mapped, and Python callback fields. The validation tests demonstrated compatibility with native Geant4 tracking, correct behaviour under translations, rotations, nested volumes, and dynamic geometry, and equivalent transport across the available field providers. Analytic and mapped fields provide efficient options for production simulations, while callback fields offer greater flexibility for prototyping and exploratory applications. Our contribution has been included in the GATE 10 codebase, and is therefore open source and publicly available to researchers. The developed architecture also allows additional field representations to be introduced without modifying the transport or coordinate-handling layers, providing an extensible basis for EM field transport in GATE 10. By coupling fields to the simulation geometry, the framework is well suited to medical-physics applications that involve charged-particle transport in EM fields, for example simulations of MRgRT, of treatment beamlines and rotating gantries containing several independently positioned magnets, or of detectors with fields confined to individual components, such as Faraday cups for proton dosimetry.

Acknowledgments

The authors would like to thank Clémence Gentner for her collaboration in the earliest prototypes of this framework. We also thank the GATE community and coordinators for their support and feedback during the development process, as well as for their open and inclusive approach to research software development.

Funding

This research was funded in whole or in part by the Swiss National Science Foundation (SNSF) [grant number 10002635]. For the purpose of Open Access, a CC BY public copyright licence is applied to any Author Accepted Manuscript (AAM) version arising from this submission.

Author contributions

  • Marc Ballestero Ribó: Conceptualisation, Methodology, Software, Validation, Formal analysis, Investigation, Visualisation, Writing – original draft.

  • Carla Winterhalter: Conceptualisation, Validation, Writing – review & editing.

  • Antony John Lomax: Conceptualisation, Resources, Writing – review & editing, Project administration.

  • Sairos Safai: Conceptualisation, Resources, Writing – review & editing, Project administration, Funding acquisition.

Data availability

The framework described in this article is part of GATE 10, which is open source and publicly available at OpenGATE GitHub repository. It was contributed through pull requests #1003, #1012, #1112 and #1130, all included in commit 0bc96f8, which was used for this work. Documentation and examples are available in the GATE 10 user guide. The code of the validation tests and the results reported in this article, including the data needed to reproduce Table 3 and Figure 2, will be made publicly available at https://doi.org/10.5281/zenodo.23685931 [4].

References

  1. [1]Agostinelli, S. et al. (2003). “Geant4—a simulation toolkit”. In: Nuclear Instruments and Methods in Physics Research Section A 506.3, pp. 250–303.DOI
  2. [2]Allison, J. et al. (2006). “Geant4 developments and applications”. In: IEEE Transactions on Nuclear Science 53.1, pp. 270–278.
  3. [3]Allison, J. et al. (2016). “Recent developments in Geant4”. In: Nuclear Instruments and Methods in Physics Research Section A 835, pp. 186–225.
  4. [4]Ballestero Ribó, M. (2026). Validation tests for the GATE 10 electromagnetic field framework. Version 1.0.0. Zenodo. https://doi.org/10.5281/zenodo.23685931.
  5. [5]Barati, S., M. Enferadi, S. Sarkar, and P. Geramifar (2021). “The effect of magnetic field strength on the positron range and projected annihilation artifact in integrated PET/MR systems: A GATE Monte Carlo study”. In: Medical Physics 48.12, pp. 7712–7724.DOI
  6. [6]Ehwald, J., M. Togno, A. J. Lomax, D. C. Weber, S. Safai, and C. Winterhalter (2023). “Detailed Monte Carlo characterization of a Faraday cup for proton therapy”. In: Medical Physics 50.9, pp. 5828–5841.
  7. [7]Fuchs, H., F. Padilla-Cabal, B. M. Oborn, and D. Georg (2023). “Commissioning a beam line for MR-guided particle therapy assisted by in silico methods”. In: Medical Physics 50.2, pp. 1019–1028.DOI
  8. [8]Geant4 Collaboration (2025). Geant4 Book For Application Developers. Version 11.4. CERN. URL: https://geant4-userdoc.web.cern.ch/UsersGuides/ForApplicationDevelopers/fo/BookForApplicationDevelopers.pdf (visited on 2026-09-01).
  9. [9]Krah, N. et al. (2026). “GATE 10 Monte Carlo particle transport simulation: II. Architecture and innovations”. In: Physics in Medicine & Biology 71.1, p. 015043.
  10. [10]Nevay, L. J. et al. (2020). “BDSIM: An accelerator tracking code with particle–matter interactions”. In: Computer Physics Communications 252, p. 107200.DOI
  11. [11]OpenGATE Collaboration (2026). GATE User Guide. URL: https://opengate-python.readthedocs.io/en/master/user_guide/user_guide_fields.html (visited on 2026-09-09).
  12. [12]Padilla-Cabal, F., J. A. Fragoso, A. F. Resch, D. Georg, and H. Fuchs (2020). “Benchmarking a GATE/Geant4 Monte Carlo model for proton beams in magnetic fields”. In: Medical Physics 47.1, pp. 223–233.
  13. [13]Raaijmakers, A. J. E., B. W. Raaymakers, and J. J. W. Lagendijk (2005). “Integrating a MRI scanner with a 6 MV radiotherapy accelerator: dose increase at tissue–air interfaces in a lateral magnetic field due to returning electrons”. In: Physics in Medicine & Biology 50.7, pp. 1363–1376.pubmed.ncbi.nlm.nih.gov/15798329
  14. [14]Raaijmakers, A. J. E., B. W. Raaymakers, and J. J. W. Lagendijk (2008). “Magnetic-field-induced dose effects in MR-guided radiotherapy systems: dependence on the magnetic field strength”. In: Physics in Medicine & Biology 53.4, pp. 909–923.DOI
  15. [15]Sarrut, D. et al. (2014). “A review of the use and potential of the GATE Monte Carlo simulation code for radiation therapy and dosimetry applications”. In: Medical Physics 41.6, p. 064301.DOI
  16. [16]Sarrut, D. et al. (2021). “Advanced Monte Carlo simulations of emission tomography imaging systems with GATE”. In: Physics in Medicine & Biology 66.10, 10TR03.DOI
  17. [17]Sarrut, D. et al. (2022). “The OpenGATE ecosystem for Monte Carlo simulation in medical physics”. In: Physics in Medicine & Biology 67.18, p. 184001.DOI
  18. [18]Sarrut, D. et al. (2026). “GATE 10 Monte Carlo particle transport simulation: I. Development and new features”. In: Physics in Medicine & Biology 71.1, p. 015042.
  19. [19]Schellhammer, S. M., S. Gantz, A. Lühr, B. M. Oborn, M. Bussmann, and A. L. Hoffmann (2018). “Technical Note: Experimental verification of magnetic field-induced beam deflection and Bragg peak displacement for MR-integrated proton therapy”. In: Medical Physics 45.7, pp. 3429–3434.DOI
  20. [20]Schellhammer, S. M. and A. L. Hoffmann (2017). “Prediction and compensation of magnetic beam deflection in MR-integrated proton therapy: a method optimized regarding accuracy, versatility and speed”. In: Physics in Medicine & Biology 62.4, pp. 1548–1564.DOI
  21. [21]Soultanidis, G., N. Karakatsanis, G. Nikiforidis, and G. Loudos (2011). “Study of the effect of magnetic field in positron range using GATE simulation toolkit”. In: Journal of Physics: Conference Series 317, p. 012021.DOI
  22. [22]Winterhalter, C., M. Togno, K. P. Nesteruk, F. Emert, S. Psoroulas, M. Vidal, D. Meer, D. C. Weber, A. Lomax, and S. Safai (2021). “Faraday cup for commissioning and quality assurance for proton pencil beam scanning beams at conventional and ultra-high dose rates”. In: Physics in Medicine & Biology 66.12, p. 124001.

Paper details

vlnc:W_75cmnps2
Version
v1 · latest
Published
Fresh — added to the Hub within the last 30 days
Added
License
CC BY 4.0
Usage

views · 0

downloads · 0

A view counts once per browser per day, a download each time the PDF is requested.

  • Physics and Astronomy

Not recorded for this paper

View statement
Looking for related papers…
Contents